@arcgis/portal-components 6.0.0-next.37 → 6.0.0-next.39
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/cdn/2574FNAZ.js +2 -0
- package/dist/cdn/3DOZPC3W.js +2 -0
- package/dist/cdn/{R5LNWMD4.js → 3HZI6MKD.js} +1 -1
- package/dist/cdn/{ASLKTYLX.js → 3KGSWW6B.js} +1 -1
- package/dist/cdn/{VWV2LCNA.js → 3OL7A2UC.js} +1 -1
- package/dist/cdn/3Q7UJKKN.js +2 -0
- package/dist/cdn/43A74S72.js +2 -0
- package/dist/cdn/46HNNQAD.js +2 -0
- package/dist/cdn/46MYBPSS.js +2 -0
- package/dist/cdn/{H25PBZPU.js → 47DKAGRV.js} +1 -1
- package/dist/cdn/{5VFGR7LA.js → 4CBRO7JP.js} +1 -1
- package/dist/cdn/{NLFBHNSX.js → 5M25PCH2.js} +1 -1
- package/dist/cdn/5MLBK66O.js +2 -0
- package/dist/cdn/5RBH3LGK.js +2 -0
- package/dist/cdn/5ZHNRQOW.js +2 -0
- package/dist/cdn/62TL6V4N.js +2 -0
- package/dist/cdn/{IWQ5I2DD.js → 66VV7NHO.js} +1 -1
- package/dist/cdn/{US37IXWO.js → 6AHPTR2E.js} +1 -1
- package/dist/cdn/{ZQ6SGKLT.js → 6APPSZ7E.js} +1 -1
- package/dist/cdn/{XH6RD5BO.js → 6CUXEL27.js} +1 -1
- package/dist/cdn/{6HNKQNS5.js → 6QI7DAS2.js} +1 -1
- package/dist/cdn/{324F5URQ.js → 6ZJNZZPC.js} +1 -1
- package/dist/cdn/{5CEFJTG4.js → 75CT6IMW.js} +1 -1
- package/dist/cdn/{CJ4S56BE.js → 7J22VLBO.js} +1 -1
- package/dist/cdn/7VPB6Q55.js +63 -0
- package/dist/cdn/7ZU43BL6.js +2 -0
- package/dist/cdn/A5QLPZ57.js +2 -0
- package/dist/cdn/AZTAWZI5.js +2 -0
- package/dist/cdn/{WIUFH5SJ.js → BNWJUQDF.js} +1 -1
- package/dist/cdn/{UBPCKCW2.js → BUYOYUA2.js} +1 -1
- package/dist/cdn/BX7Q3V2Y.js +43 -0
- package/dist/cdn/BXPNB7VJ.js +2 -0
- package/dist/cdn/{4Y73LE7P.js → BZEKNJUA.js} +1 -1
- package/dist/cdn/{WCZJXBW3.js → C6RUWLEJ.js} +1 -1
- package/dist/cdn/C7SNE6YG.js +2 -0
- package/dist/cdn/DENQY4OE.js +2 -0
- package/dist/cdn/DT4HGMLS.js +2 -0
- package/dist/cdn/{NYBLHT3F.js → DTGPLVZF.js} +1 -1
- package/dist/cdn/DU2R3VC4.js +2 -0
- package/dist/cdn/{RJRTGF33.js → E5HCHRAI.js} +1 -1
- package/dist/cdn/{IX4WEZZ2.js → EBL7YSRM.js} +1 -1
- package/dist/cdn/EDGE3T36.js +2 -0
- package/dist/cdn/{HBO7XTIL.js → EFMYI4L2.js} +1 -1
- package/dist/cdn/{XOM3GLYF.js → FFL2L4X5.js} +1 -1
- package/dist/cdn/{PST62OKJ.js → FIAEPK5L.js} +1 -1
- package/dist/cdn/{L25GEXL6.js → FTKSVLDI.js} +1 -1
- package/dist/cdn/{QMIVFHQE.js → G272JPUS.js} +1 -1
- package/dist/cdn/{D52TYBRX.js → GFUKRB6D.js} +1 -1
- package/dist/cdn/{ZGSAH7Z7.js → GG6U75ZA.js} +1 -1
- package/dist/cdn/{O4YFPGD5.js → GZ4ONSFV.js} +1 -1
- package/dist/cdn/{YP7T6NKR.js → HOIZXTOD.js} +1 -1
- package/dist/cdn/{DV57AOBF.js → IAMPUXPT.js} +1 -1
- package/dist/cdn/{AUM2QTBQ.js → IAWL475A.js} +1 -1
- package/dist/cdn/IGLODZPX.js +2 -0
- package/dist/cdn/{KTWSNYYZ.js → IOF72CDU.js} +1 -1
- package/dist/cdn/ITRJGXFV.js +93 -0
- package/dist/cdn/{EDQSL2P3.js → ITWLFQI4.js} +1 -1
- package/dist/cdn/{B343BOVA.js → IYICIRGI.js} +1 -1
- package/dist/cdn/{OVAOMUO3.js → JFGXTJY4.js} +1 -1
- package/dist/cdn/{5E4EL6TF.js → JIU6MBGB.js} +1 -1
- package/dist/cdn/{5Y32T5IJ.js → JTA223NH.js} +1 -1
- package/dist/cdn/KA2MXQTR.js +2 -0
- package/dist/cdn/KAK6CNI7.js +2 -0
- package/dist/cdn/{5S4JV6IY.js → KPZGBBDG.js} +1 -1
- package/dist/cdn/{M664QA6J.js → KRO5XRZ7.js} +1 -1
- package/dist/cdn/KWL2D56D.js +3 -0
- package/dist/cdn/{BRWHEYLW.js → KXVXQYIB.js} +1 -1
- package/dist/cdn/L3YOPSRB.js +135 -0
- package/dist/cdn/{QF626JXP.js → LEESUFWE.js} +1 -1
- package/dist/cdn/{CMNTOT5D.js → LGKI24ZT.js} +1 -1
- package/dist/cdn/LTD5KLLE.js +2 -0
- package/dist/cdn/{VFECPSKA.js → MB32XRI5.js} +1 -1
- package/dist/cdn/{3T3QBPC3.js → MSL36HAR.js} +1 -1
- package/dist/cdn/{ARAHDT2O.js → N3WRMPM6.js} +1 -1
- package/dist/cdn/N47MW5HI.js +9 -0
- package/dist/cdn/{G7DJPREL.js → N7XYFVOI.js} +1 -1
- package/dist/cdn/{WZFGZEQI.js → NU4K2AV3.js} +1 -1
- package/dist/cdn/{ESKKH4DE.js → ONRTCGLU.js} +1 -1
- package/dist/cdn/{WSQLSDQY.js → OPI4P6VO.js} +1 -1
- package/dist/cdn/{YYKKXL62.js → OPMM7QH5.js} +1 -1
- package/dist/cdn/{PRBP4AP6.js → OXF2WDSW.js} +1 -1
- package/dist/cdn/P3FFM322.js +2 -0
- package/dist/cdn/QAXFE5DD.js +2 -0
- package/dist/cdn/{6EMK2BU6.js → QKRLO5CJ.js} +1 -1
- package/dist/cdn/{FVHP6PFG.js → R26RBXQW.js} +1 -1
- package/dist/cdn/R6KJVAX3.js +99 -0
- package/dist/cdn/RA2NMLMP.js +2 -0
- package/dist/cdn/{365ICWHN.js → RJXIU4GH.js} +1 -1
- package/dist/cdn/{6FFYU4NI.js → RKHNP3KL.js} +1 -1
- package/dist/cdn/RR56BOTV.js +2 -0
- package/dist/cdn/RTZ2TKM5.js +2 -0
- package/dist/cdn/RX64JXHI.js +170 -0
- package/dist/cdn/{26KZUWNM.js → RXMM6CFK.js} +1 -1
- package/dist/cdn/{JA3GGSJJ.js → S4N5QMSN.js} +1 -1
- package/dist/cdn/{3CXU5CCM.js → SCLYGIHM.js} +1 -1
- package/dist/cdn/{PJZZIITX.js → SLK7PV62.js} +1 -1
- package/dist/cdn/{SUA7ZZUH.js → SUN4MBT3.js} +1 -1
- package/dist/cdn/SYXCSFIA.js +2 -0
- package/dist/cdn/{3QWNGHAK.js → TBSNDRRE.js} +1 -1
- package/dist/cdn/TP7V25GT.js +2 -0
- package/dist/cdn/{FGDSHTJ5.js → UBMZBXT7.js} +1 -1
- package/dist/cdn/UIK6LPA7.js +2 -0
- package/dist/cdn/{7DAB2CEU.js → VQRMXBPQ.js} +1 -1
- package/dist/cdn/{AM3UTQWH.js → VWOBCSD6.js} +1 -1
- package/dist/cdn/{C3F24ZOM.js → W3JJBZYX.js} +1 -1
- package/dist/cdn/W6WVMRGQ.js +2 -0
- package/dist/cdn/{TO666HVV.js → WNXDXB3M.js} +1 -1
- package/dist/cdn/{XEVOU7SJ.js → WOSWA2VI.js} +1 -1
- package/dist/cdn/{DMS3R2W5.js → WTKLB3R6.js} +1 -1
- package/dist/cdn/{LR33CLTB.js → X7W4VJO7.js} +1 -1
- package/dist/cdn/{CIRCDM5E.js → XCOP6QHA.js} +1 -1
- package/dist/cdn/{C4GK263H.js → XVV75AX3.js} +1 -1
- package/dist/cdn/XYHIVGUK.js +2 -0
- package/dist/cdn/{2GZVUHL5.js → Y4JOEFBJ.js} +1 -1
- package/dist/cdn/{CNEJPW3I.js → Y7ZCEONL.js} +1 -1
- package/dist/cdn/YELHAJB3.js +2 -0
- package/dist/cdn/YH2OFXPU.js +2 -0
- package/dist/cdn/{HVQ7FKJ5.js → YYVLFAFT.js} +1 -1
- package/dist/cdn/{BX2LXI3N.js → ZDH4KVAV.js} +1 -1
- package/dist/cdn/{SO3IBFEU.js → ZECUXVTO.js} +1 -1
- package/dist/cdn/ZG7OW456.js +2 -0
- package/dist/cdn/{7BFTXD5J.js → ZLNBCJE4.js} +1 -1
- package/dist/cdn/{GC4BV7IZ.js → ZNNEU5QW.js} +1 -1
- package/dist/cdn/assets/portal-item-status-card/t9n/messages.en.json +1 -0
- package/dist/cdn/assets/portal-review-layer-sharing/t9n/messages.en.json +1 -0
- package/dist/cdn/index.js +1 -1
- package/dist/cdn/main.css +1 -1
- package/dist/chunks/constants.js +7 -0
- package/dist/chunks/contextUsage.js +208 -0
- package/dist/chunks/createPortalTool.js +8 -8
- package/dist/chunks/fieldAddDelete.js +1 -1
- package/dist/chunks/groups2.js +1 -1
- package/dist/chunks/help.js +22 -0
- package/dist/chunks/item.js +29 -25
- package/dist/chunks/item2.js +66 -30
- package/dist/chunks/itemThumbnail.js +1 -1
- package/dist/chunks/items.js +11 -11
- package/dist/chunks/layers.js +1 -1
- package/dist/chunks/portal-item-preview-sublayer.js +1 -1
- package/dist/chunks/portal-item-status-card.js +81 -0
- package/dist/chunks/portal.js +2 -2
- package/dist/chunks/portal2.js +1 -1
- package/dist/chunks/previewSessionController.js +33 -0
- package/dist/chunks/request.js +9 -9
- package/dist/chunks/services.js +1 -1
- package/dist/chunks/user.js +2 -2
- package/dist/chunks/utils2.js +4 -4
- package/dist/components/arcgis-portal-ai-assistant/customElement.js +241 -219
- package/dist/components/arcgis-portal-ai-assistant/index.js +1 -0
- package/dist/components/arcgis-portal-ai-assistant-diagnostics/contextUsage.d.ts +46 -0
- package/dist/components/arcgis-portal-ai-assistant-diagnostics/customElement.d.ts +26 -0
- package/dist/components/arcgis-portal-ai-assistant-diagnostics/customElement.js +46 -0
- package/dist/components/arcgis-portal-ai-assistant-diagnostics/index.d.ts +1 -0
- package/dist/components/arcgis-portal-ai-assistant-diagnostics/index.js +10 -0
- package/dist/components/arcgis-portal-delete-items/customElement.js +95 -110
- package/dist/components/arcgis-portal-entity-picker/customElement.js +1 -1
- package/dist/components/arcgis-portal-field-delete/customElement.js +1 -1
- package/dist/components/arcgis-portal-group-browser/customElement.js +62 -90
- package/dist/components/arcgis-portal-group-thumbnail/customElement.js +1 -1
- package/dist/components/arcgis-portal-item-share-summary/customElement.js +1 -1
- package/dist/components/arcgis-portal-item-status-card/customElement.d.ts +82 -0
- package/dist/components/arcgis-portal-item-status-card/customElement.js +12 -0
- package/dist/components/arcgis-portal-item-status-card/index.d.ts +1 -0
- package/dist/components/arcgis-portal-item-status-card/index.js +4 -0
- package/dist/components/arcgis-portal-navigation/customElement.js +1 -1
- package/dist/components/arcgis-portal-navigation/index.js +4 -4
- package/dist/components/arcgis-portal-review-layer-sharing/customElement.d.ts +139 -0
- package/dist/components/arcgis-portal-review-layer-sharing/customElement.js +593 -0
- package/dist/components/arcgis-portal-review-layer-sharing/index.d.ts +1 -0
- package/dist/components/arcgis-portal-review-layer-sharing/index.js +10 -0
- package/dist/components/arcgis-portal-review-layer-sharing/types.d.ts +27 -0
- package/dist/components/arcgis-portal-user-popup/customElement.js +1 -1
- package/dist/docs/api.json +1 -1
- package/dist/docs/docs.json +1 -1
- package/dist/docs/vscode.html-custom-data.json +1 -1
- package/dist/docs/web-types.json +1 -1
- package/dist/index.d.ts +24 -0
- package/dist/index.js +1 -1
- package/dist/loader.js +3 -0
- package/dist/types/item.d.ts +2 -0
- package/dist/types/lumina.d.ts +18 -0
- package/dist/types/preact.d.ts +21 -0
- package/dist/types/react.d.ts +24 -0
- package/dist/types/stencil.d.ts +18 -0
- package/package.json +10 -10
- package/dist/cdn/234TH32X.js +0 -106
- package/dist/cdn/25K5D5HL.js +0 -2
- package/dist/cdn/4KTRAA2J.js +0 -2
- package/dist/cdn/4X4EYM3Q.js +0 -2
- package/dist/cdn/4YJGTINX.js +0 -2
- package/dist/cdn/A3OUZJ44.js +0 -2
- package/dist/cdn/ASID6YW7.js +0 -135
- package/dist/cdn/AYESDOK5.js +0 -2
- package/dist/cdn/BOEGDK4D.js +0 -2
- package/dist/cdn/CBFFZMX4.js +0 -2
- package/dist/cdn/FACH2JTF.js +0 -2
- package/dist/cdn/FGRMURKX.js +0 -2
- package/dist/cdn/GBG25IJ2.js +0 -2
- package/dist/cdn/H6MGSC3Y.js +0 -2
- package/dist/cdn/IKRGN33H.js +0 -93
- package/dist/cdn/K3GAZFRI.js +0 -63
- package/dist/cdn/LBW47BJG.js +0 -2
- package/dist/cdn/LRL2RJID.js +0 -2
- package/dist/cdn/MHQ5BATZ.js +0 -2
- package/dist/cdn/NJB24AIV.js +0 -2
- package/dist/cdn/NQ2IAQKL.js +0 -41
- package/dist/cdn/OEG4XCKY.js +0 -2
- package/dist/cdn/OHAQPQAP.js +0 -2
- package/dist/cdn/OYTK2VF2.js +0 -2
- package/dist/cdn/QPBWKASC.js +0 -2
- package/dist/cdn/RJ3SU3EV.js +0 -2
- package/dist/cdn/U2HTYOBB.js +0 -150
- package/dist/cdn/VLD3MVSG.js +0 -2
- package/dist/cdn/WMKG3CBK.js +0 -2
- package/dist/cdn/X4R2NVDQ.js +0 -2
- package/dist/cdn/X7C4PAJY.js +0 -2
- package/dist/cdn/YGZICQBT.js +0 -2
- package/dist/cdn/YNGFN7AY.js +0 -2
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
|
|
2
|
+
import{a as B}from"./DU2R3VC4.js";import{a as kt,c as Js}from"./5PV2GUZW.js";var yc=kt((Gb,Li)=>{"use strict";var yf=Object.prototype.hasOwnProperty,oe="~";function _r(){}Object.create&&(_r.prototype=Object.create(null),new _r().__proto__||(oe=!1));function bf(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function gc(t,e,r,n,i){if(typeof r!="function")throw new TypeError("The listener must be a function");var s=new bf(r,n||t,i),a=oe?oe+e:e;return t._events[a]?t._events[a].fn?t._events[a]=[t._events[a],s]:t._events[a].push(s):(t._events[a]=s,t._eventsCount++),t}function tn(t,e){--t._eventsCount===0?t._events=new _r:delete t._events[e]}function re(){this._events=new _r,this._eventsCount=0}re.prototype.eventNames=function(){var e=[],r,n;if(this._eventsCount===0)return e;for(n in r=this._events)yf.call(r,n)&&e.push(oe?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e};re.prototype.listeners=function(e){var r=oe?oe+e:e,n=this._events[r];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,a=new Array(s);i<s;i++)a[i]=n[i].fn;return a};re.prototype.listenerCount=function(e){var r=oe?oe+e:e,n=this._events[r];return n?n.fn?1:n.length:0};re.prototype.emit=function(e,r,n,i,s,a){var o=oe?oe+e:e;if(!this._events[o])return!1;var c=this._events[o],l=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,r),!0;case 3:return c.fn.call(c.context,r,n),!0;case 4:return c.fn.call(c.context,r,n,i),!0;case 5:return c.fn.call(c.context,r,n,i,s),!0;case 6:return c.fn.call(c.context,r,n,i,s,a),!0}for(d=1,u=new Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,p;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,r);break;case 3:c[d].fn.call(c[d].context,r,n);break;case 4:c[d].fn.call(c[d].context,r,n,i);break;default:if(!u)for(p=1,u=new Array(l-1);p<l;p++)u[p-1]=arguments[p];c[d].fn.apply(c[d].context,u)}}return!0};re.prototype.on=function(e,r,n){return gc(this,e,r,n,!1)};re.prototype.once=function(e,r,n){return gc(this,e,r,n,!0)};re.prototype.removeListener=function(e,r,n,i){var s=oe?oe+e:e;if(!this._events[s])return this;if(!r)return tn(this,s),this;var a=this._events[s];if(a.fn)a.fn===r&&(!i||a.once)&&(!n||a.context===n)&&tn(this,s);else{for(var o=0,c=[],l=a.length;o<l;o++)(a[o].fn!==r||i&&!a[o].once||n&&a[o].context!==n)&&c.push(a[o]);c.length?this._events[s]=c.length===1?c[0]:c:tn(this,s)}return this};re.prototype.removeAllListeners=function(e){var r;return e?(r=oe?oe+e:e,this._events[r]&&tn(this,r)):(this._events=new _r,this._eventsCount=0),this};re.prototype.off=re.prototype.removeListener;re.prototype.addListener=re.prototype.on;re.prefixed=oe;re.EventEmitter=re;typeof Li<"u"&&(Li.exports=re)});var wc=kt((zb,bc)=>{"use strict";bc.exports=(t,e)=>(e=e||(()=>{}),t.then(r=>new Promise(n=>{n(e())}).then(()=>r),r=>new Promise(n=>{n(e())}).then(()=>{throw r})))});var vc=kt((qb,nn)=>{"use strict";var wf=wc(),rn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},xc=(t,e,r)=>new Promise((n,i)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){n(t);return}let s=setTimeout(()=>{if(typeof r=="function"){try{n(r())}catch(c){i(c)}return}let a=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,o=r instanceof Error?r:new rn(a);typeof t.cancel=="function"&&t.cancel(),i(o)},e);wf(t.then(n,i),()=>{clearTimeout(s)})});nn.exports=xc;nn.exports.default=xc;nn.exports.TimeoutError=rn});var Ec=kt(Mi=>{"use strict";Object.defineProperty(Mi,"__esModule",{value:!0});function xf(t,e,r){let n=0,i=t.length;for(;i>0;){let s=i/2|0,a=n+s;r(t[a],e)<=0?(n=++a,i-=s+1):i=s}return n}Mi.default=xf});var Sc=kt(ji=>{"use strict";Object.defineProperty(ji,"__esModule",{value:!0});var vf=Ec(),$i=class{constructor(){this._queue=[]}enqueue(e,r){r=Object.assign({priority:0},r);let n={priority:r.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=r.priority){this._queue.push(n);return}let i=vf.default(this._queue,n,(s,a)=>a.priority-s.priority);this._queue.splice(i,0,n)}dequeue(){let e=this._queue.shift();return e?.run}filter(e){return this._queue.filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return this._queue.length}};ji.default=$i});var Hi=kt(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});var Ef=yc(),Ac=vc(),Sf=Sc(),sn=()=>{},Af=new Ac.TimeoutError,Ui=class extends Ef{constructor(e){var r,n,i,s;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=sn,this._resolveIdle=sn,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:Sf.default},e),!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=e.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(s=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||e.interval===0,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=e.throwOnTimeout===!0,this._isPaused=e.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=sn,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=sn,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let e=Date.now();if(this._intervalId===void 0){let r=this._intervalEnd-e;if(r<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},r)),!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){let e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let r=this._queue.dequeue();return r?(this.emit("active"),r(),e&&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(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,r={}){return new Promise((n,i)=>{let s=async()=>{this._pendingCount++,this._intervalCount++;try{let a=this._timeout===void 0&&r.timeout===void 0?e():Ac.default(Promise.resolve(e()),r.timeout===void 0?this._timeout:r.timeout,()=>{(r.throwOnTimeout===void 0?this._throwOnTimeout:r.throwOnTimeout)&&i(Af)});n(await a)}catch(a){i(a)}this._next()};this._queue.enqueue(s,r),this._tryToStartAnother(),this.emit("add")})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}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(e=>{let r=this._resolveEmpty;this._resolveEmpty=()=>{r(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{let r=this._resolveIdle;this._resolveIdle=()=>{r(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}};Di.default=Ui});var Mu=/([A-Z]+)([A-Z][a-z0-9]+)/g,$u=/([a-z0-9])([A-Z])/g,Xs=/[-_\s]+/g;function ju(t){return t.replace(Mu,"$1_$2").replace($u,"$1_$2").replace(Xs,"_").toLowerCase()}function Uu(t){let e=t.trim();return/[-_\s]/.test(e)?e.replace(Xs,"_").toLowerCase().replace(/_+([a-z0-9])/g,(r,n)=>n.toUpperCase()):e}function Qs(t,e){return e?.[t]||ju(t)}function hm(t,e){return e?.[t]||Uu(t)}function Ys(t,e,r){let n={};for(let i in t)Object.hasOwn(t,i)&&(n[e(i,r)]=t[i]);return n}var ea="__lc_escaped__";function Du(t){return"lc"in t||Object.keys(t).length===1&&"__lc_escaped__"in t}function Hu(t){return{[ea]:t}}function Bu(t){return Object.keys(t).length===1&&"__lc_escaped__"in t}function Fu(t){return t!==null&&typeof t=="object"&&"lc_serializable"in t&&typeof t.toJSON=="function"}function Gu(t){let e;return t!==null&&typeof t=="object"?"lc_id"in t&&Array.isArray(t.lc_id)?e=t.lc_id:e=[t.constructor?.name??"Object"]:e=[typeof t],{lc:1,type:"not_implemented",id:e}}function $r(t,e=new WeakSet){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){if(e.has(t))return Gu(t);if(Fu(t))return t;e.add(t);let r=t;if(Du(r))return e.delete(t),Hu(r);let n={};for(let[i,s]of Object.entries(r))n[i]=$r(s,e);return e.delete(t),n}return Array.isArray(t)?t.map(r=>$r(r,e)):t}function Zs(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let e=t;if(Bu(e))return e[ea];let r={};for(let[n,i]of Object.entries(e))r[n]=Zs(i);return r}return Array.isArray(t)?t.map(e=>Zs(e)):t}var wm=B({Serializable:()=>Nt,get_lc_unique_name:()=>jr});function ta(t){return Array.isArray(t)?[...t]:{...t}}function zu(t,e){let r=ta(t);for(let[n,i]of Object.entries(e)){let[s,...a]=n.split(".").reverse(),o=r;for(let c of a.reverse()){if(o[c]===void 0)break;o[c]=ta(o[c]),o=o[c]}o[s]!==void 0&&(o[s]={lc:1,type:"secret",id:[i]})}return r}function jr(t){let e=Object.getPrototypeOf(t);return typeof t.lc_name=="function"&&(typeof e.lc_name!="function"||t.lc_name()!==e.lc_name())?t.lc_name():t.name}var Nt=class ra{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,jr(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...r){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([n])=>this.lc_serializable_keys?.includes(n))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof ra||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let e={},r={},n=Object.keys(this.lc_kwargs).reduce((c,l)=>(c[l]=l in this?this[l]:this.lc_kwargs[l],c),{});for(let c=Object.getPrototypeOf(this);c;c=Object.getPrototypeOf(c))Object.assign(e,Reflect.get(c,"lc_aliases",this)),Object.assign(r,Reflect.get(c,"lc_secrets",this)),Object.assign(n,Reflect.get(c,"lc_attributes",this));Object.keys(r).forEach(c=>{let l=this,u=n,[d,...f]=c.split(".").reverse();for(let p of f.reverse()){if(!(p in l)||l[p]===void 0)return;(!(p in u)||u[p]===void 0)&&(typeof l[p]=="object"&&l[p]!=null?u[p]={}:Array.isArray(l[p])&&(u[p]=[])),l=l[p],u=u[p]}d in l&&l[d]!==void 0&&(u[d]=u[d]||l[d])});let i={},s=new WeakSet;s.add(this);for(let[c,l]of Object.entries(n))i[c]=$r(l,s);let a=Object.keys(r).length?zu(i,r):i,o=Ys(a,Qs,e);return{lc:1,type:"constructor",id:this.lc_id,kwargs:o}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function ze(t){return typeof t=="object"&&t!==null&&"type"in t&&typeof t.type=="string"&&"source_type"in t&&(t.source_type==="url"||t.source_type==="base64"||t.source_type==="text"||t.source_type==="id")}function na(t){return ze(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}function ia(t){return ze(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}function vm(t){return ze(t)&&t.source_type==="text"&&"text"in t&&typeof t.text=="string"}function sa(t){return ze(t)&&t.source_type==="id"&&"id"in t&&typeof t.id=="string"}function Em(t){if(ze(t)){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url}};if(t.source_type==="base64"){if(!t.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${t.mime_type};base64,${t.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function Sm(t){let e=t.split(";")[0].split("/");if(e.length!==2)throw new Error(`Invalid mime type: "${t}" - does not match type/subtype format.`);let r=e[0].trim(),n=e[1].trim();if(r===""||n==="")throw new Error(`Invalid mime type: "${t}" - type or subtype is empty.`);let i={};for(let s of t.split(";").slice(1)){let a=s.split("=");if(a.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${t}".`);let o=a[0].trim(),c=a[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${t}".`);i[o]=c}return{type:r,subtype:n,parameters:i}}function Wn({dataUrl:t,asTypedArray:e=!1}){let r=t.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),n;if(r){n=r[1].toLowerCase();let i=e?Uint8Array.from(atob(r[2]),s=>s.charCodeAt(0)):r[2];return{mime_type:n,data:i}}}function Am(t,e){if(t.type==="text"){if(!e.fromStandardTextBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardTextBlock\` method.`);return e.fromStandardTextBlock(t)}if(t.type==="image"){if(!e.fromStandardImageBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardImageBlock\` method.`);return e.fromStandardImageBlock(t)}if(t.type==="audio"){if(!e.fromStandardAudioBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardAudioBlock\` method.`);return e.fromStandardAudioBlock(t)}if(t.type==="file"){if(!e.fromStandardFileBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardFileBlock\` method.`);return e.fromStandardFileBlock(t)}throw new Error(`Unable to convert content block type '${t.type}' to provider-specific format: not recognized.`)}function x(t,e){return A(t)&&t.type===e}function A(t){return typeof t=="object"&&t!==null}function q(t){return Array.isArray(t)}function _(t){return typeof t=="string"}function pe(t){return typeof t=="number"}function Ur(t){return t instanceof Uint8Array}function Jn(t){try{return JSON.parse(t)}catch{return}}var he=t=>t();function qu(t){if(t.type==="char_location"&&_(t.document_title)&&pe(t.start_char_index)&&pe(t.end_char_index)&&_(t.cited_text)){let{document_title:e,start_char_index:r,end_char_index:n,cited_text:i,...s}=t;return{...s,type:"citation",source:"char",title:e??void 0,startIndex:r,endIndex:n,citedText:i}}if(t.type==="page_location"&&_(t.document_title)&&pe(t.start_page_number)&&pe(t.end_page_number)&&_(t.cited_text)){let{document_title:e,start_page_number:r,end_page_number:n,cited_text:i,...s}=t;return{...s,type:"citation",source:"page",title:e??void 0,startIndex:r,endIndex:n,citedText:i}}if(t.type==="content_block_location"&&_(t.document_title)&&pe(t.start_block_index)&&pe(t.end_block_index)&&_(t.cited_text)){let{document_title:e,start_block_index:r,end_block_index:n,cited_text:i,...s}=t;return{...s,type:"citation",source:"block",title:e??void 0,startIndex:r,endIndex:n,citedText:i}}if(t.type==="web_search_result_location"&&_(t.url)&&_(t.title)&&_(t.encrypted_index)&&_(t.cited_text)){let{url:e,title:r,encrypted_index:n,cited_text:i,...s}=t;return{...s,type:"citation",source:"url",url:e,title:r,startIndex:Number(n),endIndex:Number(n),citedText:i}}if(t.type==="search_result_location"&&_(t.source)&&_(t.title)&&pe(t.start_block_index)&&pe(t.end_block_index)&&_(t.cited_text)){let{source:e,title:r,start_block_index:n,end_block_index:i,cited_text:s,...a}=t;return{...a,type:"citation",source:"search",url:e,title:r??void 0,startIndex:n,endIndex:i,citedText:s}}}function oa(t){if(x(t,"document")&&A(t.source)&&"type"in t.source){if(t.source.type==="base64"&&_(t.source.media_type)&&_(t.source.data))return{type:"file",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&_(t.source.url))return{type:"file",url:t.source.url};if(t.source.type==="file"&&_(t.source.file_id))return{type:"file",fileId:t.source.file_id};if(t.source.type==="text"&&_(t.source.data))return{type:"file",mimeType:String(t.source.media_type??"text/plain"),data:t.source.data}}else if(x(t,"image")&&A(t.source)&&"type"in t.source){if(t.source.type==="base64"&&_(t.source.media_type)&&_(t.source.data))return{type:"image",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&_(t.source.url))return{type:"image",url:t.source.url};if(t.source.type==="file"&&_(t.source.file_id))return{type:"image",fileId:t.source.file_id}}}function ca(t){function*e(){for(let r of t){let n=oa(r);n?yield n:yield r}}return Array.from(e())}function aa(t){let e=!1;function*r(){let n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let s of n){if(x(s,"text")&&_(s.text)){let{text:a,citations:o,...c}=s;if(q(o)&&o.length){let l=o.reduce((u,d)=>{let f=qu(d);return f?[...u,f]:u},[]);yield{...c,type:"text",text:a,annotations:l};continue}else{yield{...c,type:"text",text:a};continue}}else if(x(s,"thinking")&&_(s.thinking)){let{thinking:a,signature:o,...c}=s;yield{...c,type:"reasoning",reasoning:a,signature:o};continue}else if(x(s,"redacted_thinking")){yield{type:"non_standard",value:s};continue}else if(x(s,"tool_use")&&_(s.name)&&_(s.id)){yield{type:"tool_call",id:s.id,name:s.name,args:s.input};continue}else if(x(s,"input_json_delta")){if(Vu(t)&&t.tool_call_chunks?.length){let a=t.tool_call_chunks[0];yield{type:"tool_call_chunk",id:a.id,name:a.name,args:a.args,index:a.index};continue}}else if(x(s,"server_tool_use")&&_(s.name)&&_(s.id)){let{name:a,id:o}=s;if(a==="web_search"){yield{id:o,type:"server_tool_call",name:"web_search",args:{query:he(()=>{if(typeof s.input=="string")return s.input;if(A(s.input)&&_(s.input.query))return s.input.query;if(_(s.partial_json)){let c=Jn(s.partial_json);if(c?.query)return c.query}return""})}};continue}else if(s.name==="code_execution"){yield{id:o,type:"server_tool_call",name:"code_execution",args:{code:he(()=>{if(typeof s.input=="string")return s.input;if(A(s.input)&&_(s.input.code))return s.input.code;if(_(s.partial_json)){let c=Jn(s.partial_json);if(c?.code)return c.code}return""})}};continue}}else if(x(s,"web_search_tool_result")&&_(s.tool_use_id)&&q(s.content)){let{content:a,tool_use_id:o}=s;yield{type:"server_tool_call_result",name:"web_search",toolCallId:o,status:"success",output:{urls:a.reduce((c,l)=>x(l,"web_search_result")?[...c,l.url]:c,[])}};continue}else if(x(s,"code_execution_tool_result")&&_(s.tool_use_id)&&A(s.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:s.tool_use_id,status:"success",output:s.content};continue}else if(x(s,"mcp_tool_use")){yield{id:s.id,type:"server_tool_call",name:"mcp_tool_use",args:s.input};continue}else if(x(s,"mcp_tool_result")&&_(s.tool_use_id)&&A(s.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:s.tool_use_id,status:"success",output:s.content};continue}else if(x(s,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:s.input};continue}else if(x(s,"search_result")){yield{id:s.id,type:"non_standard",value:s};continue}else if(x(s,"tool_result")){yield{id:s.id,type:"non_standard",value:s};continue}else{if(x(s,"refusal")&&_(s.refusal)){e=!0,yield s;continue}let a=oa(s);if(a){yield a;continue}}yield{type:"non_standard",value:s}}let i=t.response_metadata.stop_reason!==void 0?t.response_metadata:t.additional_kwargs;!e&&i.stop_reason==="refusal"&&(yield Ku(i.stop_details))}return Array.from(r())}function Ku(t){let e=A(t)?t:{},r=e.explanation,n=e.category;return{type:"refusal",refusal:_(r)?r:"",..._(n)?{extras:{category:n}}:{}}}var la={translateContent:aa,translateContentChunk:aa};function Vu(t){return typeof t?._getType=="function"&&typeof t.concat=="function"&&t._getType()==="ai"}function Wu(t){return na(t)?{type:t.type,mimeType:t.mime_type,url:t.url,metadata:t.metadata}:ia(t)?{type:t.type,mimeType:t.mime_type??"application/octet-stream",data:t.data,metadata:t.metadata}:sa(t)?{type:t.type,mimeType:t.mime_type,fileId:t.id,metadata:t.metadata}:t}function ua(t){return t.map(Wu)}function da(t){return!!(x(t,"image_url")&&A(t.image_url)||x(t,"input_audio")&&A(t.input_audio)||x(t,"file")&&A(t.file))}function fa(t){if(x(t,"image_url")&&A(t.image_url)&&_(t.image_url.url)){let e=Wn({dataUrl:t.image_url.url});return e?{type:"image",mimeType:e.mime_type,data:e.data}:{type:"image",url:t.image_url.url}}else{if(x(t,"input_audio")&&A(t.input_audio)&&_(t.input_audio.data)&&_(t.input_audio.format))return{type:"audio",data:t.input_audio.data,mimeType:`audio/${t.input_audio.format}`};if(x(t,"file")&&A(t.file)&&_(t.file.data)){let e=Wn({dataUrl:t.file.data});if(e)return{type:"file",data:e.data,mimeType:e.mime_type};if(_(t.file.file_id))return{type:"file",fileId:t.file.file_id}}}return t}function Xn(t){let e=t.additional_kwargs.refusal;return _(e)&&e.length>0?{type:"refusal",refusal:e}:void 0}function Ju(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...Dr(t.content));for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});let r=Xn(t);return r&&e.push(r),e}function Xu(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...Dr(t.content));for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});let r=Xn(t);return r&&e.push(r),e}function Dr(t){let e=[];for(let r of t)da(r)?e.push(fa(r)):e.push(r);return e}function Qu(t){if(t.type==="url_citation"){let{url:e,title:r,start_index:n,end_index:i}=t;return{type:"citation",url:e,title:r,startIndex:n,endIndex:i}}if(t.type==="file_citation"){let{file_id:e,filename:r,index:n}=t;return{type:"citation",title:r,startIndex:n,endIndex:n,fileId:e}}return t}function pa(t){if(q(t.summary))return{type:"reasoning",reasoning:t.summary.reduce((e,r)=>A(r)&&_(r.text)?`${e}${r.text}`:e,""),..._(t.id)?{id:t.id}:{},..._(t.encrypted_content)?{encrypted_content:t.encrypted_content}:{}}}function*Yu(t){if(x(t,"web_search_call")){let e={};if(A(t.action)&&_(t.action.query)&&(e.query=t.action.query),yield{id:t.id,type:"server_tool_call",name:"web_search",args:e},t.status==="completed"||t.status==="failed"){let r={};A(t.action)&&(r.action=t.action),yield{type:"server_tool_call_result",toolCallId:_(t.id)?t.id:"",status:t.status==="completed"?"success":"error",output:r}}return}if(x(t,"file_search_call")){yield{id:t.id,type:"server_tool_call",name:"file_search",args:{queries:q(t.queries)?t.queries:[]}},(t.status==="completed"||t.status==="failed")&&(yield{type:"server_tool_call_result",toolCallId:_(t.id)?t.id:"",status:t.status==="completed"?"success":"error",output:q(t.results)?{results:t.results}:{}});return}if(x(t,"computer_call")){yield{type:"non_standard",value:t};return}if(x(t,"code_interpreter_call")){if(_(t.code)&&(yield{id:t.id,type:"server_tool_call",name:"code_interpreter",args:{code:t.code}}),q(t.outputs)){let e=he(()=>{if(t.status!=="in_progress"){if(t.status==="completed")return 0;if(t.status==="incomplete")return 127;if(t.status!=="interpreting"&&t.status==="failed")return 1}});for(let r of t.outputs)x(r,"logs")&&(yield{type:"server_tool_call_result",toolCallId:t.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:e??0,stderr:[0,void 0].includes(e)?void 0:String(r.logs),stdout:[0,void 0].includes(e)?String(r.logs):void 0}})}return}if(x(t,"mcp_call")){yield{id:t.id,type:"server_tool_call",name:"mcp_call",args:t.input};return}if(x(t,"mcp_list_tools")){yield{id:t.id,type:"server_tool_call",name:"mcp_list_tools",args:t.input};return}if(x(t,"mcp_approval_request")){yield{type:"non_standard",value:t};return}if(x(t,"tool_search_call")){let e={};A(t.arguments)&&Object.assign(e,t.arguments);let r={};_(t.execution)&&(r.execution=t.execution),_(t.status)&&(r.status=t.status),_(t.call_id)&&(r.call_id=t.call_id),yield{id:_(t.id)?t.id:"",type:"server_tool_call",name:"tool_search",args:e,...Object.keys(r).length>0?{extras:r}:{}};return}if(x(t,"tool_search_output")){let e={name:"tool_search"};_(t.execution)&&(e.execution=t.execution),yield{type:"server_tool_call_result",toolCallId:_(t.id)?t.id:"",status:t.status==="completed"?"success":t.status==="failed"?"error":"success",output:{tools:q(t.tools)?t.tools:[]},extras:e};return}if(x(t,"image_generation_call")){_(t.result)&&(yield{type:"image",mimeType:"image/png",data:t.result,id:_(t.id)?t.id:void 0,metadata:{status:_(t.status)?t.status:void 0}}),yield{type:"non_standard",value:t};return}A(t)&&(yield{type:"non_standard",value:t})}function ha(t){let e=t.response_metadata?.output,r=q(e)&&e.length>0,n=new Map,i=0,s;r&&e.forEach((l,u)=>{!A(l)||!_(l.type)||(l.type==="reasoning"&&_(l.id)?n.set(`reasoning:${l.id}`,u):(l.type==="function_call"||l.type==="custom_tool_call"||l.type==="computer_call")&&_(l.call_id)?n.set(`tool_call:${l.call_id}`,u):l.type==="message"?(i+=1,s=u):_(l.id)&&n.set(`other:${l.type}:${l.id}`,u))});let a=i===1&&s!=null?`message:${s}`:void 0;a!=null&&n.set(a,s);function*o(){if(r){for(let d of e)if(A(d)&&d.type==="reasoning"){let f=pa(d);f&&(yield[f,_(d.id)?`reasoning:${d.id}`:void 0])}}else if(A(t.additional_kwargs?.reasoning)&&q(t.additional_kwargs.reasoning.summary)){let d=pa(t.additional_kwargs.reasoning);d&&(yield[d,void 0])}let l=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let d of l)if(x(d,"text")){let{text:f,annotations:p,phase:h,extras:m,...w}=d,E=A(m)?{...m}:{};_(h)&&(E.phase=h);let b=Object.keys(E).length>0?{extras:E}:{};yield[{...w,...b,type:"text",text:String(f),...Array.isArray(p)?{annotations:p.map(Qu)}:{}},a]}let u=!1;for(let d of l)x(d,"refusal")&&_(d.refusal)&&(u=!0,yield[{type:"refusal",refusal:d.refusal,..._(d.id)?{id:d.id}:{}},a]);if(!u){let d=Xn(t);d&&(yield[d,a])}for(let d of t.tool_calls??[])yield[{type:"tool_call",id:d.id,name:d.name,args:d.args},d.id?`tool_call:${d.id}`:void 0];if(A(t.additional_kwargs)&&q(t.additional_kwargs.tool_outputs))for(let d of t.additional_kwargs.tool_outputs){let f=A(d)&&_(d.type)&&_(d.id)?`other:${d.type}:${d.id}`:void 0;for(let p of Yu(d))yield[p,f]}}let c=Array.from(o());return r?c.map(([l,u],d)=>({block:l,pushIndex:d,position:u!=null?n.get(u):void 0})).sort((l,u)=>{let d=l.position??Number.POSITIVE_INFINITY,f=u.position??Number.POSITIVE_INFINITY;return d!==f?d-f:l.pushIndex-u.pushIndex}).map(l=>l.block):c.map(([l])=>l)}function Zu(t){function*e(){yield*ha(t);for(let r of t.tool_call_chunks??[])yield{type:"tool_call_chunk",id:r.id,name:r.name,args:r.args}}return Array.from(e())}var ma={translateContent:t=>typeof t.content=="string"?Ju(t):ha(t),translateContentChunk:t=>typeof t.content=="string"?Xu(t):Zu(t)};function _a(t){return typeof t=="object"&&t!==null&&"type"in t&&"content"in t&&(typeof t.content=="string"||Array.isArray(t.content))}function ga(t,e="pretty"){return e==="pretty"?ed(t):JSON.stringify(t)}function ed(t){let e=[],r=` ${t.type.charAt(0).toUpperCase()+t.type.slice(1)} Message `,n=Math.floor((80-r.length)/2),i="=".repeat(n),s=r.length%2===0?i:`${i}=`;if(e.push(`${i}${r}${s}`),t.type==="ai"){let a=t;if(a.tool_calls&&a.tool_calls.length>0){e.push("Tool Calls:");for(let o of a.tool_calls){e.push(` ${o.name} (${o.id})`),e.push(` Call ID: ${o.id}`),e.push(" Args:");for(let[c,l]of Object.entries(o.args))e.push(` ${c}: ${typeof l=="object"?JSON.stringify(l):l}`)}}}if(t.type==="tool"){let a=t;a.name&&e.push(`Name: ${a.name}`)}return typeof t.content=="string"&&t.content.trim()&&(e.length>1&&e.push(""),e.push(t.content)),e.join(`
|
|
3
|
+
`)}var Qn=Symbol.for("langchain.message");function ya(t){return Array.isArray(t)?t:typeof t=="string"?t===""?[]:[{type:"text",text:t}]:t==null?[]:[t]}function ue(t,e){if(typeof t=="string")return t===""?e:typeof e=="string"?t+e:Array.isArray(e)&&e.length===0?t:Array.isArray(e)&&e.some(r=>ze(r))?[{type:"text",source_type:"text",text:t},...e]:[{type:"text",text:t},...e];if(Array.isArray(e)){let r=ya(t);return Lt(r,e)??[...r,...e]}else return e===""?t:Array.isArray(t)&&t.some(r=>ze(r))?[...t,{type:"file",source_type:"text",text:e}]:[...ya(t),{type:"text",text:e}]}function va(t,e){return t==="error"||e==="error"?"error":"success"}function td(t,e){function r(n,i){if(typeof n!="object"||n===null||n===void 0)return n;if(i>=e)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(a=>r(a,i+1));let s={};for(let a of Object.keys(n))s[a]=r(n[a],i+1);return s}return JSON.stringify(r(t,0),null,2)}var ae=class extends Nt{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[Qn]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(t){let e=typeof t=="string"||Array.isArray(t)?{content:t}:t;e.additional_kwargs||(e.additional_kwargs={}),e.response_metadata||(e.response_metadata={}),super(e),this.name=e.name,e.content===void 0&&e.contentBlocks!==void 0?(this.content=e.contentBlocks,this.response_metadata={output_version:"v1",...e.response_metadata}):e.content!==void 0?(this.content=e.content??[],this.response_metadata=e.response_metadata):(this.content=[],this.response_metadata=e.response_metadata),this.additional_kwargs=e.additional_kwargs,this.id=e.id}get text(){return this.contentBlocks.filter(t=>t.type==="text").reduce((t,e)=>t+(e.text??""),"")}get contentBlocks(){let t=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[ua,Dr,ca].reduce((e,r)=>r(e),t)}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}}static isInstance(t){return typeof t=="object"&&t!==null&&Qn in t&&t[Qn]===!0&&_a(t)}static[Symbol.hasInstance](t){return this.isInstance(t)}_updateId(t){this.id=t,this.lc_kwargs.id=t}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](t){if(t===null)return this;let e=td(this._printableFields,Math.max(4,t));return`${this.constructor.lc_name()} ${e}`}toFormattedString(t="pretty"){return ga(this,t)}};function qm(t){return Array.isArray(t)&&t.every(e=>typeof e.index=="number")}var rd=["index","created","timestamp"];function z(t,e,r){let n=r?.ignoreKeys??rd;if(t==null&&e==null)return;if(t==null||e==null)return t??e;let i={...t};for(let[s,a]of Object.entries(e))if(i[s]==null)i[s]=a;else{if(a==null)continue;if(typeof i[s]!=typeof a||Array.isArray(i[s])!==Array.isArray(a))throw new Error(`field[${s}] already exists in the message chunk, but with a different type.`);if(typeof i[s]=="string"){if(s==="type")continue;if(["id","name","output_version","model_provider"].includes(s))a&&(i[s]=a);else{if(n.includes(s))continue;i[s]+=a}}else if(typeof i[s]=="number"){if(n.includes(s))continue;i[s]=i[s]+a}else if(typeof i[s]=="object"&&!Array.isArray(i[s]))i[s]=z(i[s],a,r);else if(Array.isArray(i[s]))i[s]=Lt(i[s],a,r);else{if(i[s]===a)continue;console.warn(`field[${s}] already exists in this message chunk and value has unsupported type.`)}}return i}function nd(t){return typeof t=="number"||typeof t=="string"}function ba(t){return typeof t!="object"||t===null||!("index"in t)?!1:nd(t.index)}function wa(t){if(typeof t!="object"||t===null||!("id"in t))return!1;let e=t.id;return e!=null&&e!==""}function xa(t){return t.endsWith("_delta")?t.slice(0,-6):t}function id(t,e){return typeof t!="object"||t===null||typeof e!="object"||e===null||!("type"in t)||!("type"in e)?!1:typeof t.type=="string"&&typeof e.type=="string"&&xa(t.type)!==xa(e.type)}function sd(t,e){let r=ba(e),n=wa(e);return!r&&!n?-1:t.findIndex(i=>{let s=ba(i),a=wa(i);return r&&s?i.index!==e.index||id(i,e)?!1:a&&n?i.id===e.id:!0:!r&&!s&&n&&a?i.id===e.id:!1})}function Lt(t,e,r){if(!(t==null&&e==null)){if(t==null||e==null)return t||e;{let n=[...t];for(let i of e){let s=sd(n,i);if(s!==-1)n[s]=z(n[s],i,r);else{if(typeof i=="object"&&i!==null&&"text"in i&&i.text==="")continue;n.push(i)}}return n}}}function Ea(t,e,r){if(!(t==null&&e==null)){if(t==null||e==null)return t??e;if(typeof t!=typeof e)throw new Error(`Cannot merge objects of different types.
|
|
4
|
+
Left ${typeof t}
|
|
5
|
+
Right ${typeof e}`);if(typeof t=="string"&&typeof e=="string")return t+e;if(Array.isArray(t)&&Array.isArray(e))return Lt(t,e,r);if(typeof t=="object"&&typeof e=="object")return z(t,e,r);if(t===e)return t;throw new Error(`Can not merge objects of different types.
|
|
6
|
+
Left ${t}
|
|
7
|
+
Right ${e}`)}}var me=class Sa extends ae{static isInstance(e){if(!super.isInstance(e))return!1;let r=Object.getPrototypeOf(e);for(;r!==null;){if(r===Sa.prototype)return!0;r=Object.getPrototypeOf(r)}return!1}static[Symbol.hasInstance](e){return this.isInstance(e)}};function Aa(t){return typeof t.role=="string"}function Ia(t){return typeof t?._getType=="function"}function Km(t){return me.isInstance(t)}var Qm=B({ToolMessage:()=>Hr,ToolMessageChunk:()=>od,defaultToolCallParser:()=>Yn,isDirectToolOutput:()=>ad,isToolMessage:()=>cd,isToolMessageChunk:()=>ld});function ad(t){return t!=null&&typeof t=="object"&&"lc_direct_tool_output"in t&&t.lc_direct_tool_output===!0}var Hr=class extends ae{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}lc_direct_tool_output=!0;type="tool";status;tool_call_id;metadata;artifact;constructor(t,e,r){let n=typeof t=="string"||Array.isArray(t)?{content:t,name:r,tool_call_id:e}:t;super(n),this.tool_call_id=n.tool_call_id,this.artifact=n.artifact,this.status=n.status,this.metadata=n.metadata}static isInstance(t){return super.isInstance(t)&&t.type==="tool"}static[Symbol.hasInstance](t){return this.isInstance(t)}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},od=class extends me{type="tool";tool_call_id;status;artifact;constructor(t){super(t),this.tool_call_id=t.tool_call_id,this.artifact=t.artifact,this.status=t.status}static lc_name(){return"ToolMessageChunk"}concat(t){let e=this.constructor;return new e({content:ue(this.content,t.content),additional_kwargs:z(this.additional_kwargs,t.additional_kwargs),response_metadata:z(this.response_metadata,t.response_metadata),artifact:Ea(this.artifact,t.artifact),tool_call_id:this.tool_call_id,id:this.id??t.id,status:va(this.status,t.status)})}static isInstance(t){return super.isInstance(t)&&t.type==="tool"}static[Symbol.hasInstance](t){return this.isInstance(t)}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function Yn(t){let e=[],r=[];for(let n of t)if(n.function){let i=n.function.name;try{let s=JSON.parse(n.function.arguments);e.push({name:i||"",args:s||{},id:n.id})}catch{r.push({name:i,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[e,r]}function cd(t){return typeof t=="object"&&t!==null&&"getType"in t&&typeof t.getType=="function"&&t.getType()==="tool"}function ld(t){return t._getType()==="tool"}function Zn(t){switch(t){case"csv":return"text/csv";case"doc":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"html":return"text/html";case"md":return"text/markdown";case"pdf":return"application/pdf";case"txt":return"text/plain";case"xls":return"application/vnd.ms-excel";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"gif":return"image/gif";case"jpeg":return"image/jpeg";case"jpg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"flv":return"video/flv";case"mkv":return"video/mkv";case"mov":return"video/mov";case"mp4":return"video/mp4";case"mpeg":return"video/mpeg";case"mpg":return"video/mpg";case"three_gp":return"video/three_gp";case"webm":return"video/webm";case"wmv":return"video/wmv";default:return"application/octet-stream"}}function ud(t){if(A(t.document)&&A(t.document.source)){let e=Zn(A(t.document)&&_(t.document.format)?t.document.format:"");if(A(t.document.source)){if(A(t.document.source.s3Location)&&_(t.document.source.s3Location.uri))return{type:"file",mimeType:e,fileId:t.document.source.s3Location.uri};if(Ur(t.document.source.bytes))return{type:"file",mimeType:e,data:t.document.source.bytes};if(_(t.document.source.text))return{type:"file",mimeType:e,data:Buffer.from(t.document.source.text).toString("base64")};if(q(t.document.source.content))return{type:"file",mimeType:e,data:t.document.source.content.reduce((r,n)=>A(n)&&_(n.text)?r+n.text:r,"")}}}return{type:"non_standard",value:t}}function dd(t){if(x(t,"image")&&A(t.image)){let e=Zn(A(t.image)&&_(t.image.format)?t.image.format:"");if(A(t.image.source)){if(A(t.image.source.s3Location)&&_(t.image.source.s3Location.uri))return{type:"image",mimeType:e,fileId:t.image.source.s3Location.uri};if(Ur(t.image.source.bytes))return{type:"image",mimeType:e,data:t.image.source.bytes}}}return{type:"non_standard",value:t}}function fd(t){if(x(t,"video")&&A(t.video)){let e=Zn(A(t.video)&&_(t.video.format)?t.video.format:"");if(A(t.video.source)){if(A(t.video.source.s3Location)&&_(t.video.source.s3Location.uri))return{type:"video",mimeType:e,fileId:t.video.source.s3Location.uri};if(Ur(t.video.source.bytes))return{type:"video",mimeType:e,data:t.video.source.bytes}}}return{type:"non_standard",value:t}}function Ta(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(x(n,"reasoning")&&_(n.reasoning)){yield{...n,type:"reasoning",reasoning:n.reasoning};continue}else if(x(n,"cache_point")){yield{type:"non_standard",value:n};continue}else if(x(n,"citations_content")&&A(n.citationsContent)){yield{type:"text",text:q(n.citationsContent.content)?n.citationsContent.content.reduce((i,s)=>A(s)&&_(s.text)?i+s.text:i,""):"",annotations:q(n.citationsContent.citations)?n.citationsContent.citations.reduce((i,s)=>{if(A(s)){let a=q(s.sourceContent)?s.sourceContent.reduce((c,l)=>A(l)&&_(l.text)?c+l.text:c,""):"",o=he(()=>{if(A(s.location)){let c=s.location.documentChar||s.location.documentPage||s.location.documentChunk;if(A(c))return{source:pe(c.documentIndex)?c.documentIndex.toString():void 0,startIndex:pe(c.start)?c.start:void 0,endIndex:pe(c.end)?c.end:void 0}}return{}});i.push({type:"citation",citedText:a,...o})}return i},[]):[]};continue}else if(x(n,"document")&&A(n.document)){yield ud(n);continue}else if(x(n,"guard_content")){yield{type:"non_standard",value:n};continue}else if(x(n,"image")&&A(n.image)){yield dd(n);continue}else if(x(n,"reasoning_content")&&A(n.reasoningText)&&_(n.reasoningText.text)){yield{type:"reasoning",reasoning:n.reasoningText.text,..._(n.reasoningText.signature)?{signature:n.reasoningText.signature}:{}};continue}else if(x(n,"reasoning_content")&&_(n.reasoningText)){yield{type:"reasoning",reasoning:n.reasoningText};continue}else if(x(n,"text")&&_(n.text)){yield{type:"text",text:n.text};continue}else if(x(n,"tool_result")){yield{type:"non_standard",value:n};continue}else{if(x(n,"tool_call"))continue;if(x(n,"video")&&A(n.video)){yield fd(n);continue}}yield{type:"non_standard",value:n}}}return Array.from(e())}var Pa={translateContent:Ta,translateContentChunk:Ta};function Ra(t){let e=[],r=t.additional_kwargs?.reasoning_content;if(_(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let n of t.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&_(n.text)&&e.push({type:"text",text:n.text});for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}var Ca={translateContent:Ra,translateContentChunk:Ra};function Oa(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(x(n,"text")&&_(n.text)){yield{type:"text",text:n.text};continue}else if(x(n,"thinking")&&_(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(x(n,"inlineData")&&A(n.inlineData)&&_(n.inlineData.mimeType)&&_(n.inlineData.data)){yield{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data};continue}else if(x(n,"functionCall")&&A(n.functionCall)&&_(n.functionCall.name)&&A(n.functionCall.args)){yield{type:"tool_call",id:t.id,name:n.functionCall.name,args:n.functionCall.args};continue}else if(x(n,"functionResponse")){yield{type:"non_standard",value:n};continue}else if(x(n,"fileData")&&A(n.fileData)&&_(n.fileData.mimeType)&&_(n.fileData.fileUri)){yield{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri};continue}else if(x(n,"executableCode")){yield{type:"non_standard",value:n};continue}else if(x(n,"codeExecutionResult")){yield{type:"non_standard",value:n};continue}yield{type:"non_standard",value:n}}}return Array.from(e())}var ka={translateContent:Oa,translateContentChunk:Oa};function Na(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(x(n,"reasoning")&&_(n.reasoning)){let i=he(()=>{let s=r.indexOf(n);if(q(t.additional_kwargs?.signatures)&&s>=0)return t.additional_kwargs.signatures.at(s)});_(i)?yield{type:"reasoning",reasoning:n.reasoning,signature:i}:yield{type:"reasoning",reasoning:n.reasoning};continue}else if(x(n,"thinking")&&_(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(x(n,"text")&&_(n.text)){if(n.text==="")continue;yield{type:"text",text:n.text};continue}else if(x(n,"image_url")){if(_(n.image_url))if(n.image_url.startsWith("data:")){let i=n.image_url.match(/^data:([^;]+);base64,(.+)$/);i?yield{type:"image",data:i[2],mimeType:i[1]}:yield{type:"image",url:n.image_url}}else yield{type:"image",url:n.image_url};continue}else if(x(n,"media")&&_(n.mimeType)&&_(n.data)){yield{type:"file",mimeType:n.mimeType,data:n.data};continue}yield{type:"non_standard",value:n}}for(let n of t.tool_calls??[])yield{type:"tool_call",id:n.id,name:n.name,args:n.args}}return Array.from(e())}var La={translateContent:Na,translateContentChunk:Na};function Ma(t){let e=[],r=t.additional_kwargs?.reasoning;if(_(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string"){let n=t.content,i=n.match(/<think>([\s\S]*?)<\/think>/);if(i){let s=i[1].trim();s.length>0&&e.push({type:"reasoning",reasoning:s}),n=n.replace(/<think>[\s\S]*?<\/think>/,"").trim()}n.length>0&&e.push({type:"text",text:n})}else for(let n of t.content)if(typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&_(n.text)){let i=n.text,s=i.match(/<think>([\s\S]*?)<\/think>/);if(s){let a=s[1].trim();a.length>0&&e.push({type:"reasoning",reasoning:a}),i=i.replace(/<think>[\s\S]*?<\/think>/,"").trim()}i.length>0&&e.push({type:"text",text:i})}for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}var $a={translateContent:Ma,translateContentChunk:Ma};function ja(t){let e=[],r=t.additional_kwargs?.reasoning_content;if(_(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let n of t.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&_(n.text)&&e.push({type:"text",text:n.text});for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}var Ua={translateContent:ja,translateContentChunk:ja};function Da(t){let e=[],r=t.additional_kwargs?.reasoning_details,n=!1;if(Array.isArray(r)&&r.length>0)for(let i of r){if(i==null||typeof i!="object")continue;let s=i.type;if(s==="reasoning.summary"){let a=i.summary;_(a)&&a.length>0&&(e.push({type:"reasoning",reasoning:a}),n=!0)}else if(s==="reasoning.text"){let a=i.text;_(a)&&a.length>0&&(e.push({type:"reasoning",reasoning:a}),n=!0)}}if(!n){let i=t.additional_kwargs?.reasoning_content;_(i)&&i.length>0&&e.push({type:"reasoning",reasoning:i})}if(typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let i of t.content)typeof i=="object"&&"type"in i&&i.type==="text"&&"text"in i&&_(i.text)&&e.push({type:"text",text:i.text});for(let i of t.tool_calls??[])e.push({type:"tool_call",id:i.id,name:i.name,args:i.args});return e}var Ha={translateContent:Da,translateContentChunk:Da};function Ba(t){let e=[];if(A(t.additional_kwargs?.reasoning)){let n=t.additional_kwargs.reasoning;if(q(n.summary)){let i=n.summary.reduce((s,a)=>A(a)&&_(a.text)?`${s}${a.text}`:s,"");i.length>0&&e.push({type:"reasoning",reasoning:i})}}let r=t.additional_kwargs?.reasoning_content;if(_(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let n of t.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&_(n.text)&&e.push({type:"text",text:n.text});for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}var Fa={translateContent:Ba,translateContentChunk:Ba};var pd=new Set(["SAFETY","PROHIBITED_CONTENT","BLOCKLIST"]);function hd(t){let e=t.response_metadata,r=t.additional_kwargs,n=e.finishReason??e.finish_reason??r.finishReason;if(!_(n)||!pd.has(n))return;let i=e.finishMessage??r.finishMessage;return{type:"refusal",refusal:_(i)?i:"",extras:{finishReason:n}}}function Ga(t){function*e(){let i=he(()=>{if(typeof t.content=="string")return t.additional_kwargs.originalTextContentBlock?[{...t.additional_kwargs.originalTextContentBlock,type:"text"}]:[{type:"text",text:t.content}];{let s=t.additional_kwargs?.originalTextContentBlock;if(s?.thoughtSignature&&!t.content.some(a=>"thoughtSignature"in a)){let a=[...t.content];for(let o=a.length-1;o>=0;o--){let c=a[o];if(c.type==="text"&&!c.thought)return c.thoughtSignature=s.thoughtSignature,a}}return t.content}});for(let s of i){let a=he(()=>x(s,"text")&&_(s.text)?{type:"text",text:s.text}:x(s,"inlineData")&&A(s.inlineData)&&_(s.inlineData.mimeType)&&_(s.inlineData.data)?{type:"file",mimeType:s.inlineData.mimeType,data:s.inlineData.data}:x(s,"functionCall")&&A(s.functionCall)&&_(s.functionCall.name)&&A(s.functionCall.args)?{type:"tool_call",id:t.id,name:s.functionCall.name,args:s.functionCall.args}:x(s,"functionResponse")?{type:"non_standard",value:s}:x(s,"fileData")&&A(s.fileData)&&_(s.fileData.mimeType)&&_(s.fileData.fileUri)?{type:"file",mimeType:s.fileData.mimeType,fileId:s.fileData.fileUri}:x(s,"executableCode")?{type:"non_standard",value:s}:x(s,"codeExecutionResult")?{type:"non_standard",value:s}:{type:"non_standard",value:s}),o=he(()=>"thought"in s&&s.thought?{type:"reasoning",reasoning:a.type==="text"?a.text:"",reasoningContentBlock:a}:a),c={thought:s.thought,thoughtSignature:s.thoughtSignature,partMetadata:s.partMetadata,...o};for(let l in c)c[l]===void 0&&delete c[l];yield c}}let r=Array.from(e()),n=hd(t);return n&&r.push(n),r}var za={translateContent:Ga,translateContentChunk:Ga};globalThis.lc_block_translators_registry??=new Map([["anthropic",la],["bedrock-converse",Pa],["deepseek",Ca],["google",za],["google-genai",ka],["google-vertexai",La],["groq",$a],["ollama",Ua],["openai",ma],["openrouter",Ha],["xai",Fa]]);function ei(t){return globalThis.lc_block_translators_registry.get(t)}function qa(t,e){return z(t,e)??{}}function Ka(t,e){let r={};return(t?.audio!==void 0||e?.audio!==void 0)&&(r.audio=(t?.audio??0)+(e?.audio??0)),(t?.image!==void 0||e?.image!==void 0)&&(r.image=(t?.image??0)+(e?.image??0)),(t?.video!==void 0||e?.video!==void 0)&&(r.video=(t?.video??0)+(e?.video??0)),(t?.document!==void 0||e?.document!==void 0)&&(r.document=(t?.document??0)+(e?.document??0)),(t?.text!==void 0||e?.text!==void 0)&&(r.text=(t?.text??0)+(e?.text??0)),r}function md(t,e){let r={...Ka(t,e)};return(t?.cache_read!==void 0||e?.cache_read!==void 0)&&(r.cache_read=(t?.cache_read??0)+(e?.cache_read??0)),(t?.cache_creation!==void 0||e?.cache_creation!==void 0)&&(r.cache_creation=(t?.cache_creation??0)+(e?.cache_creation??0)),r}function _d(t,e){let r={...Ka(t,e)};return(t?.reasoning!==void 0||e?.reasoning!==void 0)&&(r.reasoning=(t?.reasoning??0)+(e?.reasoning??0)),r}function Br(t,e){return{input_tokens:(t?.input_tokens??0)+(e?.input_tokens??0),output_tokens:(t?.output_tokens??0)+(e?.output_tokens??0),total_tokens:(t?.total_tokens??0)+(e?.total_tokens??0),input_token_details:md(t?.input_token_details,e?.input_token_details),output_token_details:_d(t?.output_token_details,e?.output_token_details)}}function Va(t){let e=Symbol.for(t);return{brand(r,n){let i=n?Symbol.for(`${t}.${n}`):e;class s extends r{[i]=!0;constructor(...o){super(...o)}static isInstance(o){return typeof o=="object"&&o!==null&&i in o&&o[i]===!0}static[Symbol.hasInstance](o){return this.isInstance(o)}}return Object.defineProperty(s,"name",{value:r.name}),s},sub(r){return Va(`${t}.${r}`)},isInstance(r){return typeof r=="object"&&r!==null&&e in r&&r[e]===!0}}}var Wa=Va("langchain");var $_=B({ContextOverflowError:()=>bd,LangChainError:()=>Gr,ModelAbortError:()=>yd,ModelRefusalError:()=>wd,addLangChainErrorFields:()=>ti,getRetryable:()=>gd,ns:()=>pr,stampRetryable:()=>Fr});function ti(t,e){return t.lc_error_code=e,t.message=`${t.message}
|
|
8
|
+
|
|
9
|
+
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
|
|
10
|
+
`,t}var pr=Wa.sub("error"),Xa=Symbol.for("langchain.errors.retryable");function Fr(t,e){if(typeof t!="object"||t===null)return t;try{Object.defineProperty(t,Xa,{value:e,configurable:!0})}catch{}return t}function gd(t){if(!(typeof t!="object"||t===null))return Object.getOwnPropertyDescriptor(t,Xa)?.value}var Gr=class extends pr.brand(Error){name="LangChainError";constructor(t){super(t),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},yd=class extends pr.brand(Gr,"model-abort"){name="ModelAbortError";partialOutput;constructor(t,e){super(t),this.partialOutput=e,Fr(this,!1)}},bd=class Qa extends pr.brand(Gr,"context-overflow"){name="ContextOverflowError";cause;constructor(e){super(e??"Input exceeded the model's context window."),Fr(this,!1)}static fromError(e){let r=new Qa(e.message);return r.cause=e,r}},Ja="Model refused to produce the requested output",wd=class Ya extends pr.brand(Gr,"model-refusal"){name="ModelRefusalError";rawMessage;constructor(e,r){super(e??Ja),this.rawMessage=r?.rawMessage,Fr(this,!1)}static fromRefusal(e,r){let n=Ja,i=e.extras?.category;return i&&(n+=` (category='${String(i)}')`),e.refusal&&(n+=`: ${e.refusal}`),new Ya(n,{rawMessage:r})}};function Za(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="tool_call")}function H_(t){return!!(t&&typeof t=="object"&&"toolCall"in t&&t.toolCall!=null&&typeof t.toolCall=="object"&&"id"in t.toolCall&&typeof t.toolCall.id=="string")}var B_=class extends Error{output;constructor(t,e){super(t),this.output=e}};function z_(t,e=ri){t=t.trim();let r=t.indexOf("```");if(r===-1)return e(t);let n=t.substring(r+3);n.startsWith(`json
|
|
11
|
+
`)?n=n.substring(5):n.startsWith("json")?n=n.substring(4):n.startsWith(`
|
|
12
|
+
`)&&(n=n.substring(1));let i=n.indexOf("```"),s=n;return i!==-1&&(s=n.substring(0,i)),e(s.trim())}function xd(t){try{return JSON.parse(t)}catch{}let e=t.trim();if(e.length===0)throw new Error("Unexpected end of JSON input");let r=0;function n(){for(;r<e.length&&/\s/.test(e[r]);)r+=1}function i(){if(e[r]!=='"')throw new Error(`Expected '"' at position ${r}, got '${e[r]}'`);r+=1;let u="",d=!1;for(;r<e.length;){let f=e[r];if(d){if(f==="n")u+=`
|
|
13
|
+
`;else if(f==="t")u+=" ";else if(f==="r")u+="\r";else if(f==="\\")u+="\\";else if(f==='"')u+='"';else if(f==="b")u+="\b";else if(f==="f")u+="\f";else if(f==="/")u+="/";else if(f==="u"){let p=e.substring(r+1,r+5);if(/^[0-9A-Fa-f]{0,4}$/.test(p))p.length===4?u+=String.fromCharCode(Number.parseInt(p,16)):u+=`u${p}`,r+=p.length;else throw new Error(`Invalid unicode escape sequence '\\u${p}' at position ${r}`)}else throw new Error(`Invalid escape sequence '\\${f}' at position ${r}`);d=!1}else if(f==="\\")d=!0;else{if(f==='"')return r+=1,u;u+=f}r+=1}return d&&(u+="\\"),u}function s(){let u=r,d="";if(e[r]==="-"&&(d+="-",r+=1),r<e.length&&e[r]==="0"&&(d+="0",r+=1,e[r]>="0"&&e[r]<="9"))throw new Error(`Invalid number at position ${u}`);if(r<e.length&&e[r]>="1"&&e[r]<="9")for(;r<e.length&&e[r]>="0"&&e[r]<="9";)d+=e[r],r+=1;if(r<e.length&&e[r]===".")for(d+=".",r+=1;r<e.length&&e[r]>="0"&&e[r]<="9";)d+=e[r],r+=1;if(r<e.length&&(e[r]==="e"||e[r]==="E"))for(d+=e[r],r+=1,r<e.length&&(e[r]==="+"||e[r]==="-")&&(d+=e[r],r+=1);r<e.length&&e[r]>="0"&&e[r]<="9";)d+=e[r],r+=1;if(d==="-")return-0;let f=Number.parseFloat(d);if(Number.isNaN(f))throw r=u,new Error(`Invalid number '${d}' at position ${u}`);return f}function a(){if(n(),r>=e.length)throw new Error(`Unexpected end of input at position ${r}`);let u=e[r];if(u==="{")return c();if(u==="[")return o();if(u==='"')return i();if("null".startsWith(e.substring(r,r+4)))return r+=Math.min(4,e.length-r),null;if("true".startsWith(e.substring(r,r+4)))return r+=Math.min(4,e.length-r),!0;if("false".startsWith(e.substring(r,r+5)))return r+=Math.min(5,e.length-r),!1;if(u==="-"||u>="0"&&u<="9")return s();throw new Error(`Unexpected character '${u}' at position ${r}`)}function o(){if(e[r]!=="[")throw new Error(`Expected '[' at position ${r}, got '${e[r]}'`);let u=[];if(r+=1,n(),r>=e.length)return u;if(e[r]==="]")return r+=1,u;for(;r<e.length;){if(n(),r>=e.length||(u.push(a()),n(),r>=e.length))return u;if(e[r]==="]")return r+=1,u;if(e[r]===","){r+=1;continue}throw new Error(`Expected ',' or ']' at position ${r}, got '${e[r]}'`)}return u}function c(){if(e[r]!=="{")throw new Error(`Expected '{' at position ${r}, got '${e[r]}'`);let u={};if(r+=1,n(),r>=e.length)return u;if(e[r]==="}")return r+=1,u;for(;r<e.length;){if(n(),r>=e.length)return u;let d=i();if(n(),r>=e.length)return u;if(e[r]!==":")throw new Error(`Expected ':' at position ${r}, got '${e[r]}'`);if(r+=1,n(),r>=e.length||(u[d]=a(),n(),r>=e.length))return u;if(e[r]==="}")return r+=1,u;if(e[r]===","){r+=1;continue}throw new Error(`Expected ',' or '}' at position ${r}, got '${e[r]}'`)}return u}let l=a();if(n(),r<e.length)throw new Error(`Unexpected character '${e[r]}' at position ${r}`);return l}function ri(t){try{return typeof t>"u"?null:xd(t)}catch{return null}}var ni=class eo extends ae{static lc_name(){return"ChatMessage"}type="generic";role;static _chatMessageClass(){return eo}constructor(e,r){(typeof e=="string"||Array.isArray(e))&&(e={content:e,role:r}),super(e),this.role=e.role}static isInstance(e){return super.isInstance(e)&&e.type==="generic"}static[Symbol.hasInstance](e){return this.isInstance(e)}get _printableFields(){return{...super._printableFields,role:this.role}}},to=class extends me{static lc_name(){return"ChatMessageChunk"}type="generic";role;constructor(t,e){(typeof t=="string"||Array.isArray(t))&&(t={content:t,role:e}),super(t),this.role=t.role}concat(t){let e=this.constructor;return new e({content:ue(this.content,t.content),additional_kwargs:z(this.additional_kwargs,t.additional_kwargs),response_metadata:z(this.response_metadata,t.response_metadata),role:this.role,id:this.id??t.id})}static isInstance(t){return super.isInstance(t)&&t.type==="generic"}static[Symbol.hasInstance](t){return this.isInstance(t)}get _printableFields(){return{...super._printableFields,role:this.role}}};function V_(t){return t._getType()==="generic"}function W_(t){return t._getType()==="generic"}var ro=class extends ae{static lc_name(){return"FunctionMessage"}type="function";name;constructor(t){super(t),this.name=t.name}static isInstance(t){return super.isInstance(t)&&t.type==="function"}static[Symbol.hasInstance](t){return this.isInstance(t)}},no=class extends me{static lc_name(){return"FunctionMessageChunk"}type="function";concat(t){let e=this.constructor;return new e({content:ue(this.content,t.content),additional_kwargs:z(this.additional_kwargs,t.additional_kwargs),response_metadata:z(this.response_metadata,t.response_metadata),name:this.name??"",id:this.id??t.id})}static isInstance(t){return super.isInstance(t)&&t.type==="function"}static[Symbol.hasInstance](t){return this.isInstance(t)}};function Y_(t){return t._getType()==="function"}function Z_(t){return t._getType()==="function"}var zr=class extends ae{static lc_name(){return"HumanMessage"}type="human";constructor(t){super(t)}static isInstance(t){return super.isInstance(t)&&t.type==="human"}static[Symbol.hasInstance](t){return this.isInstance(t)}},io=class extends me{static lc_name(){return"HumanMessageChunk"}type="human";constructor(t){super(t)}concat(t){let e=this.constructor;return new e({content:ue(this.content,t.content),additional_kwargs:z(this.additional_kwargs,t.additional_kwargs),response_metadata:z(this.response_metadata,t.response_metadata),id:this.id??t.id})}static isInstance(t){return super.isInstance(t)&&t.type==="human"}static[Symbol.hasInstance](t){return this.isInstance(t)}};function ig(t){return t.getType()==="human"}function sg(t){return t.getType()==="human"}var so=class extends ae{type="remove";id;constructor(t){super({...t,content:[]}),this.id=t.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(t){return super.isInstance(t)&&t.type==="remove"}static[Symbol.hasInstance](t){return this.isInstance(t)}};var Kr=class qr extends ae{static lc_name(){return"SystemMessage"}type="system";constructor(e){super(e)}concat(e){if(typeof e=="string")return new qr({content:ue(this.content,e),additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata,id:this.id,name:this.name});if(qr.isInstance(e))return new qr({content:ue(this.content,e.content),additional_kwargs:{...this.additional_kwargs,...e.additional_kwargs},response_metadata:{...this.response_metadata,...e.response_metadata},id:this.id??e.id,name:this.name??e.name});throw new Error("Unexpected chunk type for system message")}static isInstance(e){return super.isInstance(e)&&e.type==="system"}static[Symbol.hasInstance](e){return this.isInstance(e)}},ao=class extends me{static lc_name(){return"SystemMessageChunk"}type="system";constructor(t){super(t)}concat(t){let e=this.constructor;return new e({content:ue(this.content,t.content),additional_kwargs:z(this.additional_kwargs,t.additional_kwargs),response_metadata:z(this.response_metadata,t.response_metadata),id:this.id??t.id})}static isInstance(t){return super.isInstance(t)&&t.type==="system"}static[Symbol.hasInstance](t){return this.isInstance(t)}};function pg(t){return t._getType()==="system"}function hg(t){return t._getType()==="system"}function vd(t){return t.isCustomTool===!0}var Pg=t=>t();function Ed(t){return Za(t)?t:typeof t.id=="string"&&t.type==="function"&&typeof t.function=="object"&&t.function!==null&&"arguments"in t.function&&typeof t.function.arguments=="string"&&"name"in t.function&&typeof t.function.name=="string"?{id:t.id,args:JSON.parse(t.function.arguments),name:t.function.name,type:"tool_call"}:t}function Sd(t){return typeof t=="object"&&t!=null&&t.lc===1&&Array.isArray(t.id)&&t.kwargs!=null&&typeof t.kwargs=="object"}function ii(t){let e,r;if(Sd(t)){let n=t.id.at(-1);n==="HumanMessage"||n==="HumanMessageChunk"?e="user":n==="AIMessage"||n==="AIMessageChunk"?e="assistant":n==="SystemMessage"||n==="SystemMessageChunk"?e="system":n==="FunctionMessage"||n==="FunctionMessageChunk"?e="function":n==="ToolMessage"||n==="ToolMessageChunk"?e="tool":e="unknown",r=t.kwargs}else{let{type:n,...i}=t;e=n,r=i}if(e==="human"||e==="user")return new zr(r);if(e==="ai"||e==="assistant"){let{tool_calls:n,...i}=r;if(!Array.isArray(n))return new Mt(r);let s=n.map(Ed);return new Mt({...i,tool_calls:s})}else{if(e==="system")return new Kr(r);if(e==="developer")return new Kr({...r,additional_kwargs:{...r.additional_kwargs,__openai_role__:"developer"}});if(e==="tool"&&"tool_call_id"in r)return new Hr({...r,content:r.content,tool_call_id:r.tool_call_id,name:r.name});if(e==="remove"&&"id"in r&&typeof r.id=="string")return new so({...r,id:r.id});throw ti(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
|
|
14
|
+
|
|
15
|
+
Received: ${JSON.stringify(t,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function Rg(t){if(typeof t=="string")return new zr(t);if(Ia(t))return t;if(Array.isArray(t)){let[e,r]=t;return ii({type:e,content:r})}else if(Aa(t)){let{role:e,...r}=t;return ii({...r,type:e})}else return ii(t)}function Ad(t){if(typeof t=="string")return t;switch(t.type){case"text":return t.text??"";case"text-plain":return t.text??"[text-plain file]";case"image":case"image_url":return"[image]";case"audio":case"input_audio":return"[audio]";case"video":return"[video]";case"file":return"[file]";case"reasoning":case"tool_call":case"tool_call_chunk":case"invalid_tool_call":case"server_tool_call":case"server_tool_call_chunk":case"server_tool_call_result":case"non_standard":return"";default:return t.type?`[${t.type}]`:""}}var si=64;function co(t,e="Human",r="AI"){let n=[];for(let i of t){let s;if(i.type==="human")s=e;else if(i.type==="ai")s=r;else if(i.type==="system")s="System";else if(i.type==="tool")s="Tool";else if(i.type==="generic")s=i.role;else throw new Error(`Got unsupported message type: ${i.type}`);let a=i.name?`${i.name}, `:"",o=typeof i.content=="string"?i.content:Array.isArray(i.content)?i.content.map(Ad).filter(Boolean).join(""):"",c=`${s}: ${a}${o}`;if(i.type==="ai"){let l=i;if(l.tool_calls&&l.tool_calls.length>0){let u=l.tool_calls;c+=JSON.stringify(u.some(d=>(d.id?.length??0)>si)?u.map(d=>d.id&&d.id.length>si?{...d,id:`${d.id.slice(0,si)}...`}:d):u)}else l.additional_kwargs&&"function_call"in l.additional_kwargs&&(c+=JSON.stringify(l.additional_kwargs.function_call))}n.push(c)}return n.join(`
|
|
16
|
+
`)}function Id(t){if(t.data!==void 0)return t;{let e=t;return{type:e.type,data:{content:e.text,role:e.role,name:void 0,tool_call_id:void 0}}}}function Td(t){let e=Id(t);switch(e.type){case"human":return new zr(e.data);case"ai":return new Mt(e.data);case"system":return new Kr(e.data);case"function":if(e.data.name===void 0)throw new Error("Name must be defined for function messages");return new ro(e.data);case"tool":if(e.data.tool_call_id===void 0)throw new Error("Tool call ID must be defined for tool messages");return new Hr(e.data);case"generic":if(e.data.role===void 0)throw new Error("Role must be defined for chat messages");return new ni(e.data);default:throw new Error(`Got unexpected type: ${e.type}`)}}function Cg(t){return t.map(Td)}function Og(t){return t.map(e=>e.toDict())}function kg(t){let e=t._getType();if(e==="human")return new io({...t});if(e==="ai"){let r={...t};return"tool_calls"in r&&(r={...r,tool_call_chunks:r.tool_calls?.map(n=>({...n,type:"tool_call_chunk",index:void 0,args:JSON.stringify(n.args)}))}),new oo({...r})}else{if(e==="system")return new ao({...t});if(e==="function")return new no({...t});if(ni.isInstance(t))return new to({...t});throw new Error("Unknown message type.")}}function lo(t){let e=t.reduce((i,s)=>{let a=i.findIndex(([o])=>"id"in s&&s.id&&"index"in s&&s.index!==void 0?s.id===o.id&&s.index===o.index:"id"in s&&s.id?s.id===o.id:"index"in s&&s.index!==void 0?s.index===o.index:!1);return a!==-1?i[a].push(s):i.push([s]),i},[]),r=[],n=[];for(let i of e){let s=null,a=i.some(vd),o=i[0]?.name??"",c=i.map(f=>f.args||"").join(""),l=a?c:c.trim(),u=l.length?l:"{}",d=i.find(f=>f.id)?.id??i[0]?.id;if(a&&d){r.push({name:o,args:{input:l},id:d,type:"tool_call"});continue}try{if(s=ri(u),!d||s===null||typeof s!="object"||Array.isArray(s))throw new Error("Malformed tool call chunk args.");r.push({name:o,args:s,id:d,type:"tool_call"})}catch{n.push({name:o,args:u,id:d,error:"Malformed args.",type:"invalid_tool_call"})}}return{tool_call_chunks:t,tool_calls:r,invalid_tool_calls:n}}function uo(t){return typeof t=="string"?t.length>0?[{type:"text",text:t}]:[]:Array.isArray(t)?t:t==null?[]:[t]}var Mt=class extends ae{type="ai";tool_calls=[];invalid_tool_calls=[];usage_metadata;get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",usage_metadata:"usage_metadata"}}constructor(t){let e;if(typeof t=="string"||Array.isArray(t))e={content:t,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{e=t;let r=e.additional_kwargs?.tool_calls,n=e.tool_calls;r!=null&&r.length>0&&(n===void 0||n.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
|
|
17
|
+
|
|
18
|
+
Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(r!=null&&n===void 0){let[i,s]=Yn(r);e.tool_calls=i??[],e.invalid_tool_calls=s??[]}else e.tool_calls=e.tool_calls??[],e.invalid_tool_calls=e.invalid_tool_calls??[]}catch{e.tool_calls=[],e.invalid_tool_calls=[]}if(e.response_metadata!==void 0&&"output_version"in e.response_metadata&&e.response_metadata.output_version==="v1"&&e.content!==void 0&&(e.contentBlocks=uo(e.content),e.content=void 0),e.contentBlocks!==void 0){if(Array.isArray(e.contentBlocks)||(e.contentBlocks=uo(e.contentBlocks)),e.tool_calls){let s=e.tool_calls.filter(a=>!e.contentBlocks?.some(o=>o.type==="tool_call"&&o.id===a.id&&o.name===a.name));e.contentBlocks.push(...s.map(a=>({type:"tool_call",id:a.id,name:a.name,args:a.args})))}let i=e.contentBlocks.filter(s=>s.type==="tool_call").filter(s=>!e.tool_calls?.some(a=>a.id===s.id&&a.name===s.name));i.length>0&&(e.tool_calls=[...e.tool_calls??[],...i.map(s=>({type:"tool_call",id:s.id,name:s.name,args:s.args}))])}}super(e),typeof e!="string"&&(this.tool_calls=e.tool_calls??this.tool_calls,this.invalid_tool_calls=e.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=e.usage_metadata}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){let e=ei(this.response_metadata.model_provider);if(e)return e.translateContent(this)}let t=super.contentBlocks;if(this.tool_calls){let e=this.tool_calls.filter(r=>!t.some(n=>n.id===r.id&&n.name===r.name));t.push(...e.map(r=>({type:"tool_call",id:r.id,name:r.name,args:r.args})))}return t}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(t){return super.isInstance(t)&&t.type==="ai"}static[Symbol.hasInstance](t){return this.isInstance(t)}};function Dg(t){return t._getType()==="ai"}function Hg(t){return t._getType()==="ai"}var oo=class extends me{type="ai";tool_calls=[];invalid_tool_calls=[];tool_call_chunks=[];usage_metadata;constructor(t){let e;typeof t=="string"||Array.isArray(t)?e={content:t,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]}:t.tool_call_chunks===void 0||t.tool_call_chunks.length===0?e={...t,tool_calls:t.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:t.usage_metadata!==void 0?t.usage_metadata:void 0}:e={...t,usage_metadata:t.usage_metadata!==void 0?t.usage_metadata:void 0},super(e),this.tool_call_chunks=e.tool_call_chunks??this.tool_call_chunks,typeof t!="string"&&!Array.isArray(t)&&t.tool_call_chunks!==void 0&&t.tool_call_chunks.length>0?this._defineLazyToolCallGetters(t.tool_call_chunks.map(r=>({...r}))):(this.tool_calls=e.tool_calls??this.tool_calls,this.invalid_tool_calls=e.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=e.usage_metadata}_defineLazyToolCallGetters(t){let e,r=()=>(e??=lo(t),e),n=(i,s)=>{Object.defineProperty(i,s,{get:()=>r()[s],set:a=>{Object.defineProperty(i,s,{value:a,writable:!0,enumerable:!0,configurable:!0})},enumerable:!0,configurable:!0})};n(this,"tool_calls"),n(this,"invalid_tool_calls"),n(this.lc_kwargs,"tool_calls"),n(this.lc_kwargs,"invalid_tool_calls")}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks",usage_metadata:"usage_metadata"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){let e=ei(this.response_metadata.model_provider);if(e)return e.translateContent(this)}let t=super.contentBlocks;if(this.tool_calls&&typeof this.content!="string"){let e=this.content.filter(r=>r.type==="tool_call").map(r=>r.id);for(let r of this.tool_calls)r.id&&!e.includes(r.id)&&t.push({...r,type:"tool_call",id:r.id,name:r.name,args:r.args})}return t}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(t){let e={content:ue(this.content,t.content),additional_kwargs:z(this.additional_kwargs,t.additional_kwargs),response_metadata:qa(this.response_metadata,t.response_metadata),tool_call_chunks:[],tool_calls:[],id:this.id??t.id};if(this.tool_call_chunks!==void 0||t.tool_call_chunks!==void 0){let n=Lt(this.tool_call_chunks,t.tool_call_chunks);n!==void 0&&n.length>0&&(e.tool_call_chunks=n)}if((e.tool_call_chunks===void 0||e.tool_call_chunks.length===0)&&(this.tool_calls!==void 0||t.tool_calls!==void 0)){let n=Lt(this.tool_calls,t.tool_calls);n!==void 0&&n.length>0&&(e.tool_calls=n)}(this.usage_metadata!==void 0||t.usage_metadata!==void 0)&&(e.usage_metadata=Br(this.usage_metadata,t.usage_metadata));let r=this.constructor;return new r(e)}static isInstance(t){return super.isInstance(t)&&t.type==="ai"}static[Symbol.hasInstance](t){return this.isInstance(t)}};var fo="ffffffff-ffff-ffff-ffff-ffffffffffff";var po="00000000-0000-0000-0000-000000000000";var ho=/^(?:[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 qe(t){return typeof t=="string"&&ho.test(t)}function nt(t){if(!qe(t))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(t.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(t.slice(9,13),16))>>>8,e&255,(e=parseInt(t.slice(14,18),16))>>>8,e&255,(e=parseInt(t.slice(19,23),16))>>>8,e&255,(e=parseInt(t.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}var Z=[];for(let t=0;t<256;++t)Z.push((t+256).toString(16).slice(1));function _e(t,e=0){return(Z[t[e+0]]+Z[t[e+1]]+Z[t[e+2]]+Z[t[e+3]]+"-"+Z[t[e+4]]+Z[t[e+5]]+"-"+Z[t[e+6]]+Z[t[e+7]]+"-"+Z[t[e+8]]+Z[t[e+9]]+"-"+Z[t[e+10]]+Z[t[e+11]]+Z[t[e+12]]+Z[t[e+13]]+Z[t[e+14]]+Z[t[e+15]]).toLowerCase()}function mo(t,e=0){let r=_e(t,e);if(!qe(r))throw TypeError("Stringified UUID is invalid");return r}var Pd=new Uint8Array(16);function Ke(){return crypto.getRandomValues(Pd)}var hr={};function Vr(t,e,r){let n,i=t?._v6??!1;if(t){let s=Object.keys(t);s.length===1&&s[0]==="_v6"&&(t=void 0)}if(t)n=_o(t.random??t.rng?.()??Ke(),t.msecs,t.nsecs,t.clockseq,t.node,e,r);else{let s=Date.now(),a=Ke();Rd(hr,s,a),n=_o(a,hr.msecs,hr.nsecs,i?void 0:hr.clockseq,i?void 0:hr.node,e,r)}return e??_e(n)}function Rd(t,e,r){return t.msecs??=-1/0,t.nsecs??=0,e===t.msecs?(t.nsecs++,t.nsecs>=1e4&&(t.node=void 0,t.nsecs=0)):e>t.msecs?t.nsecs=0:e<t.msecs&&(t.node=void 0),t.node||(t.node=r.slice(10,16),t.node[0]|=1,t.clockseq=(r[8]<<8|r[9])&16383),t.msecs=e,t}function _o(t,e,r,n,i,s,a=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!s)s=new Uint8Array(16),a=0;else if(a<0||a+16>s.length)throw new RangeError(`UUID byte range ${a}:${a+15} is out of buffer bounds`);e??=Date.now(),r??=0,n??=(t[8]<<8|t[9])&16383,i??=t.slice(10,16),e+=122192928e5;let o=((e&268435455)*1e4+r)%4294967296;s[a++]=o>>>24&255,s[a++]=o>>>16&255,s[a++]=o>>>8&255,s[a++]=o&255;let c=e/4294967296*1e4&268435455;s[a++]=c>>>8&255,s[a++]=c&255,s[a++]=c>>>24&15|16,s[a++]=c>>>16&255,s[a++]=n>>>8|128,s[a++]=n&255;for(let l=0;l<6;++l)s[a++]=i[l];return s}function go(t,e,r){return!e&&!t&&crypto.randomUUID?crypto.randomUUID():Cd(t,e,r)}function Cd(t,e,r){t=t||{};let n=t.random??t.rng?.()??Ke();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;++i)e[r+i]=n[i];return e}return _e(n)}function Od(t,e,r,n){switch(t){case 0:return e&r^~e&n;case 1:return e^r^n;case 2:return e&r^e&n^r&n;case 3:return e^r^n}}function ai(t,e){return t<<e|t>>>32-e}function yo(t){let e=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520],n=new Uint8Array(t.length+1);n.set(t),n[t.length]=128,t=n;let i=t.length/4+2,s=Math.ceil(i/16),a=new Array(s);for(let o=0;o<s;++o){let c=new Uint32Array(16);for(let l=0;l<16;++l)c[l]=t[o*64+l*4]<<24|t[o*64+l*4+1]<<16|t[o*64+l*4+2]<<8|t[o*64+l*4+3];a[o]=c}a[s-1][14]=(t.length-1)*8/2**32,a[s-1][14]=Math.floor(a[s-1][14]),a[s-1][15]=(t.length-1)*8&4294967295;for(let o=0;o<s;++o){let c=new Uint32Array(80);for(let h=0;h<16;++h)c[h]=a[o][h];for(let h=16;h<80;++h)c[h]=ai(c[h-3]^c[h-8]^c[h-14]^c[h-16],1);let l=r[0],u=r[1],d=r[2],f=r[3],p=r[4];for(let h=0;h<80;++h){let m=Math.floor(h/20),w=ai(l,5)+Od(m,u,d,f)+p+e[m]+c[h]>>>0;p=f,f=d,d=ai(u,30)>>>0,u=l,l=w}r[0]=r[0]+l>>>0,r[1]=r[1]+u>>>0,r[2]=r[2]+d>>>0,r[3]=r[3]+f>>>0,r[4]=r[4]+p>>>0}return Uint8Array.of(r[0]>>24,r[0]>>16,r[0]>>8,r[0],r[1]>>24,r[1]>>16,r[1]>>8,r[1],r[2]>>24,r[2]>>16,r[2]>>8,r[2],r[3]>>24,r[3]>>16,r[3]>>8,r[3],r[4]>>24,r[4]>>16,r[4]>>8,r[4])}function kd(t){t=unescape(encodeURIComponent(t));let e=new Uint8Array(t.length);for(let r=0;r<t.length;++r)e[r]=t.charCodeAt(r);return e}var bo="6ba7b810-9dad-11d1-80b4-00c04fd430c8",wo="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function xo(t,e,r,n,i,s){let a=typeof r=="string"?kd(r):r,o=typeof n=="string"?nt(n):n;if(typeof n=="string"&&(n=nt(n)),n?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+a.length);if(c.set(o),c.set(a,o.length),c=e(c),c[6]=c[6]&15|t,c[8]=c[8]&63|128,i){if(s??=0,s<0||s+16>i.length)throw new RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`);for(let l=0;l<16;++l)i[s+l]=c[l];return i}return _e(c)}function Wr(t,e,r,n){return xo(80,yo,t,e,r,n)}Wr.DNS=bo;Wr.URL=wo;function vo(t){let e=Nd(typeof t=="string"?nt(t):t);return typeof t=="string"?_e(e):e}function Nd(t){return Uint8Array.of((t[6]&15)<<4|t[7]>>4&15,(t[7]&15)<<4|(t[4]&240)>>4,(t[4]&15)<<4|(t[5]&240)>>4,(t[5]&15)<<4|(t[0]&240)>>4,(t[0]&15)<<4|(t[1]&240)>>4,(t[1]&15)<<4|(t[2]&240)>>4,96|t[2]&15,t[3],t[8],t[9],t[10],t[11],t[12],t[13],t[14],t[15])}function Eo(t,e,r){t??={},r??=0;let n=Vr({...t,_v6:!0},new Uint8Array(16));if(n=vo(n),e){if(r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;i++)e[r+i]=n[i];return e}return _e(n)}var oi={};function Ao(t,e,r){let n;if(t)n=So(t.random??t.rng?.()??Ke(),t.msecs,t.seq,e,r);else{let i=Date.now(),s=Ke();Ld(oi,i,s),n=So(s,oi.msecs,oi.seq,e,r)}return e??_e(n)}function Ld(t,e,r){return t.msecs??=-1/0,t.seq??=0,e>t.msecs?(t.seq=r[6]<<23|r[7]<<16|r[8]<<8|r[9],t.msecs=e):(t.seq=t.seq+1|0,t.seq===0&&t.msecs++),t}function So(t,e,r,n,i=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!n)n=new Uint8Array(16),i=0;else if(i<0||i+16>n.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return e??=Date.now(),r??=t[6]*127<<24|t[7]<<16|t[8]<<8|t[9],n[i++]=e/1099511627776&255,n[i++]=e/4294967296&255,n[i++]=e/16777216&255,n[i++]=e/65536&255,n[i++]=e/256&255,n[i++]=e&255,n[i++]=112|r>>>28&15,n[i++]=r>>>20&255,n[i++]=128|r>>>14&63,n[i++]=r>>>6&255,n[i++]=r<<2&255|t[10]&3,n[i++]=t[11],n[i++]=t[12],n[i++]=t[13],n[i++]=t[14],n[i++]=t[15],n}function Io(t){if(!qe(t))throw TypeError("Invalid UUID");return parseInt(t.slice(14,15),16)}var jy=B({MAX:()=>Md,NIL:()=>$d,parse:()=>jd,stringify:()=>Ud,v1:()=>Dd,v4:()=>Hd,v5:()=>Bd,v6:()=>Fd,v7:()=>Ie,validate:()=>Gd,version:()=>zd}),Md=fo,$d=po,jd=nt,Ud=mo,Dd=Vr,Hd=go,Bd=Wr,Fd=Eo,Ie=Ao,Gd=qe,zd=Io;var Hy=B({getEnv:()=>Oo,getEnvironmentVariable:()=>Ee,getRuntimeEnvironment:()=>li,isBrowser:()=>To,isDeno:()=>Jr,isJsDom:()=>Ro,isNode:()=>Co,isWebWorker:()=>Po}),To=()=>typeof window<"u"&&typeof window.document<"u",Po=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Ro=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),Jr=()=>typeof Deno<"u",Co=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Jr(),Oo=()=>{let t;return To()?t="browser":Co()?t="node":Po()?t="webworker":Ro()?t="jsdom":Jr()?t="deno":t="other",t},ci;function li(){return ci===void 0&&(ci={library:"langchain-js",runtime:Oo()}),ci}function Ee(t){try{return typeof process<"u"?process.env?.[t]:Jr()?Deno?.env.get(t):void 0}catch{return}}var Ky=B({BaseCallbackHandler:()=>it,callbackHandlerPrefersChatModelStreamEvents:()=>Vd,callbackHandlerPrefersStreaming:()=>Kd,isBaseCallbackHandler:()=>ui}),qd=class{};function Kd(t){return"lc_prefer_streaming"in t&&t.lc_prefer_streaming}function Vd(t){return"lc_prefer_chat_model_stream_events"in t&&t.lc_prefer_chat_model_stream_events}var it=class extends qd{lc_serializable=!1;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,jr(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=Ee("LANGCHAIN_CALLBACKS_BACKGROUND")==="false";constructor(t){super(),this.lc_kwargs=t||{},t&&(this.ignoreLLM=t.ignoreLLM??this.ignoreLLM,this.ignoreChain=t.ignoreChain??this.ignoreChain,this.ignoreAgent=t.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=t.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=t.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=t.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(t._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return Nt.prototype.toJSON.call(this)}toJSONNotImplemented(){return Nt.prototype.toJSONNotImplemented.call(this)}static fromMethods(t){class e extends it{name=Ie();constructor(){super(),Object.assign(this,t)}}return new e}},ui=t=>{let e=t;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"};var ko=/^(?:[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 Wd(t){return typeof t=="string"&&ko.test(t)}var mr=Wd;function Jd(t){if(!mr(t))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(t.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(t.slice(9,13),16))>>>8,e&255,(e=parseInt(t.slice(14,18),16))>>>8,e&255,(e=parseInt(t.slice(19,23),16))>>>8,e&255,(e=parseInt(t.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}var Xr=Jd;var ee=[];for(let t=0;t<256;++t)ee.push((t+256).toString(16).slice(1));function $t(t,e=0){return(ee[t[e+0]]+ee[t[e+1]]+ee[t[e+2]]+ee[t[e+3]]+"-"+ee[t[e+4]]+ee[t[e+5]]+"-"+ee[t[e+6]]+ee[t[e+7]]+"-"+ee[t[e+8]]+ee[t[e+9]]+"-"+ee[t[e+10]]+ee[t[e+11]]+ee[t[e+12]]+ee[t[e+13]]+ee[t[e+14]]+ee[t[e+15]]).toLowerCase()}var Xd=new Uint8Array(16);function jt(){return crypto.getRandomValues(Xd)}function Qd(t,e,r){return!e&&!t&&crypto.randomUUID?crypto.randomUUID():Yd(t,e,r)}function Yd(t,e,r){t=t||{};let n=t.random??t.rng?.()??jt();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;++i)e[r+i]=n[i];return e}return $t(n)}var st=Qd;function Zd(t,e,r,n){switch(t){case 0:return e&r^~e&n;case 1:return e^r^n;case 2:return e&r^e&n^r&n;case 3:return e^r^n}}function di(t,e){return t<<e|t>>>32-e}function ef(t){let e=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520],n=new Uint8Array(t.length+1);n.set(t),n[t.length]=128,t=n;let i=t.length/4+2,s=Math.ceil(i/16),a=new Array(s);for(let o=0;o<s;++o){let c=new Uint32Array(16);for(let l=0;l<16;++l)c[l]=t[o*64+l*4]<<24|t[o*64+l*4+1]<<16|t[o*64+l*4+2]<<8|t[o*64+l*4+3];a[o]=c}a[s-1][14]=(t.length-1)*8/2**32,a[s-1][14]=Math.floor(a[s-1][14]),a[s-1][15]=(t.length-1)*8&4294967295;for(let o=0;o<s;++o){let c=new Uint32Array(80);for(let h=0;h<16;++h)c[h]=a[o][h];for(let h=16;h<80;++h)c[h]=di(c[h-3]^c[h-8]^c[h-14]^c[h-16],1);let l=r[0],u=r[1],d=r[2],f=r[3],p=r[4];for(let h=0;h<80;++h){let m=Math.floor(h/20),w=di(l,5)+Zd(m,u,d,f)+p+e[m]+c[h]>>>0;p=f,f=d,d=di(u,30)>>>0,u=l,l=w}r[0]=r[0]+l>>>0,r[1]=r[1]+u>>>0,r[2]=r[2]+d>>>0,r[3]=r[3]+f>>>0,r[4]=r[4]+p>>>0}return Uint8Array.of(r[0]>>24,r[0]>>16,r[0]>>8,r[0],r[1]>>24,r[1]>>16,r[1]>>8,r[1],r[2]>>24,r[2]>>16,r[2]>>8,r[2],r[3]>>24,r[3]>>16,r[3]>>8,r[3],r[4]>>24,r[4]>>16,r[4]>>8,r[4])}var No=ef;function tf(t){t=unescape(encodeURIComponent(t));let e=new Uint8Array(t.length);for(let r=0;r<t.length;++r)e[r]=t.charCodeAt(r);return e}var fi="6ba7b810-9dad-11d1-80b4-00c04fd430c8",pi="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function hi(t,e,r,n,i,s){let a=typeof r=="string"?tf(r):r,o=typeof n=="string"?Xr(n):n;if(typeof n=="string"&&(n=Xr(n)),n?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+a.length);if(c.set(o),c.set(a,o.length),c=e(c),c[6]=c[6]&15|t,c[8]=c[8]&63|128,i){if(s??(s=0),s<0||s+16>i.length)throw new RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`);for(let l=0;l<16;++l)i[s+l]=c[l];return i}return $t(c)}function mi(t,e,r,n){return hi(80,No,t,e,r,n)}mi.DNS=fi;mi.URL=pi;var _i=mi;var gi={};function rf(t,e,r){let n;if(t)n=Lo(t.random??t.rng?.()??jt(),t.msecs,t.seq,e,r);else{let i=Date.now(),s=jt();nf(gi,i,s),n=Lo(s,gi.msecs,gi.seq,e,r)}return e??$t(n)}function nf(t,e,r){return t.msecs??(t.msecs=-1/0),t.seq??(t.seq=0),e>t.msecs?(t.seq=r[6]<<23|r[7]<<16|r[8]<<8|r[9],t.msecs=e):(t.seq=t.seq+1|0,t.seq===0&&t.msecs++),t}function Lo(t,e,r,n,i=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!n)n=new Uint8Array(16),i=0;else if(i<0||i+16>n.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return e??(e=Date.now()),r??(r=t[6]*127<<24|t[7]<<16|t[8]<<8|t[9]),n[i++]=e/1099511627776&255,n[i++]=e/4294967296&255,n[i++]=e/16777216&255,n[i++]=e/65536&255,n[i++]=e/256&255,n[i++]=e&255,n[i++]=112|r>>>28&15,n[i++]=r>>>20&255,n[i++]=128|r>>>14&63,n[i++]=r>>>6&255,n[i++]=r<<2&255|t[10]&3,n[i++]=t[11],n[i++]=t[12],n[i++]=t[13],n[i++]=t[14],n[i++]=t[15],n}var Ut=rf;function Mo(t){let e=t.replace(/\/$/,"");for(let r of["/api/v1","/api"])if(e.endsWith(r))return e.slice(0,-r.length);return e}var $o="gen_ai.operation.name",jo="gen_ai.system",yi="gen_ai.request.model",Uo="gen_ai.response.model",bi="gen_ai.usage.input_tokens",wi="gen_ai.usage.output_tokens",xi="gen_ai.usage.total_tokens",Do="gen_ai.request.max_tokens",Ho="gen_ai.request.temperature",Bo="gen_ai.request.top_p",Fo="gen_ai.request.frequency_penalty",Go="gen_ai.request.presence_penalty",zo="gen_ai.response.finish_reasons",qo="gen_ai.prompt",Ko="gen_ai.completion",Vo="gen_ai.request.extra_query",Wo="gen_ai.request.extra_body",Jo="gen_ai.serialized.name",Xo="gen_ai.serialized.signature",Qo="gen_ai.serialized.doc",Yo="gen_ai.response.id",Zo="gen_ai.tool.name",ec="gen_ai.tool.call.id",tc="gen_ai.tool.definitions",rc="gen_ai.response.service_tier",nc="gen_ai.response.system_fingerprint",ic="gen_ai.usage.input_token_details",sc="gen_ai.usage.output_token_details",ac="langsmith.trace.session_id",oc="langsmith.trace.session_name",cc="langsmith.span.kind",lc="langsmith.trace.name",uc="langsmith.metadata",vi="langsmith.span.tags";var dc="langsmith.request.streaming",fc="langsmith.request.headers";var Ei="langsmith.usage_metadata";var Ii=class{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...r){!this.hasWarned&&Yr()==="otel"&&(console.warn('OTel tracing mode is active (via LANGSMITH_TRACING_MODE, OTEL_ENABLED, or LANGSMITH_OTEL_ENABLED), but the required OTEL instances have not been initialized. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let n;if(r.length===1&&typeof r[0]=="function"?n=r[0]:r.length===2&&typeof r[1]=="function"?n=r[1]:r.length===3&&typeof r[2]=="function"&&(n=r[2]),typeof n=="function")return n()}},Ti=class{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new Ii})}getTracer(e,r){return this.mockTracer}getActiveSpan(){}setSpan(e,r){return e}getSpan(e){}setSpanContext(e,r){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},Pi=class{active(){return{}}with(e,r){return r()}},Si=Symbol.for("ls:otel_trace"),Ai=Symbol.for("ls:otel_context"),pc=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),of=new Ti,cf=new Pi,Ri=class{getTraceInstance(){return globalThis[Si]??of}getContextInstance(){return globalThis[Ai]??cf}initializeGlobalInstances(e){globalThis[Si]===void 0&&(globalThis[Si]=e.trace),globalThis[Ai]===void 0&&(globalThis[Ai]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[pc]=e}getDefaultOTLPTracerComponents(){return globalThis[pc]??void 0}},Ci=new Ri;function Qr(){return Ci.getTraceInstance()}function hc(){return Ci.getContextInstance()}function mc(){return Ci.getDefaultOTLPTracerComponents()}var lf={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function uf(t){return lf[t]||t}function df(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"}var Zr=class{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,r){for(let n of e)try{if(!n.run)continue;if(n.operation==="post"){let i=this.createSpanForRun(n,n.run,r.get(n.id));i&&!n.run.end_time&&this.spans.set(n.id,i)}else this.updateSpanForRun(n,n.run)}catch(i){console.error(`Error processing operation ${n.id}:`,i)}}createSpanForRun(e,r,n){let i=n&&Qr().getSpan(n);if(i)try{return this.finishSpanSetup(i,r,e)}catch(s){console.error(`Failed to create span for run ${e.id}:`,s);return}}finishSpanSetup(e,r,n){return this.setSpanAttributes(e,r,n),r.error?(e.setStatus({code:2}),e.recordException(new Error(r.error))):e.setStatus({code:1}),r.end_time&&e.end(new Date(r.end_time)),e}updateSpanForRun(e,r){try{let n=this.spans.get(e.id);if(!n){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(n,r,e),r.error?(n.setStatus({code:2}),n.recordException(new Error(r.error))):n.setStatus({code:1});let i=r.end_time;i&&(n.end(new Date(i)),this.spans.delete(e.id))}catch(n){console.error(`Failed to update span for run ${e.id}:`,n)}}extractModelName(e){if(e.extra?.metadata){let r=e.extra.metadata;if(r.ls_model_name)return r.ls_model_name;if(r.invocation_params){let n=r.invocation_params;if(n.model)return n.model;if(n.model_name)return n.model_name}}}setSpanAttributes(e,r,n){if("run_type"in r&&r.run_type){e.setAttribute(cc,r.run_type);let o=uf(r.run_type||"chain");e.setAttribute($o,o)}"name"in r&&r.name&&e.setAttribute(lc,r.name),"session_id"in r&&r.session_id&&e.setAttribute(ac,r.session_id),"session_name"in r&&r.session_name&&e.setAttribute(oc,r.session_name),this.setGenAiSystem(e,r);let i=this.extractModelName(r);if(i&&e.setAttribute(yi,i),r.extra?.metadata?.usage_metadata&&typeof r.extra.metadata.usage_metadata=="object"&&e.setAttribute(Ei,JSON.stringify(r.extra.metadata.usage_metadata)),"prompt_tokens"in r&&typeof r.prompt_tokens=="number"&&e.setAttribute(bi,r.prompt_tokens),"completion_tokens"in r&&typeof r.completion_tokens=="number"&&e.setAttribute(wi,r.completion_tokens),"total_tokens"in r&&typeof r.total_tokens=="number"&&e.setAttribute(xi,r.total_tokens),this.setInvocationParameters(e,r),"run_type"in r&&r.run_type==="tool"){"name"in r&&r.name&&e.setAttribute(Zo,r.name);let o=r.extra?.tool_call_id||r.extra?.metadata?.tool_call_id;o!=null&&e.setAttribute(ec,String(o))}let s=r.extra?.metadata||{};for(let[o,c]of Object.entries(s))c!=null&&e.setAttribute(`${uc}.${o}`,df(c)?String(c):JSON.stringify(c));let a=r.tags;if(a&&Array.isArray(a)?e.setAttribute(vi,a.join(", ")):a&&e.setAttribute(vi,String(a)),"serialized"in r&&typeof r.serialized=="object"){let o=r.serialized;o.name&&e.setAttribute(Jo,String(o.name)),o.signature&&e.setAttribute(Xo,String(o.signature)),o.doc&&e.setAttribute(Qo,String(o.doc))}this.setIOAttributes(e,n)}setGenAiSystem(e,r){let n="langchain",i=this.extractModelName(r);if(i){let s=i.toLowerCase();s.includes("anthropic")||s.startsWith("claude")?n="anthropic":s.includes("bedrock")?n="aws.bedrock":s.includes("azure")&&s.includes("openai")?n="az.ai.openai":s.includes("azure")&&s.includes("inference")?n="az.ai.inference":s.includes("cohere")?n="cohere":s.includes("deepseek")?n="deepseek":s.includes("gemini")?n="gemini":s.includes("groq")?n="groq":s.includes("watson")||s.includes("ibm")?n="ibm.watsonx.ai":s.includes("mistral")?n="mistral_ai":s.includes("gpt")||s.includes("openai")?n="openai":s.includes("perplexity")||s.includes("sonar")?n="perplexity":s.includes("vertex")?n="vertex_ai":(s.includes("xai")||s.includes("grok"))&&(n="xai")}e.setAttribute(jo,n)}setInvocationParameters(e,r){let n=r.extra?.invocation_params?.tools;if(Array.isArray(n)&&n.length>0&&e.setAttribute(tc,JSON.stringify(n)),!r.extra?.metadata?.invocation_params)return;let i=r.extra.metadata.invocation_params;i.max_tokens!==void 0&&e.setAttribute(Do,i.max_tokens),i.temperature!==void 0&&e.setAttribute(Ho,i.temperature),i.top_p!==void 0&&e.setAttribute(Bo,i.top_p),i.frequency_penalty!==void 0&&e.setAttribute(Fo,i.frequency_penalty),i.presence_penalty!==void 0&&e.setAttribute(Go,i.presence_penalty)}setIOAttributes(e,r){if(r.run.inputs)try{let n=r.run.inputs;typeof n=="object"&&n!==null&&(n.model&&Array.isArray(n.messages)&&e.setAttribute(yi,n.model),n.stream!==void 0&&e.setAttribute(dc,n.stream),n.extra_headers&&e.setAttribute(fc,JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute(Vo,JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute(Wo,JSON.stringify(n.extra_body))),e.setAttribute(qo,JSON.stringify(n))}catch(n){console.debug(`Failed to process inputs for run ${r.id}`,n)}if(r.run.outputs)try{let n=r.run.outputs,i=this.getUnifiedRunTokens(n);if(i&&(e.setAttribute(bi,i[0]),e.setAttribute(wi,i[1]),e.setAttribute(xi,i[0]+i[1])),n&&typeof n=="object"){if(n.model&&e.setAttribute(Uo,String(n.model)),n.id&&e.setAttribute(Yo,n.id),n.choices&&Array.isArray(n.choices)){let s=n.choices.map(a=>a.finish_reason).filter(a=>a).map(String);s.length>0&&e.setAttribute(zo,s.join(", "))}if(n.service_tier&&e.setAttribute(rc,n.service_tier),n.system_fingerprint&&e.setAttribute(nc,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata=="object"){let s=n.usage_metadata;e.setAttribute(Ei,JSON.stringify(s)),s.input_token_details&&e.setAttribute(ic,JSON.stringify(s.input_token_details)),s.output_token_details&&e.setAttribute(sc,JSON.stringify(s.output_token_details))}}e.setAttribute(Ko,JSON.stringify(n))}catch(n){console.debug(`Failed to process outputs for run ${r.id}`,n)}}getUnifiedRunTokens(e){if(!e)return null;let r=this.extractUnifiedRunTokens(e.usage_metadata);if(r)return r;let n=Object.keys(e);for(let a of n){let o=e[a];if(!(!o||typeof o!="object")&&(r=this.extractUnifiedRunTokens(o.usage_metadata),r||o.lc===1&&o.kwargs&&typeof o.kwargs=="object"&&(r=this.extractUnifiedRunTokens(o.kwargs.usage_metadata),r)))return r}let i=e.generations||[];if(!Array.isArray(i))return null;let s=Array.isArray(i[0])?i.flat():i;for(let a of s)if(typeof a=="object"&&a.message&&typeof a.message=="object"&&a.message.kwargs&&typeof a.message.kwargs=="object"&&(r=this.extractUnifiedRunTokens(a.message.kwargs.usage_metadata),r))return r;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 ff=Object.prototype.toString,pf=t=>ff.call(t)==="[object Error]",hf=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function Oi(t){if(!(t&&pf(t)&&t.name==="TypeError"&&typeof t.message=="string"))return!1;let{message:r,stack:n}=t;return r==="Load failed"?n===void 0||"__sentry_captured__"in t:r.startsWith("error sending request for url")?!0:hf.has(r)}function mf(t){if(typeof t=="number"){if(t<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(t))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(t!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function en(t,e,{min:r=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${t}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${t}\` to be a finite number.`);if(e<r)throw new TypeError(`Expected \`${t}\` to be \u2265 ${r}.`)}}var ki=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function _f(t,e){let r=Math.max(1,t+1),n=e.randomize?Math.random()+1:1,i=Math.round(n*e.minTimeout*e.factor**(r-1));return i=Math.min(i,e.maxTimeout),i}function _c(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}async function gf({error:t,attemptNumber:e,retriesConsumed:r,startTime:n,options:i}){let s=t instanceof Error?t:new TypeError(`Non-error was thrown: "${t}". You should only throw errors.`);if(s instanceof ki)throw s.originalError;let a=Number.isFinite(i.retries)?Math.max(0,i.retries-r):i.retries,o=i.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:s,attemptNumber:e,retriesLeft:a,retriesConsumed:r});if(await i.onFailedAttempt(c),_c(n,o)<=0)throw s;let l=await i.shouldConsumeRetry(c),u=_c(n,o);if(u<=0||a<=0)throw s;if(s instanceof TypeError&&!Oi(s)){if(l)throw s;return i.signal?.throwIfAborted(),!1}if(!await i.shouldRetry(c))throw s;if(!l)return i.signal?.throwIfAborted(),!1;let d=_f(r,i),f=Math.min(d,u);return f>0&&await new Promise((p,h)=>{let m=()=>{clearTimeout(w),i.signal?.removeEventListener("abort",m),h(i.signal.reason)},w=setTimeout(()=>{i.signal?.removeEventListener("abort",m),p()},f);i.unref&&w.unref?.(),i.signal?.addEventListener("abort",m,{once:!0})}),i.signal?.throwIfAborted(),!0}async function Ni(t,e={}){if(e={...e},mf(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??(e.retries=10),e.factor??(e.factor=2),e.minTimeout??(e.minTimeout=1e3),e.maxTimeout??(e.maxTimeout=Number.POSITIVE_INFINITY),e.maxRetryTime??(e.maxRetryTime=Number.POSITIVE_INFINITY),e.randomize??(e.randomize=!1),e.onFailedAttempt??(e.onFailedAttempt=()=>{}),e.shouldRetry??(e.shouldRetry=()=>!0),e.shouldConsumeRetry??(e.shouldConsumeRetry=()=>!0),en("factor",e.factor,{min:0,allowInfinity:!1}),en("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),en("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),en("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let r=0,n=0,i=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){r++;try{e.signal?.throwIfAborted();let s=await t(r);return e.signal?.throwIfAborted(),s}catch(s){await gf({error:s,attemptNumber:r,retriesConsumed:n,startTime:i,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var an=Js(Hi(),1),Ic="default"in an.default?an.default.default:an.default;var If=[408,425,429,500,502,503,504],gr=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,"maxQueueSizeBytes",{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}),Object.defineProperty(this,"queueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.maxQueueSizeBytes=e.maxQueueSizeBytes,this.queue=new Ic({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...r){return this.callWithOptions({},e,...r)}callWithOptions(e,r,...n){let i=e.sizeBytes??0;if(this.maxQueueSizeBytes!==void 0&&i>0&&this.queueSizeBytes+i>this.maxQueueSizeBytes)return Promise.reject(new Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${i} bytes.`));i>0&&(this.queueSizeBytes+=i);let s=this.onFailedResponseHook,a=this.queue.add(()=>Ni(()=>r(...n).catch(o=>{throw o instanceof Error?o:new Error(o)}),{async onFailedAttempt({error:o}){if(typeof o!="object"||o==null)throw o;let c="message"in o&&typeof o.message=="string"?o.message:void 0;if(c?.startsWith("Cancel")||c?.startsWith("TimeoutError")||c?.startsWith("AbortError")||"name"in o&&o.name==="TimeoutError"||"code"in o&&o.code==="ECONNABORTED")throw o;let l="response"in o?o.response:void 0;if(s&&await s(l))return;let u=l?.status??("status"in o?o.status:void 0);if(u!=null&&(typeof u=="number"||typeof u=="string")&&!If.includes(+u))throw o},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return i>0&&(a=a.finally(()=>{this.queueSizeBytes-=i})),e.signal?Promise.race([a,new Promise((o,c)=>{e.signal?.addEventListener("abort",()=>{c(new Error("AbortError"))})})]):a}};function Bi(t){return typeof t?._getType=="function"}function Fi(t){let e={type:t._getType(),data:{content:t.content}};return t?.additional_kwargs&&Object.keys(t.additional_kwargs).length>0&&(e.data.additional_kwargs={...t.additional_kwargs}),e}function te(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r}function U(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}var Gi=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return Gi=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};function yr(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var br=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};var W=class extends Error{},J=class t extends W{constructor(e,r,n,i){super(`${t.makeMessage(e,r,n)}`),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.status=e,this.headers=i,this.error=r}static makeMessage(e,r,n){let i=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&i?`${e} ${i}`:e?`${e} status code (no body)`:i||"(no status code or body)"}static generate(e,r,n,i){if(!e||!i)return new Me({message:n,cause:br(r)});let s=r;return e===400?new ot(e,s,n,i):e===401?new ct(e,s,n,i):e===403?new lt(e,s,n,i):e===404?new ut(e,s,n,i):e===409?new dt(e,s,n,i):e===422?new ft(e,s,n,i):e===429?new pt(e,s,n,i):e>=500?new ht(e,s,n,i):new t(e,s,n,i)}},Ve=class extends J{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Me=class extends J{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},at=class extends Me{constructor({message:e}={}){super({message:e??"Request timed out."})}},ot=class extends J{},ct=class extends J{},lt=class extends J{},ut=class extends J{},dt=class extends J{},ft=class extends J{},pt=class extends J{},ht=class extends J{};var Pf=/^[a-z][a-z0-9+.-]*:/i,Tc=t=>Pf.test(t),ne=t=>(ne=Array.isArray,ne(t)),zi=ne;function Dt(t){return typeof t!="object"?{}:t??{}}function qi(t){if(!t)return!0;for(let e in t)return!1;return!0}function Pc(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var Rc=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new W(`${t} must be an integer`);if(e<0)throw new W(`${t} must be a positive integer`);return e};var on=t=>{try{return JSON.parse(t)}catch{return}};var Cc=t=>new Promise(e=>setTimeout(e,t));var de="0.12.0";function Rf(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var Cf=()=>{let t=Rf();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":de,"X-Stainless-OS":kc(Deno.build.os),"X-Stainless-Arch":Oc(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":de,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":de,"X-Stainless-OS":kc(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Oc(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Of();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":de,"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":de,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Of(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let i=n[1]||0,s=n[2]||0,a=n[3]||0;return{browser:e,version:`${i}.${s}.${a}`}}}return null}var Oc=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",kc=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),Nc,Lc=()=>Nc??(Nc=Cf());function Mc(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Langsmith({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Ki(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function Vi(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Ki({start(){},async pull(r){let{done:n,value:i}=await e.next();n?r.close():r.enqueue(i)},async cancel(){await e.return?.()}})}function Wi(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let r=await e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){let r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function $c(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),r=e.cancel();e.releaseLock(),await r}var jc=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Ji="RFC3986",Xi=t=>String(t),Qi={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:Xi},Uc="RFC1738";var cn=(t,e)=>(cn=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),cn(t,e)),Te=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var Yi=1024,Dc=(t,e,r,n,i)=>{if(t.length===0)return t;let s=t;if(typeof t=="symbol"?s=Symbol.prototype.toString.call(t):typeof t!="string"&&(s=String(t)),r==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(o){return"%26%23"+parseInt(o.slice(2),16)+"%3B"});let a="";for(let o=0;o<s.length;o+=Yi){let c=s.length>=Yi?s.slice(o,o+Yi):s,l=[];for(let u=0;u<c.length;++u){let d=c.charCodeAt(u);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||i===Uc&&(d===40||d===41)){l[l.length]=c.charAt(u);continue}if(d<128){l[l.length]=Te[d];continue}if(d<2048){l[l.length]=Te[192|d>>6]+Te[128|d&63];continue}if(d<55296||d>=57344){l[l.length]=Te[224|d>>12]+Te[128|d>>6&63]+Te[128|d&63];continue}u+=1,d=65536+((d&1023)<<10|c.charCodeAt(u)&1023),l[l.length]=Te[240|d>>18]+Te[128|d>>12&63]+Te[128|d>>6&63]+Te[128|d&63]}a+=l.join("")}return a};function Hc(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function Zi(t,e){if(ne(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}var Fc={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},Gc=function(t,e){Array.prototype.push.apply(t,ne(e)?e:[e])},Bc,X={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Dc,encodeValuesOnly:!1,format:Ji,formatter:Xi,indices:!1,serializeDate(t){return(Bc??(Bc=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function Lf(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var es={};function zc(t,e,r,n,i,s,a,o,c,l,u,d,f,p,h,m,w,E){let b=t,R=E,v=0,M=!1;for(;(R=R.get(es))!==void 0&&!M;){let j=R.get(t);if(v+=1,typeof j<"u"){if(j===v)throw new RangeError("Cyclic object value");M=!0}typeof R.get(es)>"u"&&(v=0)}if(typeof l=="function"?b=l(e,b):b instanceof Date?b=f?.(b):r==="comma"&&ne(b)&&(b=Zi(b,function(j){return j instanceof Date?f?.(j):j})),b===null){if(s)return c&&!m?c(e,X.encoder,w,"key",p):e;b=""}if(Lf(b)||Hc(b)){if(c){let j=m?e:c(e,X.encoder,w,"key",p);return[h?.(j)+"="+h?.(c(b,X.encoder,w,"value",p))]}return[h?.(e)+"="+h?.(String(b))]}let k=[];if(typeof b>"u")return k;let N;if(r==="comma"&&ne(b))m&&c&&(b=Zi(b,c)),N=[{value:b.length>0?b.join(",")||null:void 0}];else if(ne(l))N=l;else{let j=Object.keys(b);N=u?j.sort(u):j}let L=o?String(e).replace(/\./g,"%2E"):String(e),G=n&&ne(b)&&b.length===1?L+"[]":L;if(i&&ne(b)&&b.length===0)return G+"[]";for(let j=0;j<N.length;++j){let le=N[j],dr=typeof le=="object"&&typeof le.value<"u"?le.value:b[le];if(a&&dr===null)continue;let fr=d&&o?le.replace(/\./g,"%2E"):le,Vn=ne(b)?typeof r=="function"?r(G,fr):G:G+(d?"."+fr:"["+fr+"]");E.set(t,v);let Ws=new WeakMap;Ws.set(es,E),Gc(k,zc(dr,Vn,r,n,i,s,a,o,r==="comma"&&m&&ne(b)?null:c,l,u,d,f,p,h,m,w,Ws))}return k}function Mf(t=X){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=t.charset||X.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=Ji;if(typeof t.format<"u"){if(!cn(Qi,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=Qi[r],i=X.filter;(typeof t.filter=="function"||ne(t.filter))&&(i=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in Fc?s=t.arrayFormat:"indices"in t?s=t.indices?"indices":"repeat":s=X.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:X.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:X.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:X.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:X.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?X.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:X.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:X.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:X.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:X.encodeValuesOnly,filter:i,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:X.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:X.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:X.strictNullHandling}}function qc(t,e={}){let r=t,n=Mf(e),i,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):ne(n.filter)&&(s=n.filter,i=s);let a=[];if(typeof r!="object"||r===null)return"";let o=Fc[n.arrayFormat],c=o==="comma"&&n.commaRoundTrip;i||(i=Object.keys(r)),n.sort&&i.sort(n.sort);let l=new WeakMap;for(let f=0;f<i.length;++f){let p=i[f];n.skipNulls&&r[p]===null||Gc(a,zc(r[p],p,o,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,l))}let u=a.join(n.delimiter),d=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),u.length>0?d+u:""}function Kc(t){return qc(t,{arrayFormat:"repeat"})}function Jc(t){let e=0;for(let i of t)e+=i.length;let r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}var Vc;function wr(t){let e;return(Vc??(e=new globalThis.TextEncoder,Vc=e.encode.bind(e)))(t)}var Wc;function ts(t){let e;return(Wc??(e=new globalThis.TextDecoder,Wc=e.decode.bind(e)))(t)}var ge,ye,mt=class{constructor(){ge.set(this,void 0),ye.set(this,void 0),te(this,ge,new Uint8Array,"f"),te(this,ye,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?wr(e):e;te(this,ge,Jc([U(this,ge,"f"),r]),"f");let n=[],i;for(;(i=jf(U(this,ge,"f"),U(this,ye,"f")))!=null;){if(i.carriage&&U(this,ye,"f")==null){te(this,ye,i.index,"f");continue}if(U(this,ye,"f")!=null&&(i.index!==U(this,ye,"f")+1||i.carriage)){n.push(ts(U(this,ge,"f").subarray(0,U(this,ye,"f")-1))),te(this,ge,U(this,ge,"f").subarray(U(this,ye,"f")),"f"),te(this,ye,null,"f");continue}let s=U(this,ye,"f")!==null?i.preceding-1:i.preceding,a=ts(U(this,ge,"f").subarray(0,s));n.push(a),te(this,ge,U(this,ge,"f").subarray(i.index),"f"),te(this,ye,null,"f")}return n}flush(){return U(this,ge,"f").length?this.decode(`
|
|
19
|
+
`):[]}};ge=new WeakMap,ye=new WeakMap;Object.defineProperty(mt,"NEWLINE_CHARS",{enumerable:!0,configurable:!0,writable:!0,value:new Set([`
|
|
20
|
+
`,"\r"])});Object.defineProperty(mt,"NEWLINE_REGEXP",{enumerable:!0,configurable:!0,writable:!0,value:/\r\n|[\n\r]/g});function jf(t,e){for(let i=e??0;i<t.length;i++){if(t[i]===10)return{preceding:i,index:i+1,carriage:!1};if(t[i]===13)return{preceding:i,index:i+1,carriage:!0}}return null}function Xc(t){for(let n=0;n<t.length-1;n++){if(t[n]===10&&t[n+1]===10||t[n]===13&&t[n+1]===13)return n+2;if(t[n]===13&&t[n+1]===10&&n+3<t.length&&t[n+2]===13&&t[n+3]===10)return n+4}return-1}var un={off:0,error:200,warn:300,info:400,debug:500},rs=(t,e,r)=>{if(t){if(Pc(un,t))return t;Y(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(un))}`)}};function xr(){}function ln(t,e,r){return!e||un[t]>un[r]?xr:e[t].bind(e)}var Uf={error:xr,warn:xr,info:xr,debug:xr},Qc=new WeakMap;function Y(t){let e=t.logger,r=t.logLevel??"off";if(!e)return Uf;let n=Qc.get(e);if(n&&n[0]===r)return n[1];let i={error:ln("error",e,r),warn:ln("warn",e,r),info:ln("info",e,r),debug:ln("debug",e,r)};return Qc.set(e,[r,i]),i}var $e=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"||e.toLowerCase()==="x-tenant-id"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var vr,dn=class t{constructor(e,r,n){Object.defineProperty(this,"iterator",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),vr.set(this,void 0),this.controller=r,te(this,vr,n,"f")}static fromSSEResponse(e,r,n){let i=!1,s=n?Y(n):console;async function*a(){if(i)throw new W("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let o=!1;try{for await(let c of Df(e,r)){if(c.event==="end")break;if(c.event==="error")throw new J(void 0,on(c.data)??c.data,void 0,e.headers);if(c.event==="data")try{yield JSON.parse(c.data)}catch(l){throw s.error("Could not parse message into JSON:",c.data),s.error("From chunk:",c.raw),l}else try{yield JSON.parse(c.data)}catch(l){throw s.error("Could not parse message into JSON:",c.data),s.error("From chunk:",c.raw),l}}o=!0}catch(c){if(yr(c))return;throw c}finally{o||r.abort()}}return new t(a,r,n)}static fromReadableStream(e,r,n){let i=!1;async function*s(){let o=new mt,c=Wi(e);for await(let l of c)for(let u of o.decode(l))yield u;for(let l of o.flush())yield l}async function*a(){if(i)throw new W("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let o=!1;try{for await(let c of s())o||c&&(yield JSON.parse(c));o=!0}catch(c){if(yr(c))return;throw c}finally{o||r.abort()}}return new t(a,r,n)}[(vr=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),i=s=>({next:()=>{if(s.length===0){let a=n.next();e.push(a),r.push(a)}return s.shift()}});return[new t(()=>i(e),this.controller,U(this,vr,"f")),new t(()=>i(r),this.controller,U(this,vr,"f"))]}toReadableStream(){let e=this,r;return Ki({async start(){r=e[Symbol.asyncIterator]()},async pull(n){try{let{value:i,done:s}=await r.next();if(s)return n.close();let a=wr(JSON.stringify(i)+`
|
|
21
|
+
`);n.enqueue(a)}catch(i){n.error(i)}},async cancel(){await r.return?.()}})}};async function*Df(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new W("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 W("Attempted to iterate over a response with no body");let r=new ns,n=new mt,i=Wi(t.body);for await(let s of Hf(i))for(let a of n.decode(s)){let o=r.decode(a);o&&(yield o)}for(let s of n.flush()){let a=r.decode(s);a&&(yield a)}}async function*Hf(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?wr(r):r,i=new Uint8Array(e.length+n.length);i.set(e),i.set(n,e.length),e=i;let s;for(;(s=Xc(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}var ns=class{constructor(){Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"event",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chunks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let s={event:this.event,data:this.data.join(`
|
|
22
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,i]=Bf(e,":");return i.startsWith(" ")&&(i=i.substring(1)),r==="event"?this.event=i:r==="data"&&this.data.push(i),null}};function Bf(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function fn(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:i,startTime:s}=e,a=await(async()=>{if(e.options.stream)return Y(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller,t):dn.fromSSEResponse(r,e.controller,t);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let c=r.headers.get("content-type")?.split(";")[0]?.trim();return c?.includes("application/json")||c?.endsWith("+json")?r.headers.get("content-length")==="0"?void 0:await r.json():await r.text()})();return Y(t).debug(`[${n}] response parsed`,$e({retryOfRequestLogID:i,url:r.url,status:r.status,body:a,durationMs:Date.now()-s})),a}var Er,_t=class t extends Promise{constructor(e,r,n=fn){super(i=>{i(null)}),Object.defineProperty(this,"responsePromise",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"parseResponse",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"parsedPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Er.set(this,void 0),te(this,Er,e,"f")}_thenUnwrap(e){return new t(U(this,Er,"f"),this.responsePromise,async(r,n)=>e(await this.parseResponse(r,n),n))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(U(this,Er,"f"),e))),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};Er=new WeakMap;var pn,gt=class{constructor(e,r,n,i){pn.set(this,void 0),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),te(this,pn,e,"f"),this.options=i,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new W("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await U(this,pn,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(pn=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},Sr=class extends _t{constructor(e,r,n){super(e,r,async(i,s)=>new n(i,s.response,await fn(i,s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},hn=class extends gt{constructor(e,r,n,i){super(e,r,n,i),Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.items=n||[]}getPaginatedItems(){return this.items??[]}nextPageRequestOptions(){let e=this.options.query.offset??0,r=this.getPaginatedItems().length,n=e+r;return{...this.options,query:{...Dt(this.options.query),offset:n}}}},mn=class extends gt{constructor(e,r,n,i){super(e,r,n,i),Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.items=n||[]}getPaginatedItems(){return this.items??[]}nextPageRequestOptions(){let e=this.options.query.offset??0,r=this.getPaginatedItems().length,n=e+r;return{...this.options,query:{...Dt(this.options.query),offset:n}}}};var _n=class extends gt{constructor(e,r,n,i){super(e,r,n,i),Object.defineProperty(this,"evaluators",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"total",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.evaluators=n.evaluators||[],this.total=n.total||0}getPaginatedItems(){return this.evaluators??[]}nextPageRequestOptions(){let e=this.options.query.offset??0,r=this.getPaginatedItems().length,n=e+r;return{...this.options,query:{...Dt(this.options.query),offset:n}}}};var Pe=class extends gt{constructor(e,r,n,i){super(e,r,n,i),Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"next_cursor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.items=n.items||[],this.next_cursor=n.next_cursor||""}getPaginatedItems(){return this.items??[]}nextPageRequestOptions(){let e=this.next_cursor;return e?{...this.options,body:{...Dt(this.options.body),cursor:e}}:null}},Q=class extends gt{constructor(e,r,n,i){super(e,r,n,i),Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"next_cursor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.items=n.items||[],this.next_cursor=n.next_cursor||""}getPaginatedItems(){return this.items??[]}nextPageRequestOptions(){let e=this.next_cursor;return e?{...this.options,query:{...Dt(this.options.query),cursor:e}}:null}};var is=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function gn(t,e,r){return is(),new File(t,e??"unknown_file",r)}function Yc(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}var Zc=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function";var el=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",Gf=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&el(t),zf=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function yn(t,e,r){if(is(),t=await t,Gf(t))return t instanceof File?t:gn([await t.arrayBuffer()],t.name);if(zf(t)){let i=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),gn(await ss(i),e,r)}let n=await ss(t);if(e||(e=Yc(t)),!r?.type){let i=n.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof i=="string"&&(r={...r,type:i})}return gn(n,e,r)}async function ss(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(el(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(Zc(t))for await(let r of t)e.push(...await ss(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${qf(t)}`)}return e}function qf(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var I=class{constructor(e){Object.defineProperty(this,"_client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._client=e}};var tl=Symbol("brand.privateNullableHeaders");function*Vf(t){if(!t)return;if(tl in t){let{values:n,nulls:i}=t;yield*n.entries();for(let s of i)yield[s,null];return}let e=!1,r;t instanceof Headers?r=t.entries():zi(t)?r=t:(e=!0,r=Object.entries(t??{}));for(let n of r){let i=n[0];if(typeof i!="string")throw new TypeError("expected header name to be a string");let s=zi(n[1])?n[1]:[n[1]],a=!1;for(let o of s)o!==void 0&&(e&&!a&&(a=!0,yield[i,null]),yield[i,o])}}var P=t=>{let e=new Headers,r=new Set;for(let n of t){let i=new Set;for(let[s,a]of Vf(n)){let o=s.toLowerCase();i.has(o)||(e.delete(s),i.add(o)),a===null?(e.delete(s),r.add(o)):(e.append(s,a),r.delete(o))}}return{[tl]:!0,values:e,nulls:r}};function nl(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var rl=Object.freeze(Object.create(null)),Wf=(t=nl)=>function(r,...n){if(r.length===1)return r[0];let i=!1,s=[],a=r.reduce((u,d,f)=>{/[?#]/.test(d)&&(i=!0);let p=n[f],h=(i?encodeURIComponent:t)(""+p);return f!==n.length&&(p==null||typeof p=="object"&&p.toString===Object.getPrototypeOf(Object.getPrototypeOf(p.hasOwnProperty??rl)??rl)?.toString)&&(h=p+"",s.push({start:u.length+d.length,length:h.length,error:`Value of type ${Object.prototype.toString.call(p).slice(8,-1)} is not a valid path parameter`})),u+d+(f===n.length?"":h)},""),o=a.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=c.exec(o))!==null;)s.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(s.sort((u,d)=>u.start-d.start),s.length>0){let u=0,d=s.reduce((f,p)=>{let h=" ".repeat(p.start-u),m="^".repeat(p.length);return u=p.start+p.length,f+h+m},"");throw new W(`Path parameters result in path with invalid segments:
|
|
23
|
+
${s.map(f=>f.error).join(`
|
|
24
|
+
`)}
|
|
25
|
+
${a}
|
|
26
|
+
${d}`)}return a},y=Wf(nl);var yt=class extends I{create(e,r){return this._client.post("/api/v1/agents",{body:{...e,source_type:e.source_type===void 0?"EXTERNAL":e.source_type},...r})}retrieve(e,r={},n){return this._client.get(y`/api/v1/agents/${e}`,{query:r,...n})}update(e,r,n){return this._client.patch(y`/api/v1/agents/${e}`,{body:r,...n})}list(e={},r){return this._client.getAPIList("/api/v1/agents",Q,{query:e,...r})}delete(e,r){return this._client.delete(y`/api/v1/agents/${e}`,{...r,headers:P([{Accept:"*/*"},r?.headers])})}};var Ht=class extends I{create(e,r,n){let{extend_trace_retention:i,...s}=r;return this._client.post(y`/api/v1/platform/annotation-queues/${e}/items`,{query:{extend_trace_retention:i},body:s,...n})}update(e,r,n){let{queue_id:i,...s}=r;return this._client.patch(y`/api/v1/platform/annotation-queues/${i}/items/${e}`,{body:s,...n})}list(e,r,n){return this._client.getAPIList(y`/api/v1/platform/annotation-queues/${e}/items`,Q,{query:r,...n})}createStatus(e,r,n){return this._client.post(y`/api/v1/platform/annotation-queues/items/${e}/status`,{body:r,...n})}deleteAll(e,r,n){return this._client.post(y`/api/v1/platform/annotation-queues/${e}/items/delete`,{body:r,...n})}retrieveCount(e,r,n){return this._client.get(y`/api/v1/platform/annotation-queues/${e}/items/count`,{query:r,...n})}retrievePlacement(e,r,n){let{queue_id:i}=r;return this._client.get(y`/api/v1/platform/annotation-queues/${i}/items/${e}/placement`,n)}};var Bt=class extends I{create(e,r,n){let{body:i,extend_trace_retention:s}=r;return this._client.post(y`/api/v1/annotation-queues/${e}/runs`,{query:{extend_trace_retention:s},body:i,...n})}update(e,r,n){let{queue_id:i,...s}=r;return this._client.patch(y`/api/v1/annotation-queues/${i}/runs/${e}`,{body:s,...n})}list(e,r={},n){return this._client.get(y`/api/v1/annotation-queues/${e}/runs`,{query:r,...n})}createByKey(e,r,n){let{body:i,extend_trace_retention:s}=r;return this._client.post(y`/api/v1/annotation-queues/${e}/runs/by-key`,{query:{extend_trace_retention:s},body:i,...n})}deleteAll(e,r,n){return this._client.post(y`/api/v1/annotation-queues/${e}/runs/delete`,{body:r,...n})}deleteQueue(e,r,n){let{queue_id:i}=r;return this._client.delete(y`/api/v1/annotation-queues/${i}/runs/${e}`,n)}};var je=class extends I{constructor(){super(...arguments),Object.defineProperty(this,"runs",{enumerable:!0,configurable:!0,writable:!0,value:new Bt(this._client)}),Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:new Ht(this._client)})}retrieve(e,r){return this._client.get(y`/api/v1/annotation-queues/${e}`,r)}update(e,r,n){return this._client.patch(y`/api/v1/annotation-queues/${e}`,{body:r,...n})}delete(e,r){return this._client.delete(y`/api/v1/annotation-queues/${e}`,r)}annotationQueues(e,r){return this._client.post("/api/v1/annotation-queues",{body:e,...r})}createRunStatus(e,r,n){return this._client.post(y`/api/v1/annotation-queues/status/${e}`,{body:r,...n})}export(e,r,n){return this._client.post(y`/api/v1/annotation-queues/${e}/export`,{body:r,...n})}populate(e,r){return this._client.post("/api/v1/annotation-queues/populate",{body:e,...r})}retrieveAnnotationQueues(e={},r){return this._client.getAPIList("/api/v1/annotation-queues",hn,{query:e,...r})}retrieveQueues(e,r){return this._client.get(y`/api/v1/annotation-queues/${e}/queues`,r)}retrieveRun(e,r,n){let{queue_id:i,...s}=r;return this._client.get(y`/api/v1/annotation-queues/${i}/run/${e}`,{query:s,...n})}retrieveSize(e,r={},n){return this._client.get(y`/api/v1/annotation-queues/${e}/size`,{query:r,...n})}retrieveTotalArchived(e,r={},n){return this._client.get(y`/api/v1/annotation-queues/${e}/total_archived`,{query:r,...n})}retrieveTotalSize(e,r){return this._client.get(y`/api/v1/annotation-queues/${e}/total_size`,r)}};je.Runs=Bt;je.Items=Ht;var Ft=class extends I{delete(e,r,n){let{dataset_id:i}=r;return this._client.delete(y`/api/v1/platform/datasets/${i}/examples/${e}`,{...n,headers:P([{Accept:"*/*"},n?.headers])})}updateMetadata(e,r,n){return this._client.patch(y`/api/v1/platform/datasets/${e}/examples/metadata`,{body:r,...n})}};var Gt=class extends I{query(e,r,n){return this._client.getAPIList(y`/api/v2/datasets/${e}/experiment-runs`,Pe,{body:r,method:"post",...n})}};var Ue=class extends I{constructor(){super(...arguments),Object.defineProperty(this,"examples",{enumerable:!0,configurable:!0,writable:!0,value:new Ft(this._client)}),Object.defineProperty(this,"experimentRuns",{enumerable:!0,configurable:!0,writable:!0,value:new Gt(this._client)})}listV2(e={},r){return this._client.getAPIList("/api/v2/datasets",Q,{query:e,...r})}};Ue.Examples=Ft;Ue.ExperimentRuns=Gt;var bt=class extends I{list(e={},r){return this._client.get("/api/v1/runs/rules",{query:e,...r})}createDecisionModel(e,r){return this._client.post("/api/v1/runs/rules/decision-models",{body:e,...r})}};var zt=class extends I{activateSandbox(e,r){return this._client.post(y`/v1/fleet/threads/${e}/sandbox-activation`,r)}};var We=class extends I{constructor(){super(...arguments),Object.defineProperty(this,"threads",{enumerable:!0,configurable:!0,writable:!0,value:new zt(this._client)})}};We.Threads=zt;var wt=class extends I{list(e){return this._client.get("/api/v1/info",e)}};var xt=class extends I{retrieve(e,r={},n){return this._client.get(y`/api/v1/platform/issues/${e}`,{query:r,...n})}list(e={},r){return this._client.getAPIList("/api/v1/platform/issues",mn,{query:e,...r})}};var vt=class extends I{create(e,r){return this._client.post("/api/v1/platform/evaluators",{body:e,...r})}retrieve(e,r){return this._client.get(y`/api/v1/platform/evaluators/${e}`,r)}update(e,r,n){return this._client.patch(y`/api/v1/platform/evaluators/${e}`,{body:r,...n})}list(e={},r){return this._client.getAPIList("/api/v1/platform/evaluators",_n,{query:e,...r})}delete(e,r={},n){let{delete_run_rules:i}=r??{};return this._client.delete(y`/api/v1/platform/evaluators/${e}`,{query:{delete_run_rules:i},...n,headers:P([{Accept:"*/*"},n?.headers])})}bulkDelete(e,r){let{evaluator_ids:n,delete_run_rules:i}=e;return this._client.delete("/api/v1/platform/evaluators",{query:{evaluator_ids:n,delete_run_rules:i},...r})}spend(e,r){return this._client.get("/api/v1/platform/evaluators/spend",{query:e,...r})}};var Et=class extends I{create(e,r){let{"Idempotency-Key":n,...i}=e;return this._client.post("/api/v1/platform/product-feedbacks",{body:i,...r,headers:P([{...n!=null?{"Idempotency-Key":n}:void 0},r?.headers])})}retrieve(e,r){return this._client.get(y`/api/v1/platform/product-feedbacks/${e}`,r)}};var St=class extends I{create(e,r){return this._client.post("/api/v1/prompt-webhooks",{body:e,...r})}retrieve(e,r){return this._client.get(y`/api/v1/prompt-webhooks/${e}`,r)}update(e,r,n){return this._client.patch(y`/api/v1/prompt-webhooks/${e}`,{body:r,...n})}list(e){return this._client.get("/api/v1/prompt-webhooks",e)}delete(e,r){return this._client.delete(y`/api/v1/prompt-webhooks/${e}`,{...r,headers:P([{Accept:"*/*"},r?.headers])})}test(e,r){return this._client.post("/api/v1/prompt-webhooks/test",{body:e,...r})}};var qt=class extends I{retrieve(e,r,n){let{share_token:i,Accept:s,...a}=r;return this._client.get(y`/api/v2/public/${i}/run/${e}`,{query:a,...n,headers:P([{...s!=null?{Accept:s}:void 0},n?.headers])})}query(e,r,n){let{Accept:i,...s}=r;return this._client.post(y`/api/v2/public/${e}/runs/query`,{body:s,...n,headers:P([{...i!=null?{Accept:i}:void 0},n?.headers])})}};var Je=class extends I{constructor(){super(...arguments),Object.defineProperty(this,"runs",{enumerable:!0,configurable:!0,writable:!0,value:new qt(this._client)})}};Je.Runs=qt;var Kt=class extends I{create(e,r,n){return this._client.post(y`/api/v2/runs/${e}/share`,{body:r,...n})}delete(e,r,n){return this._client.delete(y`/api/v2/runs/${e}/share`,{body:r,...n,headers:P([{Accept:"*/*"},n?.headers])})}};async function*Vt(t,e){let r=new RegExp(`^${rp(e.items)}/(-|\\d+)$`),n;do{let i=null,s=[],a=0,o=!1;for await(let c of await t(n))for(let l of c){if(l.path===""){let u=l.value;i=il(u,e.nextCursor)??null;let d=il(u,e.items)??[];s.splice(a,s.length-a,...d.slice(a))}else if(l.path===e.nextCursor)i=l.value??null;else{let u=r.exec(l.path);if(!u)continue;let d=u[1]==="-"?s.length:Number(u[1]);u[1]!=="-"&&(o=!0),l.op==="remove"?d>=a&&d<s.length&&s.splice(d,1):l.op==="replace"?d>=a&&d<s.length&&(s[d]=l.value):s.splice(Math.min(d,s.length),0,l.value)}for(;!o&&a<s.length;)yield s[a++]}for(;a<s.length;)yield s[a++];n=i||void 0}while(n)}function il(t,e){let r=t;for(let n of e.split("/").slice(1)){if(r==null||typeof r!="object")return;r=r[n.replace(/~1/g,"/").replace(/~0/g,"~")]}return r}function rp(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Wt=class extends I{queryV2(e,r){let{Accept:n,...i}=e;return this._client.post("/api/v2/runs/query",{body:i,...r,headers:P([{Accept:n??"text/event-stream"},r?.headers]),stream:!0})}queryV2Items(e,r){return Vt(n=>this.queryV2(n?{...e,cursor:n}:e,r),{items:"/items",nextCursor:"/next_cursor"})}};var De=class extends I{constructor(){super(...arguments),Object.defineProperty(this,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:new Wt(this._client)}),Object.defineProperty(this,"share",{enumerable:!0,configurable:!0,writable:!0,value:new Kt(this._client)}),Object.defineProperty(this,"retrieve",{enumerable:!0,configurable:!0,writable:!0,value:this.retrieveV2}),Object.defineProperty(this,"query",{enumerable:!0,configurable:!0,writable:!0,value:this.queryV2})}getURL(e,r,n){return this._client.get(y`/api/v2/runs/${e}/url`,{query:r,...n})}queryV2(e,r){let{Accept:n,...i}=e;return this._client.getAPIList("/api/v2/runs/query",Pe,{body:i,method:"post",...r,headers:P([{...n!=null?{Accept:n}:void 0},r?.headers])})}retrieveV2(e,r,n){let{Accept:i,...s}=r;return this._client.get(y`/api/v2/runs/${e}`,{query:s,...n,headers:P([{...i!=null?{Accept:i}:void 0},n?.headers])})}};De.Streaming=Wt;De.Share=Kt;var Jt=class extends I{create(e,r){return this._client.post("/api/v2/sandboxes/boxes",{body:e,...r})}retrieve(e,r){return this._client.get(y`/api/v2/sandboxes/boxes/${e}`,r)}update(e,r,n){return this._client.patch(y`/api/v2/sandboxes/boxes/${e}`,{body:r,...n})}list(e={},r){return this._client.getAPIList("/api/v2/sandboxes/boxes",Q,{query:e,...r})}delete(e,r){return this._client.delete(y`/api/v2/sandboxes/boxes/${e}`,{...r,headers:P([{Accept:"*/*"},r?.headers])})}createSnapshot(e,r,n){return this._client.post(y`/api/v2/sandboxes/boxes/${e}/snapshot`,{body:r,...n})}deleteServiceURL(e,r={},n){let{port:i}=r??{};return this._client.delete(y`/api/v2/sandboxes/boxes/${e}/service-urls`,{query:{port:i},...n,headers:P([{Accept:"*/*"},n?.headers])})}generateDownloadURL(e,r,n){return this._client.post(y`/api/v2/sandboxes/boxes/${e}/download-url`,{body:r,...n})}generateServiceURL(e,r,n){return this._client.post(y`/api/v2/sandboxes/boxes/${e}/service-url`,{body:r,...n})}getStatus(e,r){return this._client.get(y`/api/v2/sandboxes/boxes/${e}/status`,r)}listServiceURLs(e,r={},n){return this._client.getAPIList(y`/api/v2/sandboxes/boxes/${e}/service-urls`,Q,{query:r,...n})}start(e,r){return this._client.post(y`/api/v2/sandboxes/boxes/${e}/start`,r)}stop(e,r){return this._client.post(y`/api/v2/sandboxes/boxes/${e}/stop`,{...r,headers:P([{Accept:"*/*"},r?.headers])})}};var Xt=class extends I{create(e,r){return this._client.post("/api/v2/sandboxes/registries",{body:e,...r})}retrieve(e,r){return this._client.get(y`/api/v2/sandboxes/registries/${e}`,r)}update(e,r,n){return this._client.patch(y`/api/v2/sandboxes/registries/${e}`,{body:r,...n})}list(e={},r){return this._client.get("/api/v2/sandboxes/registries",{query:e,...r})}delete(e,r){return this._client.delete(y`/api/v2/sandboxes/registries/${e}`,{...r,headers:P([{Accept:"*/*"},r?.headers])})}};var Qt=class extends I{create(e,r){return this._client.post("/api/v2/sandboxes/snapshots",{body:e,...r})}retrieve(e,r){return this._client.get(y`/api/v2/sandboxes/snapshots/${e}`,r)}list(e={},r){return this._client.getAPIList("/api/v2/sandboxes/snapshots",Q,{query:e,...r})}delete(e,r){return this._client.delete(y`/api/v2/sandboxes/snapshots/${e}`,{...r,headers:P([{Accept:"*/*"},r?.headers])})}retrieveByName(e,r){return this._client.get(y`/api/v2/sandboxes/snapshots-by-name/${e}`,r)}};var Re=class extends I{constructor(){super(...arguments),Object.defineProperty(this,"boxes",{enumerable:!0,configurable:!0,writable:!0,value:new Jt(this._client)}),Object.defineProperty(this,"registries",{enumerable:!0,configurable:!0,writable:!0,value:new Xt(this._client)}),Object.defineProperty(this,"snapshots",{enumerable:!0,configurable:!0,writable:!0,value:new Qt(this._client)})}listUsageCosts(e,r){return this._client.getAPIList("/api/v2/sandboxes/usage/costs",Q,{query:e,...r})}};Re.Boxes=Jt;Re.Registries=Xt;Re.Snapshots=Qt;var At=class extends I{create(e,r){let{upsert:n,...i}=e;return this._client.post("/api/v1/sessions",{query:{upsert:n},body:i,...r})}retrieve(e,r={},n){let{accept:i,...s}=r??{};return this._client.get(y`/api/v1/sessions/${e}`,{query:s,...n,headers:P([{...i!=null?{accept:i}:void 0},n?.headers])})}update(e,r,n){return this._client.patch(y`/api/v1/sessions/${e}`,{body:r,...n})}delete(e,r){return this._client.delete(y`/api/v1/sessions/${e}`,{...r,headers:P([{Accept:"*/*"},r?.headers])})}dashboard(e,r,n){let{accept:i,...s}=r;return this._client.post(y`/api/v1/sessions/${e}/dashboard`,{body:s,...n,headers:P([{...i!=null?{accept:i}:void 0},n?.headers])})}listV2(e={},r){return this._client.getAPIList("/api/v2/sessions",Q,{query:e,...r})}resolve(e,r){return this._client.get("/api/v1/sessions/resolutions",{query:e,...r})}};var It=class extends I{query(e,r){return this._client.post("/v2/sql/query",{body:e,...r})}};var Yt=class extends I{create(e,r,n){return this._client.post(y`/api/v2/threads/${e}/share`,{body:r,...n})}retrieve(e,r,n){return this._client.get(y`/api/v2/threads/${e}/share`,{query:r,...n})}delete(e,r,n){let{project_id:i}=r;return this._client.delete(y`/api/v2/threads/${e}/share`,{query:{project_id:i},...n,headers:P([{Accept:"*/*"},n?.headers])})}};var Zt=class extends I{query(e,r){let{Accept:n,...i}=e;return this._client.post("/api/v2/threads/query",{body:i,...r,headers:P([{Accept:n??"text/event-stream"},r?.headers]),stream:!0})}queryItems(e,r){return Vt(n=>this.query(n?{...e,cursor:n}:e,r),{items:"/items",nextCursor:"/next_cursor"})}};var He=class extends I{constructor(){super(...arguments),Object.defineProperty(this,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:new Zt(this._client)}),Object.defineProperty(this,"share",{enumerable:!0,configurable:!0,writable:!0,value:new Yt(this._client)})}aggregateStats(e,r){return this._client.post("/api/v2/threads/stats",{body:e,...r})}listTraces(e,r,n){return this._client.getAPIList(y`/api/v2/threads/${e}/traces`,Q,{query:r,...n})}query(e,r){let{Accept:n,...i}=e;return this._client.getAPIList("/api/v2/threads/query",Pe,{body:i,method:"post",...r,headers:P([{...n!=null?{Accept:n}:void 0},r?.headers])})}stats(e,r,n){return this._client.get(y`/api/v2/threads/${e}/stats`,{query:r,...n})}};He.Streaming=Zt;He.Share=Yt;var er=class extends I{query(e,r){let{Accept:n,...i}=e;return this._client.post("/api/v2/traces/query",{body:i,...r,headers:P([{Accept:n??"text/event-stream"},r?.headers]),stream:!0})}queryItems(e,r){return Vt(n=>this.query(n?{...e,cursor:n}:e,r),{items:"/items",nextCursor:"/next_cursor"})}};var Xe=class extends I{constructor(){super(...arguments),Object.defineProperty(this,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:new er(this._client)})}listRuns(e,r,n){let{Accept:i,...s}=r;return this._client.get(y`/api/v2/traces/${e}/runs`,{query:s,...n,headers:P([{...i!=null?{Accept:i}:void 0},n?.headers])})}query(e,r){let{Accept:n,...i}=e;return this._client.getAPIList("/api/v2/traces/query",Pe,{body:i,method:"post",...r,headers:P([{...n!=null?{Accept:n}:void 0},r?.headers])})}};Xe.Streaming=er;var tr=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()||void 0};var as,os,bn,sl,O=class{constructor({baseURL:e=tr("LANGCHAIN_BASE_URL"),apiKey:r=tr("LANGSMITH_API_KEY")??null,tenantID:n=tr("LANGSMITH_TENANT_ID")??null,...i}={}){as.add(this),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tenantID",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"baseURL",{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,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logLevel",{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,"fetch",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),bn.set(this,void 0),Object.defineProperty(this,"idempotencyHeader",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sql",{enumerable:!0,configurable:!0,writable:!0,value:new It(this)}),Object.defineProperty(this,"productFeedback",{enumerable:!0,configurable:!0,writable:!0,value:new Et(this)}),Object.defineProperty(this,"agents",{enumerable:!0,configurable:!0,writable:!0,value:new yt(this)}),Object.defineProperty(this,"fleet",{enumerable:!0,configurable:!0,writable:!0,value:new We(this)}),Object.defineProperty(this,"sessions",{enumerable:!0,configurable:!0,writable:!0,value:new At(this)}),Object.defineProperty(this,"datasets",{enumerable:!0,configurable:!0,writable:!0,value:new Ue(this)}),Object.defineProperty(this,"runs",{enumerable:!0,configurable:!0,writable:!0,value:new De(this)}),Object.defineProperty(this,"threads",{enumerable:!0,configurable:!0,writable:!0,value:new He(this)}),Object.defineProperty(this,"traces",{enumerable:!0,configurable:!0,writable:!0,value:new Xe(this)}),Object.defineProperty(this,"evaluators",{enumerable:!0,configurable:!0,writable:!0,value:new bt(this)}),Object.defineProperty(this,"onlineEvaluators",{enumerable:!0,configurable:!0,writable:!0,value:new vt(this)}),Object.defineProperty(this,"public",{enumerable:!0,configurable:!0,writable:!0,value:new Je(this)}),Object.defineProperty(this,"annotationQueues",{enumerable:!0,configurable:!0,writable:!0,value:new je(this)}),Object.defineProperty(this,"promptWebhooks",{enumerable:!0,configurable:!0,writable:!0,value:new St(this)}),Object.defineProperty(this,"info",{enumerable:!0,configurable:!0,writable:!0,value:new wt(this)}),Object.defineProperty(this,"issues",{enumerable:!0,configurable:!0,writable:!0,value:new xt(this)}),Object.defineProperty(this,"sandboxes",{enumerable:!0,configurable:!0,writable:!0,value:new Re(this)});let s={apiKey:r,tenantID:n,...i,baseURL:e||"https://api.smith.langchain.com/"};this.baseURL=s.baseURL,this.timeout=s.timeout??os.DEFAULT_TIMEOUT,this.logger=s.logger??console;let a="warn";this.logLevel=a,this.logLevel=rs(s.logLevel,"ClientOptions.logLevel",this)??rs(tr("LANGCHAIN_LOG"),"process.env['LANGCHAIN_LOG']",this)??a,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??Mc(),te(this,bn,jc,"f");let o=tr("LANGCHAIN_CUSTOM_HEADERS");if(o){let c={};for(let l of o.split(`
|
|
27
|
+
`)){let u=l.indexOf(":");u>=0&&(c[l.substring(0,u).trim()]=l.substring(u+1).trim())}s.defaultHeaders={...c,...s.defaultHeaders}}this._options=s,this.apiKey=r,this.tenantID=n}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,tenantID:this.tenantID,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){if(!(this.apiKey&&e.get("x-api-key"))&&!r.has("x-api-key")&&!(this.tenantID&&e.get("x-tenant-id"))&&!r.has("x-tenant-id"))throw new Error('Could not resolve authentication method. Expected either apiKey or tenantID to be set. Or for one of the "X-API-Key" or "X-Tenant-Id" headers to be explicitly omitted')}async authHeaders(e){return P([await this.apiKeyAuth(e),await this.tenantIDAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return P([{"X-API-Key":this.apiKey}])}async tenantIDAuth(e){if(this.tenantID!=null)return P([{"X-Tenant-Id":this.tenantID}])}stringifyQuery(e){return Kc(e)}getUserAgent(){return`${this.constructor.name}/JS ${de}`}defaultIdempotencyKey(){return`stainless-node-retry-${Gi()}`}makeStatusError(e,r,n,i){return J.generate(e,r,n,i)}buildURL(e,r,n){let i=!U(this,as,"m",sl).call(this)&&n||this.baseURL,s=Tc(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(s.searchParams);return(!qi(a)||!qi(o))&&(r={...o,...a,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(s.search=this.stringifyQuery(r)),s.toString()}async prepareOptions(e){}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(i=>({method:e,path:r,...i})))}request(e,r=null){return new _t(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let i=await e,s=i.maxRetries??this.maxRetries;r==null&&(r=s),await this.prepareOptions(i);let{req:a,url:o,timeout:c}=await this.buildRequest(i,{retryCount:s-r});await this.prepareRequest(a,{url:o,options:i});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=n===void 0?"":`, retryOf: ${n}`,d=Date.now();if(Y(this).debug(`[${l}] sending request`,$e({retryOfRequestLogID:n,method:i.method,url:o,options:i,headers:a.headers})),i.signal?.aborted)throw new Ve;let f=new AbortController,p=await this.fetchWithTimeout(o,a,c,f).catch(br),h=Date.now();if(p instanceof globalThis.Error){let w=`retrying, ${r} attempts remaining`;if(i.signal?.aborted)throw new Ve;let E=yr(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(r)return Y(this).info(`[${l}] connection ${E?"timed out":"failed"} - ${w}`),Y(this).debug(`[${l}] connection ${E?"timed out":"failed"} (${w})`,$e({retryOfRequestLogID:n,url:o,durationMs:h-d,message:p.message})),this.retryRequest(i,r,n??l);throw Y(this).info(`[${l}] connection ${E?"timed out":"failed"} - error; no more retries left`),Y(this).debug(`[${l}] connection ${E?"timed out":"failed"} (error; no more retries left)`,$e({retryOfRequestLogID:n,url:o,durationMs:h-d,message:p.message})),E?new at:new Me({cause:p})}let m=`[${l}${u}] ${a.method} ${o} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${h-d}ms`;if(!p.ok){let w=await this.shouldRetry(p);if(r&&w){let k=`retrying, ${r} attempts remaining`;return await $c(p.body),Y(this).info(`${m} - ${k}`),Y(this).debug(`[${l}] response error (${k})`,$e({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:h-d})),this.retryRequest(i,r,n??l,p.headers)}let E=w?"error; no more retries left":"error; not retryable";Y(this).info(`${m} - ${E}`);let b=await p.text().catch(k=>br(k).message),R=on(b),v=R?void 0:b;throw Y(this).debug(`[${l}] response error (${E})`,$e({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,message:v,durationMs:Date.now()-d})),this.makeStatusError(p.status,R,v,p.headers)}return Y(this).info(m),Y(this).debug(`[${l}] response start`,$e({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:h-d})),{response:p,options:i,controller:f,requestLogID:l,retryOfRequestLogID:n,startTime:d}}getAPIList(e,r,n){return this.requestAPIList(r,n&&"then"in n?n.then(i=>({method:"get",path:e,...i})):{method:"get",path:e,...n})}requestAPIList(e,r){let n=this.makeRequest(r,null,void 0);return new Sr(this,n,e)}async fetchWithTimeout(e,r,n,i){let{signal:s,method:a,...o}=r||{},c=this._makeAbort(i);s&&s.addEventListener("abort",c,{once:!0});let l=setTimeout(c,n),u=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body=="object"&&o.body!==null&&Symbol.asyncIterator in o.body,d={signal:i.signal,...u?{duplex:"half"}:{},method:"GET",...o};a&&(d.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(l)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,i){let s,a=i?.get("retry-after-ms");if(a){let c=parseFloat(a);Number.isNaN(c)||(s=c)}let o=i?.get("retry-after");if(o&&!s){let c=parseFloat(o);Number.isNaN(c)?s=Date.parse(o)-Date.now():s=c*1e3}if(s===void 0){let c=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(r,c)}return await Cc(s),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let s=r-e,a=Math.min(.5*Math.pow(2,s),16),o=1-Math.random()*.25;return a*o*1e3}async buildRequest(e,{retryCount:r=0}={}){let n={...e},{method:i,path:s,query:a,defaultBaseURL:o}=n,c=this.buildURL(s,a,o);"timeout"in n&&Rc("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:l,body:u}=this.buildBody({options:n}),d=await this.buildHeaders({options:e,method:i,bodyHeaders:l,retryCount:r});return{req:{method:i,headers:d,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...n.fetchOptions??{}},url:c,timeout:n.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:i}){let s={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let a=P([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Lc()},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=P([r]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Vi(e)}:typeof e=="object"&&n.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:U(this,bn,"f").call(this,{body:e,headers:n})}};os=O,bn=new WeakMap,as=new WeakSet,sl=function(){return this.baseURL!=="https://api.smith.langchain.com/"};Object.defineProperty(O,"Langsmith",{enumerable:!0,configurable:!0,writable:!0,value:os});Object.defineProperty(O,"DEFAULT_TIMEOUT",{enumerable:!0,configurable:!0,writable:!0,value:9e4});Object.defineProperty(O,"LangsmithError",{enumerable:!0,configurable:!0,writable:!0,value:W});Object.defineProperty(O,"APIError",{enumerable:!0,configurable:!0,writable:!0,value:J});Object.defineProperty(O,"APIConnectionError",{enumerable:!0,configurable:!0,writable:!0,value:Me});Object.defineProperty(O,"APIConnectionTimeoutError",{enumerable:!0,configurable:!0,writable:!0,value:at});Object.defineProperty(O,"APIUserAbortError",{enumerable:!0,configurable:!0,writable:!0,value:Ve});Object.defineProperty(O,"NotFoundError",{enumerable:!0,configurable:!0,writable:!0,value:ut});Object.defineProperty(O,"ConflictError",{enumerable:!0,configurable:!0,writable:!0,value:dt});Object.defineProperty(O,"RateLimitError",{enumerable:!0,configurable:!0,writable:!0,value:pt});Object.defineProperty(O,"BadRequestError",{enumerable:!0,configurable:!0,writable:!0,value:ot});Object.defineProperty(O,"AuthenticationError",{enumerable:!0,configurable:!0,writable:!0,value:ct});Object.defineProperty(O,"InternalServerError",{enumerable:!0,configurable:!0,writable:!0,value:ht});Object.defineProperty(O,"PermissionDeniedError",{enumerable:!0,configurable:!0,writable:!0,value:lt});Object.defineProperty(O,"UnprocessableEntityError",{enumerable:!0,configurable:!0,writable:!0,value:ft});Object.defineProperty(O,"toFile",{enumerable:!0,configurable:!0,writable:!0,value:yn});O.Sql=It;O.ProductFeedback=Et;O.Agents=yt;O.Fleet=We;O.Sessions=At;O.Datasets=Ue;O.Runs=De;O.Threads=He;O.Traces=Xe;O.Evaluators=bt;O.OnlineEvaluators=vt;O.Public=Je;O.AnnotationQueues=je;O.PromptWebhooks=St;O.Info=wt;O.Issues=xt;O.Sandboxes=Re;var al={};function K(t,e){let r=e?.code??t;al[r]||(al[r]=!0,e?.type&&typeof process<"u"&&typeof process.emitWarning=="function"?process.emitWarning(t,{type:e.type,code:e.code}):e?.type&&e?.code?console.warn(`${e.type} [${e.code}]: ${t}`):console.warn(t))}var g=t=>BigInt(t),ul=g("0x9E3779B1"),dl=g("0x85EBCA77"),dp=g("0xC2B2AE3D"),Qe=g("0x9E3779B185EBCA87"),Tt=g("0xC2B2AE3D27D4EB4F"),fl=g("0x165667B19E3779F9"),ds=g("0x85EBCA77C2B2AE63"),fp=g("0x27D4EB2F165667C5"),pp=g("0x165667919E3779F9"),hp=g("0x9FB21C651E98DF25");function mp(t){let e=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)e[r/2]=parseInt(t.substring(r,r+2),16);return e}var Ce=mp("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),nr=(g(1)<<g(128))-g(1),C=(g(1)<<g(64))-g(1),En=(g(1)<<g(32))-g(1),Be=64,pl=Be/8,_p=8,wn=4;function D(t,e=0){return new Uint8Array(t.buffer,t.byteOffset+e,t.length-e)}function H(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getBigUint64(0,!0)}function rr(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getUint32(0,!0)}function cs(t,e=0){return t[e]}var gp=t=>(t&g(255))<<g(56)|(t&g(65280))<<g(40)|(t&g(16711680))<<g(24)|(t&g(4278190080))<<g(8)|(t&g(0xff00000000))>>g(8)|(t&g(0xff0000000000))>>g(24)|(t&g(0xff000000000000))>>g(40)|(t&g(0xff00000000000000))>>g(56),yp=t=>(t=(t&g(65535))<<g(16)|(t&g(4294901760))>>g(16),t=(t&g(16711935))<<g(8)|(t&g(4278255360))>>g(8),t),bp=(t,e)=>(t&En)*(e&En)&C,ir=t=>{if(!t)throw new Error("Assert failed")};function wp(t,e){return(t<<e|t>>g(32)-e)&En}function hl(t,e,r){for(let n=0;n<pl;n++){let i=H(e,n*8),s=i^H(r,n*8);t[n^1]+=i,t[n]+=bp(s,s>>g(32))}return t}function ol(t,e,r,n){for(let i=0;i<n;i++)hl(t,D(e,i*Be),D(r,i*8));return t}function xp(t,e){for(let r=0;r<pl;r++){let n=H(e,r*8),i=t[r];i=ls(i,g(47)),i^=n,i*=ul,t[r]=i&C}return t}function xn(t,e){return ml(t[0]^H(e,0),t[1]^H(e,_p))}function cl(t,e,r){let n=r;return n+=xn(t.slice(0),D(e,0*wn)),n+=xn(t.slice(2),D(e,4*wn)),n+=xn(t.slice(4),D(e,8*wn)),n+=xn(t.slice(6),D(e,12*wn)),Oe(n&C)}function vp(t,e,r,n,i){let s=Math.floor((r.byteLength-Be)/8),a=Be*s,o=Math.floor((e.byteLength-1)/a);for(let c=0;c<o;c++)t=ol(t,D(e,c*a),r,s),t=i(t,D(r,r.byteLength-Be));{let c=Math.floor((e.byteLength-1-a*o)/Be);t=ol(t,D(e,o*a),r,c),t=n(t,D(e,e.byteLength-Be),D(r,r.byteLength-Be-7))}return t}function Ep(t,e,r){let n=new BigUint64Array([dp,Qe,Tt,fl,ds,dl,fp,ul]);ir(t.length>128),n=vp(n,t,e,hl,xp),ir(n.length*8==64);{let i=cl(n,D(e,11),g(t.byteLength)*Qe&C);return cl(n,D(e,e.byteLength-Be-11),~(g(t.byteLength)*Tt)&C)<<g(64)|i}}function ml(t,e){let r=t*e&nr;return r&C^r>>g(64)}function ll(t,e,r){return ml((H(t,0)^H(e,0)+r)&C,(H(t,8)^H(e,8)-r)&C)}function vn(t,e,r,n,i){let s=t&C,a=t>>g(64)&C;return s+=ll(e,n,i),s^=H(r,0)+H(r,8),s&=C,a+=ll(r,D(n,16),i),a^=H(e,0)+H(e,8),a&=C,a<<g(64)|s}function Oe(t){return t^=t>>g(37),t*=pp,t&=C,t^=t>>g(32),t}function Sn(t){return t^=t>>g(33),t*=Tt,t&=C,t^=t>>g(29),t*=fl,t&=C,t^=t>>g(32),t}function Sp(t,e,r){let n=t.byteLength;ir(n>0&&n<=3);let i=g(cs(t,n-1))|g(n<<8)|g(cs(t,0)<<16)|g(cs(t,n>>1)<<24),s=(g(rr(e,0))^g(rr(e,4)))+r,a=(i^s)&C,o=(g(rr(e,8))^g(rr(e,12)))-r,c=(wp(yp(i),g(13))^o)&C;return(Sn(c)&C)<<g(64)|Sn(a)}function ls(t,e){return t^t>>e}function Ap(t,e,r){let n=t.byteLength;ir(n>=4&&n<=8);{let i=rr(t,0),s=rr(t,n-4),a=g(i)|g(s)<<g(32),o=(H(e,16)^H(e,24))+r&C,l=(a^o)*(Qe+(g(n)<<g(2)))&nr;return l+=(l&C)<<g(65),l&=nr,l^=l>>g(67),ls(ls(l&C,g(35))*hp&C,g(28))|Oe(l>>g(64))<<g(64)}}function Ip(t,e,r){let n=t.byteLength;ir(n>=9&&n<=16);{let i=(H(e,32)^H(e,40))+r&C,s=(H(e,48)^H(e,56))-r&C,a=H(t),o=H(t,n-8),c=(a^o^i)*Qe,l=(c&C)+(g(n-1)<<g(54));c=c&(nr^C)|l,o^=s,c+=o+(o&En)*(dl-g(1))<<g(64),c&=nr,c^=gp(c>>g(64));let u=(c&C)*Tt;return u+=(c>>g(64))*Tt<<g(64),u&=nr,Oe(u&C)|Oe(u>>g(64))<<g(64)}}function Tp(t,e){let r=t.byteLength;return ir(r<=16),r>8?Ip(t,Ce,e):r>=4?Ap(t,Ce,e):r>0?Sp(t,Ce,e):Sn(e^H(Ce,64)^H(Ce,72))|Sn(e^H(Ce,80)^H(Ce,88))<<g(64)}function us(t){return~t+g(1)&C}function Pp(t,e,r){let n=g(t.byteLength)*Qe&C,i=g(t.byteLength-1)/g(32);for(;i>=0;){let o=Number(i);n=vn(n,D(t,16*o),D(t,t.byteLength-16*(o+1)),D(e,32*o),r),i--}let s=n+(n>>g(64))&C;s=Oe(s);let a=(n&C)*Qe+(n>>g(64))*ds+(g(t.byteLength)-r&C)*Tt;return a&=C,a=us(Oe(a)),s|a<<g(64)}function Rp(t,e,r){let n=g(t.byteLength)*Qe&C;for(let a=32;a<160;a+=32)n=vn(n,D(t,a-32),D(t,a-16),D(e,a-32),r);n=Oe(n&C)|Oe(n>>g(64))<<g(64);for(let a=160;a<=t.byteLength;a+=32)n=vn(n,D(t,a-32),D(t,a-16),D(e,3+a-160),r);n=vn(n,D(t,t.byteLength-16),D(t,t.byteLength-32),D(e,103),us(r));let i=n+(n>>g(64))&C;i=Oe(i);let s=(n&C)*Qe+(n>>g(64))*ds+(g(t.byteLength)-r&C)*Tt;return s&=C,s=us(Oe(s)),i|s<<g(64)}function An(t,e=g(0)){let r=t.byteLength;return r<=16?Tp(t,e):r<=128?Pp(t,Ce,e):r<=240?Rp(t,Ce,e):Ep(t,Ce,e)}function _l(t){let e=new Uint8Array(16),r=new DataView(e.buffer),n=t&C,i=t>>g(64);return r.setBigUint64(0,i,!1),r.setBigUint64(8,n,!1),e}var gl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function T(t,e){if(!gl.test(t)){let r=e!==void 0?`Invalid UUID for ${e}: ${t}`:`Invalid UUID: ${t}`;throw new Error(r)}return t}function In(t){let e=typeof t=="string"?Date.parse(t):t;return Ut({msecs:e,seq:0})}function yl(t){if(!gl.test(t))return null;let e=t[14];return parseInt(e,16)}function Cp(t){let e=t.replace(/-/g,""),r=new Uint8Array(16);for(let n=0;n<16;n++)r[n]=parseInt(e.slice(n*2,n*2+2),16);return r}function Op(t){let e=Array.from(t).map(r=>r.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}var kp=new TextEncoder;function Np(t){let e=kp.encode(t),r=An(e);return _l(r)}function sr(t,e){let r=`${t}:${e}`,n=Np(r),i=new Uint8Array(16);if(yl(t)===7){let a=Cp(t);i.set(a.slice(0,6),0)}else i.set(n.slice(10,16),0);return i[6]=112|n[0]&15,i[7]=n[1],i[8]=128|n[2]&63,i.set(n.slice(3,10),9),Op(i)}function bl(){throw new Error("zstd is not available in this runtime")}var fs=new TextEncoder,wl=t=>{let e=new Uint8Array(t.reduce((n,i)=>n+i.byteLength,0)),r=0;for(let n of t)e.set(n,r),r+=n.byteLength;return e},Ar=class{constructor(e="gzip"){Object.defineProperty(this,"encoding",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"boundary",{enumerable:!0,configurable:!0,writable:!0,value:"----LangSmithFormBoundary"+Math.random().toString(36).slice(2)}),Object.defineProperty(this,"uncompressedSize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"count",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"onSent",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chunks",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"readDone",{enumerable:!0,configurable:!0,writable:!0,value:void 0});let r=e==="zstd"?bl():new CompressionStream("gzip");this.writer=r.writable.getWriter();let n=r.readable.getReader();this.readDone=(async()=>{for(;;){let{done:i,value:s}=await n.read();if(i)return;this.chunks.push(s)}})()}static pickEncoding(e){return e&&!1?"zstd":typeof CompressionStream<"u"?"gzip":void 0}async writeParts(e,r,n){this.count+=1,this.context.push(r),this.onSent.push(n),await this._write(wl(e.flatMap(i=>[fs.encode(`--${this.boundary}\r
|
|
28
|
+
Content-Disposition: form-data; name="${i.name}"\r
|
|
29
|
+
Content-Type: ${i.contentType}\r
|
|
30
|
+
\r
|
|
31
|
+
`),i.data,fs.encode(`\r
|
|
32
|
+
`)])))}async close(){await this._write(fs.encode(`--${this.boundary}--\r
|
|
33
|
+
`)),await this.writer.close(),await this.readDone;let e=wl(this.chunks);return this.chunks=[],e}async _write(e){this.uncompressedSize+=e.byteLength,await this.writer.write(e)}};var xl=1000000n,Mp=new TextEncoder,vl=(t,e)=>{if(e===void 0||e>=1)return!0;if(e<=0)return!1;if(t==null)return!0;let r=An(Mp.encode(t.toLowerCase()))%xl;return Number(r)/Number(xl)<e};function Pt(t,e){if(t&&e)throw new Error(`A run is sent to a project (${JSON.stringify(t)}) or to an address, not both.`)}function $p(){return $("PROJECT")||V("LANGCHAIN_SESSION")||void 0}function Ir(){let t=$p(),e=hs();if(t&&e)throw new ke("LANGSMITH_AGENT_* and a project are both set in the environment.");return e?[void 0,e]:[t??"default",void 0]}function Tn(t){K(`LangSmith is not tracing this call: ${t.message}`)}function El(){if(Sl().some(t=>V(t)))try{Ir()}catch(t){K(`${t.message} Runs that name no destination in code are not traced.`)}}function ps(t,{update:e=!1}={}){let r=t,n;if(typeof r.address=="string")try{n=Pn(r.address)}catch{throw new Error("The run's `address` is not a valid agent address.")}else n=be(r.address);delete r.address;let i=r.session_id!=null||r.session_name!=null;!n&&!e&&!i&&(n=hs()),n&&(r.address=Fe(n),i||(delete r.session_name,delete r.session_id))}var Tr={CLICKHOUSE_ONLY:"clickhouse_only",SMITHDB_ONLY:"smithdb_only",DUAL:"dual"};function Al(t){let e=t??{},r=!!(e.ch_query_enabled??!0),n=!!(e.sdb_query_enabled??!1);return!r&&n?Tr.SMITHDB_ONLY:r&&n?Tr.DUAL:Tr.CLICKHOUSE_ONLY}function Cn(t){return`Invalid prompt identifier format: "${t}". Expected one of:
|
|
34
|
+
- "prompt-name" (for private prompts)
|
|
35
|
+
- "owner/prompt-name" (for prompts with explicit owner)
|
|
36
|
+
- "prompt-name:commit-hash" (with commit reference)
|
|
37
|
+
- "owner/prompt-name:commit-hash" (with owner and commit)`}var ms=class 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}},_s=class extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithNotFoundError",this.status=404}};function Pr(t){return t!=null&&typeof t=="object"&&"name"in t&&t?.name==="LangSmithNotFoundError"}function Il(t){return t!=null&&typeof t=="object"&&"name"in t&&t?.name==="LangSmithConflictError"}async function S(t,e,r){let n;if(t.ok){r&&(n=await t.text());return}try{n=await t.text()}catch{n=""}if(t.status===403){let a;try{a=JSON.parse(n)}catch{}a?.error==="org_scoped_key_requires_workspace"&&(n="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}let i=`Failed to ${e}. Received status [${t.status}]: ${t.statusText}. Message: ${n}`;if(t.status===404)throw new _s(i);if(t.status===409)throw new ms(i);let s=new Error(i);throw s.status=t.status,s}var Tl="ERR_CONFLICTING_ENDPOINTS",Rn=class 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:Tl}),this.name="ConflictingEndpointsError"}};function Pl(t){return typeof t=="object"&&t!==null&&t.code===Tl}function ie(t){if(!t||t.split("/").length>2||t.startsWith("/")||t.endsWith("/")||t.split(":").length>2)throw new Error(Cn(t));let[e,r]=t.split(":"),n=r||"latest";if(e.includes("/")){let[i,s]=e.split("/",2);if(!i||!s)throw new Error(Cn(t));return[i,s,n]}else{if(!e)throw new Error(Cn(t));return["-",e,n]}}function Rl(){return""}var Se={join:(...t)=>t.join("/"),dirname:t=>t.split("/").slice(0,-1).join("/")};async function On(t){}async function ar(t,e){}async function Cl(t){return[]}async function Ol(t){return{size:0}}function or(t){return!1}function Rt(t){return""}async function kl(t){}async function kn(t){}function jp(t,e){return e===null?!1:Date.now()-t.createdAt>e*1e3}var Nn=class{constructor(e={}){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ttlSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshIntervalSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_metrics",{enumerable:!0,configurable:!0,writable:!0,value:{hits:0,misses:0,refreshes:0,refreshErrors:0}}),this.configure(e)}get metrics(){return{...this._metrics}}get totalRequests(){return this._metrics.hits+this._metrics.misses}get hitRate(){let e=this.totalRequests;return e>0?this._metrics.hits/e:0}resetMetrics(){this._metrics={hits:0,misses:0,refreshes:0,refreshErrors:0}}get(e,r){if(this.maxSize===0)return;let n=this.cache.get(e);if(!n){this._metrics.misses+=1;return}return this.cache.delete(e),this.cache.set(e,{...n,refreshFunc:r}),this._metrics.hits+=1,n.value}set(e,r,n){if(this.maxSize===0)return;if(this.refreshTimer===void 0&&this.startRefreshLoop(),!this.cache.has(e)&&this.cache.size>=this.maxSize){let s=this.cache.keys().next().value;s!==void 0&&this.cache.delete(s)}let i={value:r,createdAt:Date.now(),refreshFunc:n};this.cache.delete(e),this.cache.set(e,i)}invalidate(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0)}dump(e){let r={};for(let[s,a]of this.cache.entries())r[s]=a.value;let n=Se.dirname(e);or(n)||void 0;let i=`${e}.tmp`;try{JSON.stringify({entries:r},null,2)}catch(s){throw or(i)&&void 0,s}}load(e){if(!or(e))return 0;let r;try{let s=Rt(e);r=JSON.parse(s).entries??null}catch{return 0}if(!r)return 0;let n=0,i=Date.now();for(let[s,a]of Object.entries(r)){if(this.cache.size>=this.maxSize)break;let o={value:a,createdAt:i};this.cache.set(s,o),n+=1}return n}startRefreshLoop(){this.stop(),this.ttlSeconds!==null&&(this.refreshTimer=setInterval(()=>{this.refreshStaleEntries().catch(e=>{console.warn("Unexpected error in cache refresh loop:",e)})},this.refreshIntervalSeconds*1e3),this.refreshTimer.unref&&this.refreshTimer.unref())}getStaleEntries(){let e=[];for(let[r,n]of this.cache.entries())jp(n,this.ttlSeconds)&&e.push([r,n]);return e}async refreshStaleEntries(){let e=this.getStaleEntries();if(e.length!==0){for(let[r,n]of e)if(n.refreshFunc!==void 0)try{let i=await n.refreshFunc();this.set(r,i,n.refreshFunc),this._metrics.refreshes+=1}catch(i){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${r}:`,i)}}}configure(e){this.stop(),this.refreshIntervalSeconds=e.refreshIntervalSeconds??60,this.maxSize=e.maxSize??100,this.ttlSeconds=e.ttlSeconds??300}},Ln=new Nn;var Up=(...t)=>fetch(...t),Dp,Nl=Symbol.for("ls:fetch_implementation");var Ll=()=>globalThis[Nl]===void 0?!0:Dp??!1,Ml=t=>async(...e)=>{if(t||$("DEBUG")==="true"){let[n,i]=e;console.log(`\u2192 ${i?.method||"GET"} ${n}`)}let r=await(globalThis[Nl]??Up)(...e);return(t||$("DEBUG")==="true")&&console.log(`\u2190 ${r.status} ${r.statusText} ${r.url}`),r};var Bp=10,ys=15e3,Fp=ys,$l="created_at";function Gp(t){return new Promise(e=>setTimeout(e,t))}function zp(t){return typeof t=="object"&&t!==null&&t.code==="EEXIST"}function jl(t){try{return Rt(Se.join(t,$l)).split(`
|
|
38
|
+
`)}catch{return}}function qp(t){let e=jl(t);if(e&&e[0]&&e[0].trim()){let r=Date.parse(e[0].trim());if(!Number.isNaN(r))return r}return void 0}async function Kp(t){let e=qp(t);return e===void 0||Date.now()-e<=Fp?!1:(await kn(t),!0)}function Vp(t){let e=jl(t);if(e&&e.length>=2&&e[1].trim())return e[1].trim()}async function Ul(t,e){let r=`${t}.oauth.lock.lock`,n=performance.now()+Math.max(0,e-Date.now()),i=Se.dirname(r);i&&await On(i);let s=globalThis.crypto.randomUUID();for(;;){if(performance.now()>=n)throw new Error("timed out acquiring OAuth refresh lock");try{await kl(r)}catch(a){if(!zp(a))throw a;await Kp(r)||await Gp(Math.min(Bp,Math.max(0,n-performance.now())));continue}try{await ar(Se.join(r,$l),`${new Date().toISOString()}
|
|
39
|
+
${s}
|
|
40
|
+
`)}catch(a){throw await kn(r),a}break}return{async release(){Vp(r)===s&&await kn(r)}}}var $n="https://api.smith.langchain.com",Wp="langsmith-cli",Jp=6e4,Xp=1e4,Qp=5e3,Dl="/.well-known/oauth-authorization-server";function Yp(){let t=Cr();return t==="browser"||t==="webworker"}function Zp(t){let r=t||V("LANGSMITH_CONFIG_FILE")||Se.join(Rl(),".langsmith","config.json");try{return r}catch{return}}function eh(t,e){let r=e||V("LANGSMITH_PROFILE");if(r)return r;if(t.current_profile)return t.current_profile;if(t.profiles?.default)return"default"}function th(t={}){if(Yp())return;let e=Zp(t.configPath);if(!(!e||!or(e)))try{let r=JSON.parse(Rt(e)),n=eh(r,t.profile),i=n?r.profiles?.[n]:void 0;return!n||!i?void 0:{configPath:e,config:r,profileName:n,profile:i}}catch{return}}function xe(t){return t!=null&&t.trim()!==""}function we(t){return t?.trim().replace(/^["']|["']$/g,"")}function Hl(t){let e=t.oauth;if(!e?.refresh_token)return!1;if(!e.access_token)return!0;if(!e.expires_at)return!1;let r=Date.parse(e.expires_at);return Number.isNaN(r)?!1:r<=Date.now()+Jp}function rh(t){if(!we(t.oauth?.access_token))return!1;let e=t.oauth?.expires_at?Date.parse(t.oauth.expires_at):Number.NaN;return Number.isNaN(e)||e>Date.now()}function Fl(t){let e=t;for(;e.endsWith("/");)e=e.slice(0,-1);let r="/api/v1";return e.endsWith(r)?e.slice(0,-r.length):e}function nh(t){let e=Fl(t),r=e.endsWith("/api")?e.slice(0,-4):e,n=[];for(let i of[e,`${r}/api`,r])i&&i!=="/api"&&!n.includes(i)&&n.push(i);return n}function ih(t,e){let{issuer:r}=t;if(typeof r!="string"||r.replace(/\/+$/,"")!==e.replace(/\/+$/,""))return!1;let n;try{n=new URL(r)}catch{return!1}for(let i of[t.device_authorization_endpoint,t.token_endpoint]){if(typeof i!="string"||!i)return!1;try{let s=new URL(i);if(s.protocol!==n.protocol||s.host!==n.host)return!1}catch{return!1}}return!0}function sh(t){let e=`${t}${Dl}`,r;try{let n=new URL(t);r=`${n.origin}${Dl}${n.pathname==="/"?"":n.pathname}`}catch{return[e]}return r===e?[r]:[r,e]}async function ah(t,e,r,n){let i=Math.min(Qp,n-Date.now());if(i<=0)return;let s;try{s=await r(t,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(i)})}catch{return}if(!s.ok)return;let a;try{a=await s.json()}catch{return}if(!(!a||typeof a!="object"||!ih(a,e)))return a}async function oh(t,e,r=Number.POSITIVE_INFINITY){for(let n of nh(t))for(let i of sh(n)){let s=await ah(i,n,e,r);if(s)return s.token_endpoint}return`${Fl(t)}/oauth/token`}function ch(t,e){t.oauth??(t.oauth={}),e.access_token&&(t.oauth.access_token=e.access_token),e.refresh_token&&(t.oauth.refresh_token=e.refresh_token),typeof e.expires_in=="number"&&e.expires_in>0&&(t.oauth.expires_at=new Date(Date.now()+e.expires_in*1e3).toISOString())}function Bl(t){return t.reason??new Error("The operation was aborted.")}async function lh(t,e){if(!e)return t;if(e.aborted)throw Bl(e);let r,n=new Promise((i,s)=>{let a=()=>{s(Bl(e))};e.addEventListener("abort",a,{once:!0}),r=()=>{e.removeEventListener("abort",a)}});try{return await Promise.race([t,n])}finally{r?.()}}function Gl(t={}){let e=th(t),r=e?.profile;if(!e||!r)return{};let n=we(r.api_key),i=we(r.oauth?.access_token),s=we(r.oauth?.refresh_token),a=we(r.api_key_env)||we(r.api_key_cmd);return{apiUrl:r.api_url,apiKey:n,workspaceId:r.workspace_id,oauthAccessToken:i,oauthRefreshToken:s,profileAuth:n||i||s||a?new bs(e):void 0}}var Rr=class extends Error{constructor(e){super(e),this.name="ProfileApiKeyError"}},Mn=class extends Error{constructor(e,r){super(e),this.name="ProfileRefreshLockError",r&&"cause"in r&&(this.cause=r.cause)}},bs=class{constructor(e){Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"refreshPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"managedAuthorizationValue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.rememberProfileAuthHeader(this.currentAuthHeader())}currentAuthHeader(){let e;try{e=uh(this.state)}catch(r){if(!(r instanceof Rr))throw r;e=void 0}return this.rememberProfileAuthHeader(e),e}async getAuthHeader(e,r){Hl(this.state.profile)&&(this.refreshPromise||(this.refreshPromise=this.refreshOAuthToken(e).finally(()=>{this.refreshPromise=void 0})),await lh(this.refreshPromise,r));let n=zl(this.state);return this.rememberProfileAuthHeader(n),n}isProfileAuthorizationHeader(e){return e===this.managedAuthorizationValue}reloadProfile(){try{let e=JSON.parse(Rt(this.state.configPath)),r=e.profiles?.[this.state.profileName];return r?(this.state.config=e,this.state.profile=r,r):void 0}catch{return}}async refreshOAuthToken(e){var r;if(!this.state.profile.oauth?.refresh_token)return;let i=Date.now()+Xp,s;try{try{s=await Ul(this.state.configPath,i)}catch(p){if(!rh(this.state.profile))throw new Mn(`Could not refresh the expired OAuth token for LangSmith profile "${this.state.profileName}": failed to acquire the refresh lock next to ${this.state.configPath} (${p instanceof Error?p.message:String(p)}). Another process may be refreshing it, or the config directory may not be writable; OAuth profiles need a writable config. Use an API key for read-only configs. A lock left by a crashed process is released automatically after ${ys/1e3} seconds.`,{cause:p});return}let a=this.reloadProfile(),o=a?.oauth?.refresh_token;if(!a||!o||!Hl(a))return;let c=we(a.api_url)??$n,l=new URLSearchParams({grant_type:"refresh_token",client_id:Wp,refresh_token:o}),u=await oh(c,e,i);if(Date.now()>=i)return;let d=await e(u,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:l.toString(),signal:AbortSignal.timeout(Math.max(0,i-Date.now()))});if(!d.ok)return;let f=await d.json();if(!f.access_token)return;ch(this.state.profile,f),(r=this.state.config).profiles??(r.profiles={}),this.state.config.profiles[this.state.profileName]=this.state.profile,await ar(this.state.configPath,`${JSON.stringify(this.state.config,null,2)}
|
|
41
|
+
`)}catch(a){if(a instanceof Mn)throw a;return}finally{await s?.release()}}rememberProfileAuthHeader(e){this.managedAuthorizationValue=e?.name==="Authorization"?e.value:void 0}};function uh(t){let{profile:e}=t,r=we(e.oauth?.access_token);if(r)return{name:"Authorization",value:`Bearer ${r}`};if(!we(e.oauth?.refresh_token))return zl(t)}function zl(t){let{profile:e}=t,r=we(e.oauth?.access_token);if(r)return{name:"Authorization",value:`Bearer ${r}`};let n=dh(t.profileName,e);if(n)return{name:"x-api-key",value:n}}function dh(t,e){let r=we(e.api_key);if(r)return r;let n=we(e.api_key_env);if(n){let i=V(n)?.trim();if(i)return i;throw new Rr(`LangSmith profile "${t}" reads its API key from $${n}, which is not set`)}if(we(e.api_key_cmd))throw new Rr(`LangSmith profile "${t}" gets its API key from a command (api_key_cmd), which the JS SDK does not support yet. Set api_key_env in the profile, or set LANGSMITH_API_KEY.`)}var ql="[...]",fh={result:"[Circular]"},Un=[],cr=[],ph=new TextEncoder;function hh(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function jn(t){return ph.encode(t)}function Kl(t){if(t&&typeof t=="object"&&t!==null){if(t instanceof Map)return Object.fromEntries(t);if(t instanceof Set)return Array.from(t);if(t instanceof Date)return t.toISOString();if(t instanceof RegExp)return t.toString();if(t instanceof Error)return{name:t.name,message:t.message}}else if(typeof t=="bigint")return t.toString();return t}function mh(t){return function(e,r){if(t){let n=t.call(this,e,r);if(n!==void 0)return n}return Kl(r)}}function Vl(t){try{let i=function(u){let d=n(u);return d>r&&(r=d),d+2},s=function(u){return u===0?2:2+u*4},a=function(u){return u===void 0||typeof u=="function"||typeof u=="symbol"},o=function(u){return u===void 0||typeof u=="function"||typeof u=="symbol"?4:c(u)},c=function(u){if(u===null)return 4;if(u===void 0)return 0;let d=typeof u;if(d==="boolean")return 5;if(d==="number")return Number.isFinite(u)?u.toString().length:4;if(d==="bigint")return u.toString().length+2;if(d==="string")return i(u);if(d==="function"||d==="symbol")return 0;let f=u;if(f instanceof Date)return 26;if(f instanceof RegExp)return n(f.toString())+2;if(f instanceof Error){let h=f.name??"",m=f.message??"";return 22+n(h)+n(m)}if(typeof Buffer<"u"&&f instanceof Buffer)return 28+s(f.byteLength);if(ArrayBuffer.isView(f)){if(f instanceof DataView)return 2;let h=f.length??0,w=f instanceof Float32Array||f instanceof Float64Array?30:12;return 2+h*w}if(f instanceof ArrayBuffer)return 2;if(e.has(f))return 24;if(typeof f.toJSON=="function"){let h;try{h=f.toJSON("")}catch{return 16}e.add(f);let m=c(h);return e.delete(f),m}e.add(f);let p;if(Array.isArray(f)){p=2;let h=f.length;for(let m=0;m<h;m++)p+=o(f[m]),m<h-1&&(p+=1)}else if(f instanceof Map){p=2;let h=0;for(let[m,w]of f){if(a(w))continue;h>0&&(p+=1);let E=typeof m=="string"?m:String(m);p+=n(E)+3,p+=c(w),h++}}else if(f instanceof Set){p=2;let h=0;for(let m of f)h>0&&(p+=1),p+=o(m),h++}else{p=2;let h=0,m=Object.keys(f);for(let w=0;w<m.length;w++){let E=m[w],b=f[E];a(b)||(h>0&&(p+=1),p+=n(E)+3,p+=c(b),h++)}}return e.delete(f),p},e=new Set,r=0,n=typeof Buffer<"u"&&typeof Buffer.byteLength=="function"?u=>Buffer.byteLength(u,"utf8"):u=>u.length;return{size:c(t),maxStringLen:r}}catch{return{size:se(t).length,maxStringLen:0}}}function se(t,e,r,n,i){try{let s=JSON.stringify(t,mh(r),n);return jn(s)}catch(s){if(!s.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`
|
|
42
|
+
Context: ${e}`:""}`),jn("[Unserializable]");$("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
|
|
43
|
+
Context: ${e}`:""}`),typeof i>"u"&&(i=hh()),xs(t,"",0,[],void 0,0,i);let a;try{cr.length===0?a=JSON.stringify(t,r,n):a=JSON.stringify(t,_h(r),n)}catch{return jn("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Un.length!==0;){let o=Un.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return jn(a)}}function ws(t,e,r,n){var i=Object.getOwnPropertyDescriptor(n,r);i.get!==void 0?i.configurable?(Object.defineProperty(n,r,{value:t}),Un.push([n,r,e,i])):cr.push([e,r,t]):(n[r]=t,Un.push([n,r,e]))}function xs(t,e,r,n,i,s,a){s+=1;var o;if(typeof t=="object"&&t!==null){for(o=0;o<n.length;o++)if(n[o]===t){ws(fh,t,e,i);return}if(typeof a.depthLimit<"u"&&s>a.depthLimit){ws(ql,t,e,i);return}if(typeof a.edgesLimit<"u"&&r+1>a.edgesLimit){ws(ql,t,e,i);return}if(n.push(t),Array.isArray(t))for(o=0;o<t.length;o++)xs(t[o],o,o,n,t,s,a);else{t=Kl(t);var c=Object.keys(t);for(o=0;o<c.length;o++){var l=c[o];xs(t[l],l,o,n,t,s,a)}}n.pop()}}function _h(t){return t=typeof t<"u"?t:function(e,r){return r},function(e,r){if(cr.length>0)for(var n=0;n<cr.length;n++){var i=cr[n];if(i[1]===e&&i[0]===r){r=i[2],cr.splice(n,1);break}}return t.call(this,e,r)}}var yh=`
|
|
44
|
+
const { parentPort } = require("worker_threads");
|
|
45
|
+
|
|
46
|
+
const CIRCULAR_REPLACE_NODE = { result: "[Circular]" };
|
|
47
|
+
|
|
48
|
+
function serializeWellKnownTypes(val) {
|
|
49
|
+
if (val && typeof val === "object") {
|
|
50
|
+
if (val instanceof Map) return Object.fromEntries(val);
|
|
51
|
+
if (val instanceof Set) return Array.from(val);
|
|
52
|
+
if (val instanceof Date) return val.toISOString();
|
|
53
|
+
if (val instanceof RegExp) return val.toString();
|
|
54
|
+
if (val instanceof Error) return { name: val.name, message: val.message };
|
|
55
|
+
} else if (typeof val === "bigint") {
|
|
56
|
+
return val.toString();
|
|
57
|
+
}
|
|
58
|
+
return val;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function defaultReplacer(_key, val) {
|
|
62
|
+
return serializeWellKnownTypes(val);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Decirculate in-place: replace circular refs with { result: "[Circular]" }
|
|
66
|
+
// then restore after stringify. Mirrors fast-safe-stringify's decirc().
|
|
67
|
+
const restoreStack = [];
|
|
68
|
+
function decirc(val, k, stack, parent) {
|
|
69
|
+
if (typeof val === "object" && val !== null) {
|
|
70
|
+
for (let i = 0; i < stack.length; i++) {
|
|
71
|
+
if (stack[i] === val) {
|
|
72
|
+
const orig = parent[k];
|
|
73
|
+
parent[k] = CIRCULAR_REPLACE_NODE;
|
|
74
|
+
restoreStack.push([parent, k, orig]);
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
stack.push(val);
|
|
79
|
+
if (Array.isArray(val)) {
|
|
80
|
+
for (let i = 0; i < val.length; i++) decirc(val[i], i, stack, val);
|
|
81
|
+
} else {
|
|
82
|
+
const normalized = serializeWellKnownTypes(val);
|
|
83
|
+
// Only recurse into normalized if it's still an object (arrays/objects),
|
|
84
|
+
// else it was replaced with a primitive (e.g. Date -> string).
|
|
85
|
+
if (normalized === val) {
|
|
86
|
+
const keys = Object.keys(val);
|
|
87
|
+
for (let i = 0; i < keys.length; i++) decirc(val[keys[i]], keys[i], stack, val);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
stack.pop();
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function serialize(obj) {
|
|
95
|
+
try {
|
|
96
|
+
return JSON.stringify(obj, defaultReplacer);
|
|
97
|
+
} catch (e) {
|
|
98
|
+
if (!String(e && e.message).includes("Converting circular structure to JSON")) {
|
|
99
|
+
return "[Unserializable]";
|
|
100
|
+
}
|
|
101
|
+
decirc(obj, "", [], { "": obj });
|
|
102
|
+
try {
|
|
103
|
+
return JSON.stringify(obj, defaultReplacer);
|
|
104
|
+
} catch (_) {
|
|
105
|
+
return "[unable to serialize, circular reference is too complex to analyze]";
|
|
106
|
+
} finally {
|
|
107
|
+
while (restoreStack.length) {
|
|
108
|
+
const [p, k, v] = restoreStack.pop();
|
|
109
|
+
p[k] = v;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
parentPort.on("message", (msg) => {
|
|
116
|
+
const { id, op, payload } = msg;
|
|
117
|
+
try {
|
|
118
|
+
if (op === "serialize") {
|
|
119
|
+
const str = serialize(payload);
|
|
120
|
+
const buf = Buffer.from(str, "utf8");
|
|
121
|
+
// Slice into its own ArrayBuffer so we can transfer without dragging
|
|
122
|
+
// unrelated bytes from any shared pool buffer.
|
|
123
|
+
const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
|
|
124
|
+
parentPort.postMessage({ id, bytes: ab, length: buf.byteLength }, [ab]);
|
|
125
|
+
} else if (op === "ping") {
|
|
126
|
+
parentPort.postMessage({ id });
|
|
127
|
+
} else {
|
|
128
|
+
parentPort.postMessage({ id, error: "unknown op: " + op });
|
|
129
|
+
}
|
|
130
|
+
} catch (e) {
|
|
131
|
+
parentPort.postMessage({ id, error: String((e && e.message) || e) });
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
`,Es=class{constructor(){Object.defineProperty(this,"worker",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"nextId",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"pending",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"disabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"startPromise",{enumerable:!0,configurable:!0,writable:!0,value:null})}async ensureStarted(){if(this.disabled)return!1;if(this.worker!==null)return!0;if(this.startPromise!==null)return this.startPromise;this.startPromise=this._start();try{return await this.startPromise}finally{this.startPromise=null}}async _start(){if(!!1||null===null)return this.disabled=!0,!1;try{let e=new null(yh,{eval:!0});return e.on("message",r=>{let n=this.pending.get(r.id);n&&(this.pending.delete(r.id),r.error?n.reject(new Error(r.error)):r.bytes&&typeof r.length=="number"?n.resolve(new Uint8Array(r.bytes,0,r.length)):n.reject(new Error("worker returned malformed message")))}),e.on("error",r=>{for(let[,n]of this.pending)n.reject(r);this.pending.clear(),this.disabled=!0,this.worker=null}),e.on("exit",r=>{for(let[,n]of this.pending)n.reject(new Error(`worker exited with code ${r}`));this.pending.clear(),this.worker=null}),e.unref(),this.worker=e,!0}catch{return this.disabled=!0,!1}}async serialize(e){if(!await this.ensureStarted())return null;let n=this.nextId++;return new Promise((i,s)=>{this.pending.set(n,{resolve:i,reject:s});try{this.worker.postMessage({id:n,op:"serialize",payload:e})}catch(a){this.pending.delete(n),s(a)}})}async terminate(){this.worker&&(await this.worker.terminate(),this.worker=null);for(let[,e]of this.pending)e.reject(new Error("worker terminated"));this.pending.clear()}},vs=null;function Jl(){return vs===null&&(vs=new Es),vs}var bh=64*1024,wh=2048;function Xl(t,e=bh,r=wh){if(t===null||typeof t!="object")return typeof t=="string"&&t.length>=e;let n=[t],i=new Set,s=0;for(;n.length>0;){if(s++>=r)return!1;let a=n.pop();if(a==null)continue;let o=typeof a;if(o==="string"){if(a.length>=e)return!0;continue}if(o!=="object")continue;let c=a;if(i.has(c)||(i.add(c),c instanceof Date||c instanceof RegExp||c instanceof Error||c instanceof ArrayBuffer||ArrayBuffer.isView(c)))continue;if(Array.isArray(c)){for(let u=c.length-1;u>=0;u--)n.push(c[u]);continue}if(c instanceof Map){for(let[,u]of c)n.push(u);continue}if(c instanceof Set){for(let u of c)n.push(u);continue}let l=Object.keys(c);for(let u=l.length-1;u>=0;u--)n.push(c[l[u]])}return!1}function xh(t,e){let[r]=ie(t);if(r!=="-"&&!e)throw new Error("Pulling a public prompt by owner/name is disabled by default because prompts may contain untrusted serialized LangChain objects. If you trust this prompt, set `dangerouslyPullPublicPrompt: true` to acknowledge the risk.")}function Ql(t){return typeof t=="string"&&t.length>0&&!t.includes("Z")&&!t.includes("+")&&!t.includes("-",10)?t+"Z":t}function lr(t){return{...t,start_time:Ql(t.start_time),end_time:Ql(t.end_time)}}function Yl(t){let e={};for(let r of t){if(!r.id)continue;let n=e[r.id];n!==void 0&&n.session_name!==r.session_name&&console.warn(`LangSmith run ${r.id} was queued for two projects with the same id (${JSON.stringify(n.session_name)} and ${JSON.stringify(r.session_name)}); only one of the projects will keep the run. This usually means two write replicas both keep the original run ids, for example a replica marked \`primary\` plus one for the run's own project.`),e[r.id]=r}return e}function Ss(t,e,r,n){if(r)return t;let i=Dn(),s=e??Ts(),a=t.extra??{},o=a.metadata;return t.extra={...a,runtime:{...i,...a?.runtime},metadata:{...s,...s.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??s.revision_id}:{},...o,...n!==void 0?{ls_tracing_sample_rate:n}:{}}},t}var vh=t=>{let e=t?.toString()??$("TRACING_SAMPLING_RATE");if(e===void 0)return;let r=parseFloat(e);if(r<0||r>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r},Eh=t=>{let r=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"};async function Sh(t){let e=[];for await(let r of t)e.push(r);return e}function Or(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}var Ah=async t=>{if(t?.status===429){let e=parseInt(t.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(r=>setTimeout(r,e)),!0}return!1};function Zl(t){return typeof t=="number"?Number(t.toFixed(4)):t}function Ih(t,e){if(!t)return;let r=l=>l.split(".").map(u=>parseInt(u,10)),[n,i,s]=r(t),[a,o,c]=r(e);if(isNaN(n)||isNaN(i)||isNaN(s)||isNaN(a)||isNaN(o)||isNaN(c)){console.warn(`[LANGSMITH]: Could not parse backend version ${JSON.stringify(t)} for compatibility check.`);return}(n<a||n===a&&i<o||n===a&&i===o&&s<c)&&console.warn(`[LANGSMITH]: Backend version ${JSON.stringify(t)} is older than the minimum version required by this SDK (${JSON.stringify(e)}). Some features may not work as expected. See https://docs.langchain.com/langsmith/smithdb-sdk-migration`)}var Th=24*1024*1024,As=1024*1024*1024,Ph=1e4,Rh=100,eu=1e4;async function Ch(t){return t.status===405?!0:t.status!==404?!1:!(await t.clone().text()).toLowerCase().includes("dataset not found")}function su(t,e){new Headers({[t]:e})}function tu(t){for(let[e,r]of Object.entries(t??{}))su(e,r)}function ru(t){if(!t)return{};let e=t instanceof Headers?[...t.entries()]:Array.isArray(t)?t.map(([i,s])=>[i,s]):Object.entries(t),r={},n=new Map;for(let[i,s]of e){su(i,s);let a=i.toLowerCase(),o=n.get(a);o===void 0?(n.set(a,i),r[i]=s):r[o]=s}return r}function Oh(t,e,r){let n={...t},i=new Map(Object.keys(n).map(s=>[s.toLowerCase(),s]));for(let[s,a]of Object.entries(e)){let o=s.toLowerCase();n[i.get(o)??s]=a}for(let s of Object.keys(n))r.has(s.toLowerCase())&&delete n[s];return n}var Is=class{constructor(e){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"maxSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSizeBytes=e??As}peek(){return this.items[0]}push(e){let r,n=new Promise(s=>{r=s}),i=Vl(e.item).size;return this.sizeBytes+i>this.maxSizeBytes&&this.sizeBytes>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${e.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${i} bytes.`),r(),n):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,workspaceId:e.workspaceId,itemPromiseResolve:r,itemPromise:n,size:i}),this.sizeBytes+=i,n)}pop({upToSizeBytes:e,upToSize:r}){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");let n=[],i=0;for(;i+(this.peek()?.size??0)<e&&this.items.length>0&&n.length<r;){let s=this.items.shift();s&&(n.push(s),i+=s.size,this.sizeBytes-=s.size)}if(n.length===0&&this.items.length>0){let s=this.items.shift();n.push(s),i+=s.size,this.sizeBytes-=s.size}return[n.map(s=>({action:s.action,item:s.payload,otelContext:s.otelContext,apiKey:s.apiKey,apiUrl:s.apiUrl,workspaceId:s.workspaceId,size:s.size})),()=>n.forEach(s=>s.itemPromiseResolve())]}},Ye=class t{get tracingMode(){return this._tracingMode}_applyReplicaWorkspace(e,r){r?.workspaceId!==void 0?e["x-tenant-id"]=r.workspaceId:r?.apiUrl!==void 0&&r.apiKey!==void 0&&r.apiKey!==this.apiKey&&new URL(r.apiUrl).host!==new URL(this.apiUrl).host&&delete e["x-tenant-id"]}get _fetch(){let e=this.fetchImplementation||Ml(this.debug);return(async(r,n)=>{let i,s=this.getProfileManagedAuthorizationHeader(n);return this.apiKey!==void 0?i={name:"x-api-key",value:`${this.apiKey}`}:this.hasExplicitAuthHeader(n,s)||(i=await this.profileAuth?.getAuthHeader(e,n?.signal)),e(r,this.applyCurrentAuthHeaders(n,i,s))})}getProfileManagedAuthorizationHeader(e){if(!e?.headers||!this.profileAuth)return;let r=new Headers(e.headers).get("Authorization");if(xe(r))return this.profileAuth.isProfileAuthorizationHeader(r??"")?r??void 0:void 0}isProfileManagedAuthorizationHeader(e,r){return e===r||this.profileAuth?.isProfileAuthorizationHeader(e)===!0}hasExplicitAuthHeader(e,r){if(!e?.headers)return!1;let n=new Headers(e.headers);if(xe(n.get("x-api-key")))return!0;let i=n.get("Authorization");return xe(i)?!this.isProfileManagedAuthorizationHeader(i??"",r):!1}applyCurrentAuthHeaders(e,r,n){if(!r)return e;let i=d=>{if(this.apiKey!==void 0&&r.name==="x-api-key")return d.delete("Authorization"),d.has("x-api-key")||d.set("x-api-key",r.value),d;if(r.name==="Authorization"){if(xe(d.get("x-api-key")))return d;let p=d.get("Authorization");return xe(p)&&!this.isProfileManagedAuthorizationHeader(p??"",n)||d.set("Authorization",r.value),d}let f=d.get("Authorization");return xe(f)&&!this.isProfileManagedAuthorizationHeader(f??"",n)||(xe(f)&&d.delete("Authorization"),d.has("x-api-key")||d.set("x-api-key",r.value)),d};if(!e)return{headers:{[r.name]:r.value}};if(e.headers instanceof Headers)return{...e,headers:i(new Headers(e.headers))};if(Array.isArray(e.headers))return{...e,headers:i(new Headers(e.headers))};let s={...e.headers??{}},a=d=>Object.keys(s).find(f=>f.toLowerCase()===d),o=d=>{let f=a(d);return f?s[f]:void 0},c=xe(o("x-api-key")),l=o("authorization"),u=xe(l)&&!this.isProfileManagedAuthorizationHeader(l??"",n);if(this.apiKey!==void 0&&r.name==="x-api-key"){let d=a("authorization");return d&&delete s[d],c||(s["x-api-key"]=r.value),{...e,headers:s}}if(r.name==="Authorization"){if(!c&&!u){let d=a("authorization");d&&d!=="Authorization"&&delete s[d],s.Authorization=r.value}return{...e,headers:s}}if(!u){let d=a("authorization");d&&delete s[d],c||(s["x-api-key"]=r.value)}return{...e,headers:s}}_trackDrain(e){this._pendingDrains.add(e),e.finally(()=>{this._pendingDrains.delete(e)})}async _serializeBody(e,r){if(this.manualFlushMode)return se(e,r);if(!Xl(e))return se(e,r);if(this._serializeWorker===void 0&&(this._serializeWorker=Jl()),this._serializeWorker===null)return se(e,r);try{let n=await this._serializeWorker.serialize(e);return n===null?(this._serializeWorker=null,se(e,r)):n}catch{return se(e,r)}}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,"hideMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"anonymizer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitTracedRuntimeInfo",{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,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),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,"_fetchOptionsHeaders",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"_openAPIClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_openAPIClientSignature",{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:V("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,"_stainlessVersionsChecked",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_serializeWorker",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_pendingDrains",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_compressedBuffers",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"_compressedWriteChain",{enumerable:!0,configurable:!0,writable:!0,value:Promise.resolve()}),Object.defineProperty(this,"_compressedFlushTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_maxIngestMemoryBytes",{enumerable:!0,configurable:!0,writable:!0,value:As}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tracingMode",{enumerable:!0,configurable:!0,writable:!0,value:"langsmith"}),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,"_promptCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"profileAuth",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:$("DISABLE_MULTIPART_STREAMING")==="true"}),Object.defineProperty(this,"_multipartDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_runCompressionDisabled",{enumerable:!0,configurable:!0,writable:!0,value:$("DISABLE_RUN_COMPRESSION")==="true"}),Object.defineProperty(this,"failedTracesDir",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"failedTracesMaxBytes",{enumerable:!0,configurable:!0,writable:!0,value:100*1024*1024}),Object.defineProperty(this,"_customHeaders",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:V("LANGSMITH_DEBUG")==="true"});let r=t.getDefaultClientConfig({profile:e.profile,apiKey:e.apiKey,profileConfigPath:e.profileConfigPath,preferProfileAuth:e.preferProfileAuth});this.tracingSampleRate=vh(e.tracingSamplingRate),this.apiUrl=Or(e.apiUrl??r.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1));let n=Or(e.apiKey??r.apiKey);if(this.apiKey=xe(n)?n:void 0,this.profileAuth=this.apiKey!==void 0?void 0:r.profileAuth,this.webUrl=Or(e.webUrl??r.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=Or(e.workspaceId??r.workspaceId),this.timeout_ms=e.timeout_ms??9e4,this.caller=new gr({...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.");if(this.debug=e.debug??this.debug,this.debug){let c=e.apiUrl!=null?"apiUrl option":r.apiUrlSource;console.log(`LangSmith API URL ${this.apiUrl} resolved from ${c}`)}this.fetchImplementation=e.fetchImplementation,this.failedTracesDir=$("FAILED_TRACES_DIR")||void 0;let i=$("FAILED_TRACES_MAX_MB");if(i){let c=parseInt(i,10);Number.isFinite(c)&&c>0&&(this.failedTracesMaxBytes=c*1024*1024)}let s=e.maxIngestMemoryBytes??As;this._maxIngestMemoryBytes=s,this.batchIngestCaller=new gr({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:s,...e.callerOptions??{},onFailedResponseHook:Ah,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??r.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??r.hideOutputs,this.hideMetadata=e.hideMetadata??e.anonymizer??r.hideMetadata,this.anonymizer=e.anonymizer,this.omitTracedRuntimeInfo=e.omitTracedRuntimeInfo??!1,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new Is(s),this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit;let{headers:a,...o}=e.fetchOptions||{};this.fetchOptions=o,this._fetchOptionsHeaders=ru(a),tu(e.headers),this._customHeaders=e.headers??{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,this._tracingMode=Yr(e.tracingMode),this._tracingMode==="otel"&&(this.langSmithToOTELTranslator=new Zr),this.cachedLSEnvVarsForMetadata=Ts(),El(),e.cache!==void 0&&e.disablePromptCache&&K("Both 'cache' and 'disablePromptCache' were provided. The 'cache' parameter is deprecated and will be removed in a future version. Using 'cache' parameter value."),e.cache!==void 0?(K("The 'cache' parameter is deprecated and will be removed in a future version. Use 'configureGlobalPromptCache()' to configure the global cache, or 'disablePromptCache: true' to disable caching for this client."),e.cache===!1?this._promptCache=void 0:e.cache===!0?this._promptCache=Ln:this._promptCache=e.cache):e.disablePromptCache||(this._promptCache=Ln)}static getDefaultClientConfig(e={}){let r=Gl({profile:e.profile,configPath:e.profileConfigPath}),n=e.preferProfileAuth===!0&&!xe(Or(e.apiKey))&&r.profileAuth!==void 0,i=n?void 0:$("API_KEY"),s=n?void 0:$("ENDPOINT"),a=n&&r.workspaceId!=null?void 0:$("WORKSPACE_ID"),o=xe(i),c=s??r.apiUrl??$n,l=s!=null?"LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT environment variable":r.apiUrl!=null?"profile config":"built-in default",u=a??r.workspaceId,d=$("HIDE_INPUTS")==="true",f=$("HIDE_OUTPUTS")==="true",p=$("HIDE_METADATA")==="true";return{apiUrl:c,apiUrlSource:l,apiKey:i,webUrl:void 0,hideInputs:d,hideOutputs:f,hideMetadata:p,workspaceId:u,oauthAccessToken:o?void 0:r.oauthAccessToken,oauthRefreshToken:o?void 0:r.oauthRefreshToken,profileAuth:o?void 0:r.profileAuth}}getHostUrl(){return this.webUrl?this.webUrl:Eh(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("aws")?(this.webUrl="https://aws.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("apac")?(this.webUrl="https://apac.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 _sdkControlledHeaders(){let e=new Set;if(this.apiKey!==void 0)e.add("x-api-key");else{let r=this.profileAuth?.currentAuthHeader();r&&e.add(r.name.toLowerCase())}return this.workspaceId&&e.add("x-tenant-id"),e}get _callerHeaders(){return Oh(ru(this._customHeaders),this._fetchOptionsHeaders,this._sdkControlledHeaders)}get _mergedHeaders(){let e={"User-Agent":`langsmith-js/${de}`,...this._callerHeaders};if(this.apiKey!==void 0)e["x-api-key"]=`${this.apiKey}`;else{let r=this.profileAuth?.currentAuthHeader();r&&(e[r.name]=r.value)}return this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}get _openAPIClientOptions(){let e={...this._callerHeaders};Object.keys(e).some(i=>i.toLowerCase()==="user-agent")||(e["User-Agent"]=`langsmith-js/${de}`);let r=Object.keys(e).find(i=>i.toLowerCase()==="x-api-key"),n=this.apiKey;return n===void 0&&r!==void 0&&(n=e[r]??void 0,delete e[r]),n===void 0&&this.workspaceId===void 0&&(e["X-API-Key"]=null),{apiKey:n,defaultHeaders:Object.keys(e).length>0?e:void 0}}get headers(){return this._customHeaders}set headers(e){tu(e),this._customHeaders=e??{}}_getOpenAPIBaseUrl(){return Mo(this.apiUrl)}get openAPIClient(){let e=this._openAPIClientOptions,r=JSON.stringify([e.apiKey,e.defaultHeaders]);return(this._openAPIClient===void 0||this._openAPIClientSignature!==r)&&(this._openAPIClientSignature=r,this._openAPIClient=this._newOpenAPIClient(e)),this._openAPIClient}_newOpenAPIClient(e=this._openAPIClientOptions){let{method:r,body:n,signal:i,...s}=this.fetchOptions;return new O({apiKey:e.apiKey,tenantID:this.workspaceId,baseURL:this._getOpenAPIBaseUrl(),timeout:this.timeout_ms,fetch:this._fetch,fetchOptions:s,defaultHeaders:e.defaultHeaders})}_getPlatformEndpointPath(e){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${e}`:`/platform/${e}`}get evaluators(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.onlineEvaluators}get runs(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.runs}get sandboxes(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.sandboxes}get datasets(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.datasets}get annotationQueues(){return this._checkStainlessVersion("0.16.14"),this.openAPIClient.annotationQueues}get threads(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.threads}get traces(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.traces}get sessions(){return this._checkStainlessVersion("0.18.0"),this.openAPIClient.sessions}get agents(){return this.openAPIClient.agents}get public(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.public}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 processMetadata(e){return this.hideMetadata===!1?e:this.hideMetadata===!0?{}:typeof this.hideMetadata=="function"?this.hideMetadata(e):e}async processError(e){if(this.anonymizer==null)return e;let r=await this.anonymizer({error:e});return typeof r?.error=="string"?r.error:e}_filterNewTokenEvents(e){return!e||e.length===0?e:e.map(r=>{if(r.name==="new_token"){let{kwargs:n,...i}=r;return i}return r})}async prepareRunCreateOrUpdateInputs(e,r){let n={...e};return ps(n,{update:r?.update??!1}),n.inputs!==void 0&&(n.inputs=await this.processInputs(n.inputs)),n.outputs!==void 0&&(n.outputs=await this.processOutputs(n.outputs)),n.error!==void 0&&(n.error=await this.processError(n.error)),n.extra!=null&&"metadata"in n.extra&&(n.extra={...n.extra,metadata:await this.processMetadata(n.extra.metadata)}),n.events!==void 0&&(n.events=this._filterNewTokenEvents(n.events)),n}async _getResponse(e,r){let n=r?.toString()??"",i=`${this.apiUrl}${e}?${n}`;return await this.caller.call(async()=>{let a=await this._fetch(i,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(a,`fetch ${e}`),a})}async _get(e,r){return(await this._getResponse(e,r)).json()}async*_getPaginated(e,r=new URLSearchParams,n){let i=Number(r.get("offset"))||0,s=Number(r.get("limit"))||100;for(;;){r.set("offset",String(i)),r.set("limit",String(s));let a=`${this.apiUrl}${e}?${r}`,o=await this.caller.call(async()=>{let l=await this._fetch(a,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(l,`fetch ${e}`),l}),c=n?n(await o.json()):await o.json();if(c.length===0||(yield c,c.length<s))break;i+=c.length}}async*_getCursorPaginatedList(e,r=null,n="POST",i="runs"){let s=r?{...r}:{};for(;;){let a=JSON.stringify(s),c=await(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}${e}`,{method:n,headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await S(u,`fetch ${e}`),u})).json();if(!c||!c[i])break;yield c[i];let l=c.cursors;if(!l||!l.next)break;s.cursor=l.next}}_shouldSample(e){return vl(e,this.tracingSampleRate)}_filterForSampling(e){return e.filter(r=>this._shouldSample(r.trace_id??r.dotted_order?.split(".",1)[0].split("Z")[1]??r.id))}async _getBatchSizeLimitBytes(){let e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e?.batch_ingest_config?.size_limit_bytes??Th}async _getBatchSizeLimit(){let e=await this._ensureServerInfo();return this.batchSizeLimit??e?.batch_ingest_config?.size_limit??Rh}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:r}){let n=[];for(;this.autoBatchQueue.items.length>0;){let[i,s]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:r});if(!i.length){s();break}let a=i.reduce((l,u)=>{let d=u.apiUrl??this.apiUrl,f=u.apiKey??this.apiKey,p=u.workspaceId,m=u.apiKey===this.apiKey&&u.apiUrl===this.apiUrl&&u.workspaceId===this.workspaceId?"default":`${d}|${f}|${p??""}`;return l[m]||(l[m]=[]),l[m].push(u),l},{}),o=[];for(let[l,u]of Object.entries(a)){let d=l==="default",f=d?[]:l.split("|"),p=f[2],h=this._processBatch(u,{apiUrl:d?void 0:f[0],apiKey:d?void 0:f[1],workspaceId:d||!p?void 0:p});o.push(h)}let c=Promise.all(o).finally(s);n.push(c)}return Promise.all(n)}static async _writeTraceToFallbackDir(e,r,n,i,s){try{let a=typeof r=="string"?Buffer.from(r,"utf8"):Buffer.from(r),o=JSON.stringify({version:1,endpoint:i,headers:n,body_base64:a.toString("base64")}),c=`trace_${Date.now()}_${st().slice(0,8)}.json`,l=Se.join(e,c);if(t._fallbackDirsCreated.has(e)||(await On(e),t._fallbackDirsCreated.add(e)),s!==void 0&&s>0)try{let d=(await Cl(e)).filter(p=>p.startsWith("trace_")&&p.endsWith(".json")),f=0;for(let p of d){let{size:h}=await Ol(Se.join(e,p));f+=h}if(f>=s){console.warn(`Could not write trace to fallback dir ${e} as it's already over size limit (${f} bytes >= ${s} bytes). Increase LANGSMITH_FAILED_TRACES_MAX_MB if possible.`);return}}catch{}await ar(l,o),console.warn(`LangSmith trace upload failed; data saved to ${l} for later replay.`)}catch(a){console.error(`LangSmith tracing error: could not write trace to fallback dir ${e}:`,a)}}async _processBatch(e,r){if(!e.length)return;let n=e.reduce((a,o)=>a+(o.size??0),0),i=e.filter(a=>a.action==="feedback").map(a=>a.item),s=e.filter(a=>a.action!=="feedback");try{if(this.langSmithToOTELTranslator!==void 0){for(let a of s)a.item=await this._maskRunMetadata(a.item);this._sendBatchToOTELTranslator(s),await this._postFeedbacks(i,r)}else{let a={runCreates:e.filter(l=>l.action==="create").map(l=>l.item),runUpdates:e.filter(l=>l.action==="update").map(l=>l.item)},o=await this._ensureServerInfo();if(!this._multipartDisabled&&(o?.batch_ingest_config?.use_multipart_endpoint??!0)){let l=!this._runCompressionDisabled&&o?.instance_flags?.gzip_body_enabled;try{await this.multipartIngestRuns({...a,feedbacks:i},{...r,useGzip:l,sizeBytes:n})}catch(u){if(Pr(u))this._multipartDisabled=!0,await this.batchIngestRuns(a,{...r,sizeBytes:n}),await this._postFeedbacks(i,r);else throw u}}else await this.batchIngestRuns(a,{...r,sizeBytes:n}),await this._postFeedbacks(i,r)}}catch(a){console.error("Error exporting batch:",a)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){let r=new Map,n=[];for(let i of e)i.item.id&&i.otelContext&&(r.set(i.item.id,i.otelContext),i.action==="create"?n.push({operation:"post",id:i.item.id,trace_id:i.item.trace_id??i.item.id,run:i.item}):n.push({operation:"patch",id:i.item.id,trace_id:i.item.trace_id??i.item.id,run:i.item}));this.langSmithToOTELTranslator.exportBatch(n,r)}}async _maskRunMetadata(e){return e.extra?.metadata==null?e:{...e,extra:{...e.extra,metadata:await this.processMetadata(e.extra.metadata)}}}async _mergeRuntimeEnvAndMaskMetadata(e){let r=Ss(e,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo,this.tracingSampleRate);return this.omitTracedRuntimeInfo?r:this._maskRunMetadata(r)}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.action!=="feedback"&&(e.item=Ss(e.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo,this.tracingSampleRate));let r=this.autoBatchQueue.push(e);if(this.manualFlushMode)return r;let n=await this._getBatchSizeLimitBytes(),i=await this._getBatchSizeLimit();return this._queueEncoding()!==void 0?(this._moveQueueToCompressed(),r):((this.autoBatchQueue.sizeBytes>n||this.autoBatchQueue.items.length>i)&&this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:i})),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:i}))},this.autoBatchAggregationDelayMs)),r)}async _getServerInfo(){let r=await(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(Ph),...this.fetchOptions});return await S(n,"get server info"),n})).json();return this.debug&&console.log(`
|
|
135
|
+
=== LangSmith Server Configuration ===
|
|
136
|
+
`+JSON.stringify(r,null,2)+`
|
|
137
|
+
`),r}_checkStainlessVersion(e){this._stainlessVersionsChecked.has(e)||(this._stainlessVersionsChecked.add(e),this._ensureServerInfo().then(r=>{Ih(r?.version,e)}).catch(()=>{}))}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 _supportsSDBQuery(){return(await this._ensureServerInfo()).instance_flags?.sdb_query_enabled===!0}async _checkFeedbackSessionId(){let e="https://docs.langchain.com/langsmith/smithdb-sdk-migration-feedback#feedback-create",r=await this._ensureServerInfo();if(Al(r.instance_flags)===Tr.SMITHDB_ONLY)throw new Error(`sessionId must be provided when creating feedback for a run: this deployment cannot locate the run without it. See ${e}`);K(`Creating feedback for a run without sessionId is deprecated and will stop working in a future release. See ${e}`)}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}_queueEncoding(){let e=this._serverInfo;if(e===void 0||this.langSmithToOTELTranslator!==void 0||this._runCompressionDisabled||this._multipartDisabled||!(e.batch_ingest_config?.use_multipart_endpoint??!0))return;let r=Ar.pickEncoding(e.instance_flags?.zstd_compression_enabled===!0);if(!(r==="gzip"&&!e.instance_flags?.gzip_body_enabled))return r}_moveQueueToCompressed(){let e=this.autoBatchQueue.items.splice(0);for(let r of e){let{itemPromiseResolve:n,size:i}=r;this._enqueueCompressed(i,{action:r.action,item:r.payload,otelContext:r.otelContext,apiKey:r.apiKey,apiUrl:r.apiUrl,workspaceId:r.workspaceId}).then(n)}}async _serializeQueuedOperation(e){if(e.action==="feedback"){let i=e.item;return{parts:[await this._serializeFeedbackPart(i)],context:`trace=${i.trace_id},id=${i.id}`}}let r=e.action==="create"?await this.prepareRunCreateOrUpdateInputs(e.item):await this.prepareRunCreateOrUpdateInputs(e.item,{update:!0}),n=r.attachments;return delete r.attachments,{parts:await this._serializeRunParts(e.action==="create"?"post":"patch",r,n),context:`trace=${r.trace_id},id=${r.id}`}}_enqueueCompressed(e,r){let n,i=new Promise(c=>{n=c}),s=r.apiKey===this.apiKey&&r.apiUrl===this.apiUrl&&r.workspaceId===this.workspaceId,a=s?"default":`${r.apiUrl??this.apiUrl}|${r.apiKey??this.apiKey}|${r.workspaceId??this.workspaceId??""}`,o=async()=>{let c;try{c=await this._serializeQueuedOperation(r)}finally{this.autoBatchQueue.sizeBytes-=e}let{parts:l,context:u}=c,d=await this._getBatchSizeLimitBytes(),f=await this._getBatchSizeLimit(),p=l.reduce((m,w)=>m+w.data.byteLength,0),h=this._compressedBuffers.get(a);h!==void 0&&h.buffer.count>0&&h.buffer.uncompressedSize+p>this._maxIngestMemoryBytes&&(this._compressedBuffers.delete(a),this._trackDrain(this._sendCompressedBuffer(h)),h=void 0),h===void 0&&(h={buffer:new Ar(this._queueEncoding()??"gzip"),apiKey:s?void 0:r.apiKey??this.apiKey,apiUrl:s?void 0:r.apiUrl??this.apiUrl,workspaceId:s?void 0:r.workspaceId??this.workspaceId},this._compressedBuffers.set(a,h)),await h.buffer.writeParts(l,u,n),(h.buffer.uncompressedSize>=d||h.buffer.count>=f)&&(this._compressedBuffers.delete(a),this._trackDrain(this._sendCompressedBuffer(h)))};return this._compressedWriteChain=this._compressedWriteChain.then(o).catch(c=>{console.error("Error queueing run for tracing:",c),n()}),!this.manualFlushMode&&this._compressedFlushTimeout===void 0&&(this._compressedFlushTimeout=setTimeout(()=>{this._compressedFlushTimeout=void 0,this._trackDrain(this._flushCompressedBuffers())},this.autoBatchAggregationDelayMs)),i}async _sendCompressedBuffer(e){let{buffer:r}=e;try{let n=await r.close();await this._sendCompressedMultipart(n,r,e)}catch(n){console.error("Error exporting batch:",n)}finally{for(let n of r.onSent)n()}}async _flushCompressedBuffers(){let e=this._compressedWriteChain.then(()=>{let n=[...this._compressedBuffers.values()];return this._compressedBuffers.clear(),n});this._compressedWriteChain=e.then(()=>{});let r=await e;await Promise.all(r.map(n=>this._sendCompressedBuffer(n)))}async _sendCompressedMultipart(e,r,n){let i=r.context.join("; "),s={...this._mergedHeaders,"Content-Type":`multipart/form-data; boundary=${r.boundary}`,"Content-Encoding":r.encoding};n.apiKey!==void 0&&(s["x-api-key"]=n.apiKey),n.workspaceId!==void 0&&(s["x-tenant-id"]=n.workspaceId);try{await this.batchIngestCaller.callWithOptions({sizeBytes:e.byteLength},async()=>{let a=await this._fetch(`${n.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:s,body:e,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(a,"Failed to send multipart request",!0),a})}catch(a){Pr(a)&&(this._multipartDisabled=!0),console.warn(`${a.message.trim()}
|
|
138
|
+
|
|
139
|
+
Context: ${i}`),this.failedTracesDir&&await t._writeTraceToFallbackDir(this.failedTracesDir,e.buffer,{"Content-Type":`multipart/form-data; boundary=${r.boundary}`,"Content-Encoding":r.encoding},"runs/multipart",this.failedTracesMaxBytes)}}async flush(){let e=await this._getBatchSizeLimitBytes(),r=await this._getBatchSizeLimit();await Promise.all([this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:r}),this._flushCompressedBuffers()])}_cloneCurrentOTELContext(){let e=Qr(),r=hc();if(this.langSmithToOTELTranslator!==void 0){let n=e.getActiveSpan();if(n)return e.setSpan(r.active(),n)}}async createRun(e,r){if(!this._filterForSampling([e]).length)return;let n={...this._mergedHeaders,"Content-Type":"application/json"},i=be(e.address),s=e.session_name;Pt(e.project_name??s,i);let a=e.project_name;if(delete e.project_name,!a&&s==null&&!i)try{e.address=Ir()[1]}catch(u){if(!(u instanceof ke))throw u;Tn(u);return}let o=await this.prepareRunCreateOrUpdateInputs({session_name:a,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&o.trace_id!==void 0&&o.dotted_order!==void 0){let u=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:o,otelContext:u,apiKey:r?.apiKey,apiUrl:r?.apiUrl,workspaceId:r?.workspaceId}).catch(console.error);return}let c=await this._mergeRuntimeEnvAndMaskMetadata(o);r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),this._applyReplicaWorkspace(n,r);let l=se(c,`Creating run with id: ${c.id}`);await this.caller.call(async()=>{let u=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await S(u,"create run",!0),u})}async batchIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let i=await Promise.all(e?.map(l=>this.prepareRunCreateOrUpdateInputs(l))??[]),s=await Promise.all(r?.map(l=>this.prepareRunCreateOrUpdateInputs(l,{update:!0}))??[]),a=Yl(i);if(i.length>0&&s.length>0){let l=[];for(let u of s)u.id!==void 0&&a[u.id]?a[u.id]={...a[u.id],...u}:l.push(u);i=Object.values(a),s=l}let o={post:i,patch:s};if(!o.post.length&&!o.patch.length)return;let c={post:[],patch:[]};for(let l of["post","patch"]){let u=l,d=o[u].reverse(),f=d.pop();for(;f!==void 0;)c[u].push(f),f=d.pop()}if(c.post.length>0||c.patch.length>0){let l=c.post.map(u=>u.id).concat(c.patch.map(u=>u.id)).join(",");await this._postBatchIngestRuns(await this._serializeBody(c,`Ingesting runs with ids: ${l}`),n)}}async _postBatchIngestRuns(e,r){let n={...this._mergedHeaders,"Content-Type":"application/json",Accept:"application/json"};r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),this._applyReplicaWorkspace(n,r),await this.batchIngestCaller.callWithOptions({sizeBytes:r?.sizeBytes},async()=>{let i=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await S(i,"batch create run",!0),i})}async multipartIngestRuns({runCreates:e,runUpdates:r,feedbacks:n},i){if(e===void 0&&r===void 0&&!n?.length)return;let s={},a=[];for(let h of e??[]){let m=await this.prepareRunCreateOrUpdateInputs(h);m.id!==void 0&&m.attachments!==void 0&&(s[m.id]=m.attachments),delete m.attachments,a.push(m)}let o=[];for(let h of r??[]){let m=await this.prepareRunCreateOrUpdateInputs(h,{update:!0});m.id!==void 0&&m.attachments!==void 0&&(s[m.id]={...s[m.id],...m.attachments}),delete m.attachments,o.push(m)}if(a.find(h=>h.trace_id===void 0||h.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(o.find(h=>h.trace_id===void 0||h.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');let u=Yl(a);if(a.length>0&&o.length>0){let h=[];for(let m of o)m.id!==void 0&&u[m.id]?u[m.id]={...u[m.id],...m}:h.push(m);a=Object.values(u),o=h}if(a.length===0&&o.length===0&&!n?.length)return;let d=[],f=[],p=h=>({name:h.name,payload:new Blob([h.data],{type:h.contentType})});for(let[h,m]of[["post",a],["patch",o]])for(let w of m){let E=w.id!==void 0?s[w.id]:void 0;w.id!==void 0&&delete s[w.id];let b=await this._serializeRunParts(h,w,E);f.push(...b.map(p)),d.push(`trace=${w.trace_id},id=${w.id}`)}for(let h of n??[])f.push(p(await this._serializeFeedbackPart(h))),d.push(`trace=${h.trace_id},id=${h.id}`);await this._sendMultipartRequest(f,d.join("; "),i)}async _serializeRunParts(e,r,n){let i=[],{inputs:s,outputs:a,events:o,extra:c,error:l,serialized:u,attachments:d,...f}=r,p={inputs:s,outputs:a,events:o,extra:c,error:l,serialized:u},h=await this._serializeBody(f,`Serializing for multipart ingestion of run with id: ${f.id}`);i.push({name:`${e}.${f.id}`,contentType:`application/json; length=${h.length}`,data:h});for(let[m,w]of Object.entries(p)){if(w===void 0)continue;let E=await this._serializeBody(w,`Serializing ${m} for multipart ingestion of run with id: ${f.id}`);i.push({name:`${e}.${f.id}.${m}`,contentType:`application/json; length=${E.length}`,data:E})}for(let[m,w]of Object.entries(n??{})){let E,b;if(Array.isArray(w)?[E,b]=w:(E=w.mimeType,b=w.data),m.includes(".")){console.warn(`Skipping attachment '${m}' for run ${f.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}i.push({name:`attachment.${f.id}.${m}`,contentType:`${E}; length=${b.byteLength}`,data:b instanceof Uint8Array?b:new Uint8Array(b)})}return i}async _serializeFeedbackPart(e){let r=await this._serializeBody(e,`Serializing for multipart ingestion of feedback with id: ${e.id}`);return{name:`feedback.${e.id}`,contentType:`application/json; length=${r.length}`,data:r}}async _createNodeFetchBody(e,r){let n=[];for(let a of e)n.push(new Blob([`--${r}\r
|
|
140
|
+
`])),n.push(new Blob([`Content-Disposition: form-data; name="${a.name}"\r
|
|
141
|
+
`,`Content-Type: ${a.payload.type}\r
|
|
142
|
+
\r
|
|
143
|
+
`])),n.push(a.payload),n.push(new Blob([`\r
|
|
144
|
+
`]));return n.push(new Blob([`--${r}--\r
|
|
145
|
+
`])),await new Blob(n).arrayBuffer()}async _createMultipartStream(e,r){let n=new TextEncoder;return new ReadableStream({async start(s){let a=async o=>{typeof o=="string"?s.enqueue(n.encode(o)):s.enqueue(o)};for(let o of e){await a(`--${r}\r
|
|
146
|
+
`),await a(`Content-Disposition: form-data; name="${o.name}"\r
|
|
147
|
+
`),await a(`Content-Type: ${o.payload.type}\r
|
|
148
|
+
\r
|
|
149
|
+
`);let l=o.payload.stream().getReader();try{let u;for(;!(u=await l.read()).done;)s.enqueue(u.value)}finally{l.releaseLock()}await a(`\r
|
|
150
|
+
`)}await a(`--${r}--\r
|
|
151
|
+
`),s.close()}})}async _sendMultipartRequest(e,r,n){let i="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),s=()=>this._createNodeFetchBody(e,i),a=()=>this._createMultipartStream(e,i),o=async c=>this.batchIngestCaller.callWithOptions({sizeBytes:n?.sizeBytes},async()=>{let l=await c(),u={...this._mergedHeaders,"Content-Type":`multipart/form-data; boundary=${i}`};n?.apiKey!==void 0&&(u["x-api-key"]=n.apiKey),this._applyReplicaWorkspace(u,n);let d=l;n?.useGzip&&typeof l=="object"&&"pipeThrough"in l&&(d=l.pipeThrough(new CompressionStream("gzip")),u["Content-Encoding"]="gzip");let f=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:u,body:d,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(f,"Failed to send multipart request",!0),f});try{let c,l=!1;Ll()&&!this.multipartStreamingDisabled&&Cr()!=="bun"?(l=!0,c=await o(a)):c=await o(s),(!this.multipartStreamingDisabled||l)&&c.status===422&&(n?.apiUrl??this.apiUrl)!==$n&&(console.warn(`Streaming multipart upload to ${n?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${r}".`),this.multipartStreamingDisabled=!0,c=await o(s))}catch(c){if(Pr(c))throw c;if(console.warn(`${c.message.trim()}
|
|
152
|
+
|
|
153
|
+
Context: ${r}`),this.failedTracesDir){let l=await this._createNodeFetchBody(e,i).catch(()=>null);l&&await t._writeTraceToFallbackDir(this.failedTracesDir,l,{"Content-Type":`multipart/form-data; boundary=${i}`},"runs/multipart",this.failedTracesMaxBytes)}}}async updateRun(e,r,n){T(e),r.inputs&&(r.inputs=await this.processInputs(r.inputs)),r.outputs&&(r.outputs=await this.processOutputs(r.outputs)),r.error&&(r.error=await this.processError(r.error)),r.extra!=null&&"metadata"in r.extra&&(r.extra={...r.extra,metadata:await this.processMetadata(r.extra.metadata)}),r.events&&(r.events=this._filterNewTokenEvents(r.events)),be(r.address);let i={...r,id:e};if(!this._filterForSampling([i]).length)return;if(this.autoBatchTracing&&i.trace_id!==void 0&&i.dotted_order!==void 0){let c=this._cloneCurrentOTELContext();if(r.end_time!==void 0&&i.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:i,otelContext:c,apiKey:n?.apiKey,apiUrl:n?.apiUrl,workspaceId:n?.workspaceId}).catch(console.error);return}else this.processRunOperation({action:"update",item:i,otelContext:c,apiKey:n?.apiKey,apiUrl:n?.apiUrl,workspaceId:n?.workspaceId}).catch(console.error);return}let s={...this._mergedHeaders,"Content-Type":"application/json"};n?.apiKey!==void 0&&(s["x-api-key"]=n.apiKey),this._applyReplicaWorkspace(s,n);let a={...r};ps(a,{update:!0});let o=se(a.extra?Ss(a,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo,this.tracingSampleRate):a,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{let c=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:s,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await S(c,"update run",!0),c})}async readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){return K("readRun() is deprecated and will be removed after Jan 31, 2027. Use client.runs.retrieve() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration-runs#runs-retrieve for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_READ_RUN"}),this._readRun(e,{loadChildRuns:r})}async _readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){T(e);let n=lr(await this._get(`/runs/${e}`));return r&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:e,run:r,projectOpts:n,address:i}){if(K("getRunUrl() is deprecated and will be removed after Jan 31, 2027. Use client.runs.getURL() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration-runs#runs-get-url for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_GET_RUN_URL"}),r!==void 0){let s=Ps(i);Pt(n?.projectName??n?.projectId,s);let a=s??be(r.address),o;r.session_id?o=r.session_id:n?.projectName?o=(await this.readProject({projectName:n?.projectName})).id:n?.projectId?o=n?.projectId:a?o=await this._resolveAddress(a):o=(await this.readProject({projectName:$("PROJECT")||"default"})).id;let c=await this._getTenantId();return`${this.getHostUrl()}/o/${c}/projects/p/${o}/r/${r.id}?poll=true`}else if(e!==void 0){let 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 _resolveAddress(e){let{session_id:r}=await this.sessions.resolve(e);return T(r),r}async _loadChildRuns(e){let r=await Sh(this._listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),n={},i={};r.sort((s,a)=>(s?.dotted_order??"").localeCompare(a?.dotted_order??""));for(let s of r){if(s.parent_run_id===null||s.parent_run_id===void 0)throw new Error(`Child run ${s.id} has no parent`);s.dotted_order?.startsWith(e.dotted_order??"")&&s.id!==e.id&&(s.parent_run_id in n||(n[s.parent_run_id]=[]),n[s.parent_run_id].push(s),i[s.id]=s)}e.child_runs=n[e.id]||[];for(let s in n)s!==e.id&&(i[s].child_runs=n[s]);return e}async*listRuns(e){K("listRuns() is deprecated and will be removed after Jan 31, 2027. Use client.runs.query() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration-query-runs#runs-query for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_LIST_RUNS"}),yield*this._listRuns(e)}async*_listRuns(e){let{projectId:r,projectName:n,parentRunId:i,traceId:s,referenceExampleId:a,startTime:o,executionOrder:c,isRoot:l,runType:u,error:d,id:f,query:p,filter:h,traceFilter:m,treeFilter:w,limit:E,select:b,order:R}=e,v=[];if(r&&(v=Array.isArray(r)?r:[r]),n){let L=Array.isArray(n)?n:[n],G=await Promise.all(L.map(j=>this.readProject({projectName:j}).then(le=>le.id)));v.push(...G)}let M=["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"],k={session:v.length?v:null,run_type:u,reference_example:a,query:p,filter:h,trace_filter:m,tree_filter:w,execution_order:c,parent_run:i,start_time:o?o.toISOString():null,error:d,id:f,limit:E,trace:s,select:b||M,is_root:l,order:R};k.select.includes("child_run_ids")&&K("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let N=0;for await(let L of this._getCursorPaginatedList("/runs/query",k)){let G=L.map(lr);if(E){if(N>=E)break;if(G.length+N>E){yield*G.slice(0,E-N);break}N+=G.length,yield*G}else yield*G}}async*listGroupRuns(e){let{projectId:r,projectName:n,groupBy:i,filter:s,startTime:a,endTime:o,limit:c,offset:l}=e,d={session_id:r||(await this.readProject({projectName:n})).id,group_by:i,filter:s,start_time:a?a.toISOString():null,end_time:o?o.toISOString():null,limit:Number(c)||100},f=Number(l)||0,p="/runs/group",h=`${this.apiUrl}${p}`;for(;;){let m={...d,offset:f},w=Object.fromEntries(Object.entries(m).filter(([k,N])=>N!==void 0)),E=JSON.stringify(w),R=await(await this.caller.call(async()=>{let k=await this._fetch(h,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:E});return await S(k,`Failed to fetch ${p}`),k})).json(),{groups:v,total:M}=R;if(v.length===0)break;for(let k of v)yield k;if(f+=v.length,f>=M)break}}async*readThread(e){K("readThread() is deprecated and will be removed after Jan 31, 2027. Use client.threads.listTraces() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration-threads#threads-list-traces for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_READ_THREAD"});let{threadId:r,projectId:n,projectName:i,isRoot:s=!0,limit:a,filter:o,order:c="asc"}=e;if(!n&&!i)throw new Error("threadId requires projectId or projectName");let l=`eq(thread_id, ${JSON.stringify(r)})`,u=o?`and(${l}, ${o})`:l;yield*this._listRuns({projectId:n??void 0,projectName:i??void 0,isRoot:s,limit:a,filter:u,order:c})}async listThreads(e){K("listThreads() is deprecated and will be removed after Jan 31, 2027. Use client.threads.query() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration-threads#threads-query for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_LIST_THREADS"});let{projectId:r,projectName:n,limit:i,offset:s=0,filter:a,startTime:o,isRoot:c=!0}=e;if(!r&&!n)throw new Error("Either projectId or projectName must be provided");if(r&&n)throw new Error("Provide exactly one of projectId or projectName");let l=r??(await this.readProject({projectName:n})).id,u=o??new Date(Date.now()-1440*60*1e3),f={session:[l],is_root:c,limit:100,order:"desc",select:["id","name","status","start_time","end_time","thread_id","trace_id","run_type","error","tags","session_id","parent_run_id","total_tokens","total_cost","dotted_order","reference_example_id","feedback_stats","app_path","completion_cost","completion_tokens","prompt_cost","prompt_tokens","first_token_time"],start_time:u.toISOString()};a!=null&&(f.filter=a);let p=new Map;for await(let E of this._getCursorPaginatedList("/runs/query",f))for(let b of E){let R=lr(b),v=R.thread_id;if(v){let M=p.get(v)??[];M.push(R),p.set(v,M)}}let h=[];for(let[E,b]of p.entries()){b.sort((N,L)=>{let G=N,j=L,le=G.start_time??"",dr=j.start_time??"";if(le!==dr)return le.localeCompare(dr);let fr=G.dotted_order??"",Vn=j.dotted_order??"";return fr.localeCompare(Vn)});let v=[...b.map(N=>N.start_time).filter(Boolean)].sort(),M=v.length?v[0]:"",k=v.length?v[v.length-1]:"";h.push({thread_id:E,runs:b,count:b.length,filter:"",total_tokens:0,total_cost:null,min_start_time:M,max_start_time:k,latency_p50:0,latency_p99:0,feedback_stats:null,first_inputs:"",last_outputs:"",last_error:null})}h.sort((E,b)=>{let R=E.max_start_time??"";return(b.max_start_time??"").localeCompare(R)});let m=s>0?h.slice(s):h;return i!==void 0?m.slice(0,i):m}async getRunStats({id:e,trace:r,parentRun:n,runType:i,projectNames:s,projectIds:a,referenceExampleIds:o,startTime:c,endTime:l,error:u,query:d,filter:f,traceFilter:p,treeFilter:h,isRoot:m,dataSourceType:w}){let E=a||[];if(s&&(E=[...a||[],...await Promise.all(s.map(N=>this.readProject({projectName:N}).then(L=>L.id)))]),E.length===0)throw new Error("At least one of projectNames or projectIds must be provided.");let R=Object.fromEntries(Object.entries({id:e,trace:r,parent_run:n,run_type:i,session:E,reference_example:o,start_time:c,end_time:l,error:u,query:d,filter:f,trace_filter:p,tree_filter:h,is_root:m,data_source_type:w}).filter(([N,L])=>L!==void 0)),v=JSON.stringify(R);return await(await this.caller.call(async()=>{let N=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:v});return await S(N,"get run stats"),N})).json()}async shareRun(e,{shareId:r}={}){K("shareRun() is deprecated and will be removed after Jan 31, 2027. Use client.runs.share.create() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration-feedback#share-and-read-public-runs for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_SHARE_RUN"});let n={run_id:e,share_token:r||st()};T(e);let i=JSON.stringify(n),a=await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await S(o,"share run"),o})).json();if(a===null||!("share_token"in a))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${a.share_token}/r`}async unshareRun(e){K("unshareRun() is deprecated and will be removed after Jan 31, 2027. Use client.runs.share.delete() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration-feedback#share-and-read-public-runs for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_UNSHARE_RUN"}),T(e),await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(r,"unshare run",!0),r})}async readRunSharedLink(e){K('readRunSharedLink() is deprecated and will be removed after Jan 31, 2027. Use client.runs.retrieve({ selects: ["SHARE_URL"] }) instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration-feedback#share-and-read-public-runs for the migration guide.',{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_READ_RUN_SHARED_LINK"}),T(e);let n=await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(i,"read run shared link"),i})).json();if(!(n===null||!("share_token"in n)))return`${this.getHostUrl()}/public/${n.share_token}/r`}async listSharedRuns(e,{runIds:r}={}){K("listSharedRuns() is deprecated and will be removed after Jan 31, 2027. Use client.public.runs.query() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration-feedback#share-and-read-public-runs for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_LIST_SHARED_RUNS"});let n=new URLSearchParams({share_token:e});if(r!==void 0)for(let a of r)n.append("id",a);return T(e),(await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/public/${e}/runs${n}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(a,"list shared runs"),a})).json()).map(lr)}async readDatasetSharedSchema(e,r){if(!e&&!r)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:r})).id),T(e);let i=await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(s,"read dataset shared schema"),s})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async shareDataset(e,r){if(!e&&!r)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:r})).id);let n={dataset_id:e};T(e);let i=JSON.stringify(n),a=await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await S(o,"share dataset"),o})).json();return a.url=`${this.getHostUrl()}/public/${a.share_token}/d`,a}async unshareDataset(e){T(e),await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(r,"unshare dataset",!0),r})}async readSharedDataset(e){return T(e),await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(i,"read shared dataset"),i})).json()}async listSharedExamples(e,r){let n={};r?.exampleIds&&(n.id=r.exampleIds);let i=new URLSearchParams;Object.entries(n).forEach(([o,c])=>{Array.isArray(c)?c.forEach(l=>i.append(o,l)):i.append(o,c)});let s=await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/public/${e}/examples?${i.toString()}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(o,"list shared examples"),o}),a=await s.json();if(!s.ok)throw"detail"in a?new Error(`Failed to list shared examples.
|
|
154
|
+
Status: ${s.status}
|
|
155
|
+
Message: ${Array.isArray(a.detail)?a.detail.join(`
|
|
156
|
+
`):"Unspecified error"}`):new Error(`Failed to list shared examples: ${s.status} ${s.statusText}`);return a.map(o=>({...o,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:r=null,metadata:n=null,upsert:i=!1,projectExtra:s=null,referenceDatasetId:a=null,numExamples:o=null,numRepetitions:c=null,evaluatorKeys:l=null,tagValueIds:u=null}){let d=i?"?upsert=true":"",f=`${this.apiUrl}/sessions${d}`,p=s||{};n&&(p.metadata=n);let h={name:e,extra:p,description:r};a!==null&&(h.reference_dataset_id=a),o!=null&&(h.num_examples=o),c!=null&&(h.num_repetitions=c),l!=null&&l.length>0&&(h.evaluator_keys=l),u!==null&&(h.tag_value_ids=u);let m=JSON.stringify(h);return await(await this.caller.call(async()=>{let b=await this._fetch(f,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:m});return await S(b,"create project"),b})).json()}async updateProject(e,{name:r=null,description:n=null,metadata:i=null,projectExtra:s=null,endTime:a=null}){let o=`${this.apiUrl}/sessions/${e}`,c=s;i&&(c={...c||{},metadata:i});let l=JSON.stringify({name:r,extra:c,description:n,end_time:a?new Date(a).toISOString():null});return await(await this.caller.call(async()=>{let f=await this._fetch(o,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await S(f,"update project"),f})).json()}async hasProject({projectId:e,projectName:r}){let n="/sessions",i=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)T(e),n+=`/${e}`;else if(r!==void 0)i.append("name",r);else throw new Error("Must provide projectName or projectId");let s=await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${n}?${i}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(a,"has project"),a});try{let a=await s.json();return s.ok?Array.isArray(a)?a.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:r,includeStats:n}){let i="/sessions",s=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)T(e),i+=`/${e}`;else if(r!==void 0)s.append("name",r);else throw new Error("Must provide projectName or projectId");n!==void 0&&s.append("include_stats",n.toString());let a=await this._get(i,s),o;if(Array.isArray(a)){if(a.length===0)throw new Error(`Project[id=${e}, name=${r}] not found`);o=a[0]}else o=a;return o}async getProjectUrl({projectId:e,projectName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either projectName or projectId");let n=await this.readProject({projectId:e,projectName:r}),i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${n.id}`}async getDatasetUrl({datasetId:e,datasetName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");let n=await this.readDataset({datasetId:e,datasetName:r}),i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let e=new URLSearchParams({limit:"1"});for await(let r of this._getPaginated("/sessions",e))return this._tenantId=r[0].tenant_id,r[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:r,nameContains:n,referenceDatasetId:i,referenceDatasetName:s,includeStats:a,datasetVersion:o,referenceFree:c,metadata:l}={}){let u=new URLSearchParams;if(e!==void 0)for(let d of e)u.append("id",d);if(r!==void 0&&u.append("name",r),n!==void 0&&u.append("name_contains",n),i!==void 0)u.append("reference_dataset",i);else if(s!==void 0){let d=await this.readDataset({datasetName:s});u.append("reference_dataset",d.id)}a!==void 0&&u.append("include_stats",a.toString()),o!==void 0&&u.append("dataset_version",o),c!==void 0&&u.append("reference_free",c.toString()),l!==void 0&&u.append("metadata",JSON.stringify(l));for await(let d of this._getPaginated("/sessions",u))yield*d}async deleteProject({projectId:e,projectName:r}){let n;if(e===void 0&&r===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?n=(await this.readProject({projectName:r})).id:n=e,T(n),await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/sessions/${n}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(i,`delete session ${n} (${r})`,!0),i})}async uploadCsv({csvFile:e,fileName:r,inputKeys:n,outputKeys:i,description:s,dataType:a,name:o}){let c=`${this.apiUrl}/datasets/upload`,l=new FormData,u=new Blob([e],{type:"text/csv"});return l.append("file",u,r),n.forEach(p=>{l.append("input_keys",p)}),i.forEach(p=>{l.append("output_keys",p)}),s&&l.append("description",s),a&&l.append("data_type",a),o&&l.append("name",o),await(await this.caller.call(async()=>{let p=await this._fetch(c,{method:"POST",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await S(p,"upload CSV"),p})).json()}async createDataset(e,{description:r,dataType:n,inputsSchema:i,outputsSchema:s,metadata:a,tagValueIds:o}={}){let c={name:e,description:r,extra:{source:"sdk",...a?{metadata:a}:{}}};n&&(c.data_type=n),i&&(c.inputs_schema_definition=i),s&&(c.outputs_schema_definition=s),o!==void 0&&(c.tag_value_ids=o);let l=JSON.stringify(c);return await(await this.caller.call(async()=>{let f=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await S(f,"create dataset"),f})).json()}async readDataset({datasetId:e,datasetName:r}){let n="/datasets",i=new URLSearchParams({limit:"1"});if(e&&r)throw new Error("Must provide either datasetName or datasetId, not both");if(e)T(e),n+=`/${e}`;else if(r)i.append("name",r);else throw new Error("Must provide datasetName or datasetId");let s=await this._get(n,i),a;if(Array.isArray(s)){if(s.length===0)throw new Error(`Dataset[id=${e}, name=${r}] not found`);a=s[0]}else a=s;return a}async hasDataset({datasetId:e,datasetName:r}){try{return await this.readDataset({datasetId:e,datasetName:r}),!0}catch(n){if(n instanceof Error&&n.message.toLocaleLowerCase().includes("not found"))return!1;throw n}}async diffDatasetVersions({datasetId:e,datasetName:r,fromVersion:n,toVersion:i}){let s=e;if(s===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");if(s!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");s===void 0&&(s=(await this.readDataset({datasetName:r})).id);let a=new URLSearchParams({from_version:typeof n=="string"?n:n.toISOString(),to_version:typeof i=="string"?i:i.toISOString()});return await this._get(`/datasets/${s}/versions/diff`,a)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:r}){let n="/datasets";if(e===void 0)if(r!==void 0)e=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${n}/${e}/openai_ft`)).text()).trim().split(`
|
|
157
|
+
`).map(o=>JSON.parse(o))}async*listDatasets({limit:e=100,offset:r=0,datasetIds:n,datasetName:i,datasetNameContains:s,metadata:a}={}){let o="/datasets",c=new URLSearchParams({limit:e.toString(),offset:r.toString()});if(n!==void 0)for(let l of n)c.append("id",l);i!==void 0&&c.append("name",i),s!==void 0&&c.append("name_contains",s),a!==void 0&&c.append("metadata",JSON.stringify(a));for await(let l of this._getPaginated(o,c))yield*l}async updateDataset(e){let{datasetId:r,datasetName:n,...i}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let s=r??(await this.readDataset({datasetName:n})).id;T(s);let a=JSON.stringify(i);return await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${s}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await S(c,"update dataset"),c})).json()}async updateDatasetTag(e){let{datasetId:r,datasetName:n,asOf:i,tag:s}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let a=r??(await this.readDataset({datasetName:n})).id;T(a);let o=JSON.stringify({as_of:typeof i=="string"?i:i.toISOString(),tag:s});await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${a}/tags`,{method:"PUT",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await S(c,"update dataset tags",!0),c})}async deleteDataset({datasetId:e,datasetName:r}){let n="/datasets",i=e;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(r!==void 0&&(i=(await this.readDataset({datasetName:r})).id),i!==void 0)T(i),n+=`/${i}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{let s=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(s,`delete ${n}`,!0),s})}async createExample(e,r,n){if(nu(e)&&(r!==void 0||n!==void 0))throw new Error("Cannot provide referenceOutputs or options when using ExampleCreate object");let i=r?n?.datasetId:e.dataset_id,s=r?n?.datasetName:e.dataset_name;if(i===void 0&&s===void 0)throw new Error("Must provide either datasetName or datasetId");if(i!==void 0&&s!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");i===void 0&&(i=(await this.readDataset({datasetName:s})).id);let a=(r?n?.createdAt:e.created_at)||new Date,o;nu(e)?o=e:o={inputs:e,reference_outputs:r,created_at:a?.toISOString(),id:n?.exampleId,metadata:n?.metadata,split:n?.split,source_run_id:n?.sourceRunId,use_source_run_io:n?.useSourceRunIO,use_source_run_attachments:n?.useSourceRunAttachments,attachments:n?.attachments};let c=await this._uploadExamplesMultipart(i,[o]);return await this.readExample(c.example_ids?.[0]??st())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let R=e,v=R[0].dataset_id,M=R[0].dataset_name;if(v===void 0&&M===void 0)throw new Error("Must provide either datasetName or datasetId");if(v!==void 0&&M!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");v===void 0&&(v=(await this.readDataset({datasetName:M})).id);let k=await this._uploadExamplesMultipart(v,R);return await Promise.all(k.example_ids.map(L=>this.readExample(L)))}let{inputs:r,referenceOutputs:n,outputs:i,metadata:s,splits:a,sourceRunIds:o,useSourceRunIOs:c,useSourceRunAttachments:l,attachments:u,exampleIds:d,datasetId:f,datasetName:p}=e;if(n!==void 0&&i!==void 0)throw new Error("Cannot specify both referenceOutputs and outputs");if(r===void 0)throw new Error("Must provide inputs when using legacy parameters");let h=f,m=p;if(h===void 0&&m===void 0)throw new Error("Must provide either datasetName or datasetId");if(h!==void 0&&m!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");h===void 0&&(h=(await this.readDataset({datasetName:m})).id);let w=r.map((R,v)=>({dataset_id:h,inputs:R,reference_outputs:(n??i)?.[v],metadata:s?.[v],split:a?.[v],id:d?.[v],attachments:u?.[v],source_run_id:o?.[v],use_source_run_io:c?.[v],use_source_run_attachments:l?.[v]})),E=await this._uploadExamplesMultipart(h,w);return await Promise.all(E.example_ids.map(R=>this.readExample(R)))}async createLLMExample(e,r,n){return this.createExample({input:e},{output:r},n)}async createChatExample(e,r,n){let i=e.map(a=>Bi(a)?Fi(a):a),s=Bi(r)?Fi(r):r;return this.createExample({input:i},{output:s},n)}async readExample(e){T(e);let r=`/examples/${e}`,n=await this._get(r),{attachment_urls:i,...s}=n,a=s;return i&&(a.attachments=Object.entries(i).reduce((o,[c,l])=>(o[c.slice(11)]={presigned_url:new URL(l.presigned_url,this.apiUrl).href,mime_type:l.mime_type},o),{})),a}async*listExamples({datasetId:e,datasetName:r,exampleIds:n,asOf:i,splits:s,inlineS3Urls:a,metadata:o,limit:c,offset:l,filter:u,includeAttachments:d,select:f,excludeDefaultFields:p}={}){let h;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)h=e;else if(r!==void 0)h=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide a datasetName or datasetId");let m=new URLSearchParams({dataset:h}),w=i?typeof i=="string"?i:i?.toISOString():void 0;w&&m.append("as_of",w);let E=a??!0;if(m.append("inline_s3_urls",E.toString()),n!==void 0)for(let v of n)m.append("id",v);if(s!==void 0)for(let v of s)m.append("splits",v);if(o!==void 0){let v=JSON.stringify(o);m.append("metadata",v)}c!==void 0&&m.append("limit",c.toString()),l!==void 0&&m.append("offset",l.toString()),u!==void 0&&m.append("filter",u);let b=new Set(f??[]);if(d===!0)for(let v of["attachment_urls","outputs","metadata"])b.add(v);for(let v of b)m.append("select",v);p===!0&&m.append("exclude_default_fields","true");let R=0;for await(let v of this._getPaginated("/examples",m)){for(let M of v){let{attachment_urls:k,...N}=M,L=N;k&&(L.attachments=Object.entries(k).reduce((G,[j,le])=>(G[j.slice(11)]={presigned_url:new URL(le.presigned_url,this.apiUrl).href,mime_type:le.mime_type||void 0},G),{})),yield L,R++}if(c!==void 0&&R>=c)break}}async deleteExample(e){T(e);let r=`/examples/${e}`;await this.caller.call(async()=>{let n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(n,`delete ${r}`,!0),n})}async deleteExamples(e,r){if(e.forEach(n=>T(n)),r?.hardDelete){let n=this._getPlatformEndpointPath("datasets/examples/delete");await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}${n}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},body:JSON.stringify({example_ids:e,hard_delete:!0}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(i,"hard delete examples",!0),i})}else{let n=new URLSearchParams;e.forEach(i=>n.append("example_ids",i)),await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/examples?${n.toString()}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(i,"delete examples",!0),i})}}async updateExample(e,r){let n;r?n=e:n=e.id,T(n);let i;r?i={id:n,...r}:i=e;let s;return i.dataset_id!==void 0?s=i.dataset_id:s=(await this.readExample(n)).dataset_id,this._updateExamplesMultipart(s,[i])}async updateExamples(e){let r;return e[0].dataset_id===void 0?r=(await this.readExample(e[0].id)).dataset_id:r=e[0].dataset_id,this._updateExamplesMultipart(r,e)}async readDatasetVersion({datasetId:e,datasetName:r,asOf:n,tag:i}){let s;if(e?s=e:s=(await this.readDataset({datasetName:r})).id,T(s),n&&i||!n&&!i)throw new Error("Exactly one of asOf and tag must be specified.");let a=new URLSearchParams;return n!==void 0&&a.append("as_of",typeof n=="string"?n:n.toISOString()),i!==void 0&&a.append("tag",i),await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${s}/version?${a.toString()}`,{method:"GET",headers:{...this._mergedHeaders},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(c,"read dataset version"),c})).json()}async listDatasetSplits({datasetId:e,datasetName:r,asOf:n}){let i;if(e===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?i=(await this.readDataset({datasetName:r})).id:i=e,T(i);let s=new URLSearchParams,a=n?typeof n=="string"?n:n?.toISOString():void 0;return a&&s.append("as_of",a),await this._get(`/datasets/${i}/splits`,s)}async updateDatasetSplits({datasetId:e,datasetName:r,splitName:n,exampleIds:i,remove:s=!1}){let a;if(e===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?a=(await this.readDataset({datasetName:r})).id:a=e,T(a),i.forEach(l=>T(l));let o=`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${a}/examples/metadata`)}`,c=s?"array_remove":"array_add";for(let l=0;l<i.length;l+=eu){let u=JSON.stringify({example_ids:i.slice(l,l+eu),operations:[{key:"dataset_split",operation:c,values:[n]}]});if(await this.caller.call(async()=>{let f=await this._fetch(o,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await Ch(f)?!0:(await S(f,"update dataset splits",!0),!1)})){await this._updateDatasetSplitsLegacy(a,n,i.slice(l),s);return}}}async _updateDatasetSplitsLegacy(e,r,n,i){let s=JSON.stringify({split_name:r,examples:n,remove:i});await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/datasets/${e}/splits`,{method:"PUT",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await S(a,"update dataset splits",!0),a})}async createFeedback(e,r,n){let{runId:i=null,key:s,score:a,value:o,correction:c,comment:l,sourceInfo:u,feedbackSourceType:d="api",sourceRunId:f,feedbackId:p,feedbackConfig:h,projectId:m,traceId:w,comparativeExperimentId:E,sessionId:b,startTime:R,extendTraceRetention:v,address:M}=typeof e=="object"&&e!==null?e:{runId:e,key:r,...n},k=be(M);if(Pt(b??m,k),!i&&!m)throw new Error("One of runId or projectId must be provided");if(i&&m)throw new Error("Only one of runId or projectId can be provided");i&&b===void 0&&!k&&await this._checkFeedbackSessionId();let N={type:d??"api",metadata:u??{}};f!==void 0&&N?.metadata!==void 0&&!N.metadata.__run&&(N.metadata.__run={run_id:f}),N?.metadata!==void 0&&N.metadata.__run?.run_id!==void 0&&T(N.metadata.__run.run_id);let L={id:p??Ut(),run_id:i,trace_id:w,key:s,score:Zl(a),value:o,correction:c,comment:l,feedback_source:N,comparative_experiment_id:E,feedbackConfig:h,session_id:b??m,start_time:R,extend_trace_retention:v},G=w??i;if(G!=null&&!this._shouldSample(G))return L;let j=k?{...L,address:Fe(k)}:L;return i&&w&&v!==!1&&await this._canBatchFeedback()?(this.processRunOperation({action:"feedback",item:{...j,start_time:typeof R=="number"?new Date(R).toISOString():R}}).catch(console.error),L):(await this._postFeedback(j),L)}async _canBatchFeedback(){return!this.autoBatchTracing||this.langSmithToOTELTranslator!==void 0||this._multipartDisabled?!1:(await this._ensureServerInfo())?.batch_ingest_config?.use_multipart_endpoint??!0}async _postFeedback(e,r){let n={...this._mergedHeaders,"Content-Type":"application/json"};r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),this._applyReplicaWorkspace(n,r);let i=JSON.stringify(e);await this.caller.call(async()=>{let s=await this._fetch(`${r?.apiUrl??this.apiUrl}/feedback`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await S(s,"create feedback",!0),s})}async _postFeedbacks(e,r){await Promise.all(e.map(n=>this._postFeedback(n,r)))}async updateFeedback(e,{score:r,value:n,correction:i,comment:s}){let a={};r!==void 0&&(a.score=Zl(r)),n!==void 0&&(a.value=n),i!==void 0&&(a.correction=i),s!==void 0&&(a.comment=s),T(e);let o=JSON.stringify(a);await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await S(c,"update feedback",!0),c})}async readFeedback(e){T(e);let r=`/feedback/${e}`;return await this._get(r)}async deleteFeedback(e){T(e);let r=`/feedback/${e}`;await this.caller.call(async()=>{let n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(n,`delete ${r}`,!0),n})}async*listFeedback({runIds:e,feedbackKeys:r,feedbackSourceTypes:n}={}){let i=new URLSearchParams;if(e)for(let s of e)T(s),i.append("run",s);if(r)for(let s of r)i.append("key",s);if(n)for(let s of n)i.append("source",s);for await(let s of this._getPaginated("/feedback",i))yield*s}async createPresignedFeedbackToken(e,r,{expiration:n,feedbackConfig:i}={}){let s={run_id:e,feedback_key:r,feedback_config:i};n?typeof n=="string"?s.expires_at=n:(n?.hours||n?.minutes||n?.days)&&(s.expires_in=n):s.expires_in={hours:3};let a=JSON.stringify(s);return await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await S(c,"create presigned feedback token"),c})).json()}async createComparativeExperiment({name:e,experimentIds:r,referenceDatasetId:n,createdAt:i,description:s,metadata:a,id:o}){if(r.length===0)throw new Error("At least one experiment is required");if(n||(n=(await this.readProject({projectId:r[0]})).reference_dataset_id),!n==null)throw new Error("A reference dataset is required");let c={id:o,name:e,experiment_ids:r,reference_dataset_id:n,description:s,created_at:(i??new Date)?.toISOString(),extra:{}};a&&(c.extra.metadata=a);let l=JSON.stringify(c);return(await this.caller.call(async()=>{let d=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await S(d,"create comparative experiment"),d})).json()}async*listPresignedFeedbackTokens(e){T(e);let r=new URLSearchParams({run_id:e});for await(let n of this._getPaginated("/feedback/tokens",r))yield*n}_selectEvalResults(e){let r;return"results"in e?r=e.results:Array.isArray(e)?r=e:r=[e],r}async _logEvaluationFeedback(e,r,n,i){let s=this._selectEvalResults(e),a=[];for(let o of s){let c=n||{};o.evaluatorInfo&&(c={...o.evaluatorInfo,...c});let l=null;o.targetRunId?l=o.targetRunId:r&&(l=r.id),a.push(await this.createFeedback(l,o.key,{score:o.score,value:o.value,comment:o.comment,correction:o.correction,sourceInfo:c,sourceRunId:o.sourceRunId,feedbackConfig:o.feedbackConfig,feedbackSourceType:"model",sessionId:r?.session_id??i,startTime:r?.start_time,traceId:l===r?.id?r?.trace_id:void 0}))}return[s,a]}async logEvaluationFeedback(e,r,n,i){if(e!=null&&typeof e=="object"&&"evaluatorResponse"in e){let[a]=await this._logEvaluationFeedback(e.evaluatorResponse,e.run,e.sourceInfo,e.projectId);return a}let[s]=await this._logEvaluationFeedback(e,r,n,i);return s}async createFeedbackConfig(e){let{feedbackKey:r,feedbackConfig:n,isLowerScoreBetter:i,isEnforced:s=!1}=e,a={feedback_key:r,feedback_config:n,is_enforced:s};return i!==void 0&&(a.is_lower_score_better=i),(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(a)});return await S(c,"create feedback config"),c})).json()}async*listFeedbackConfigs(e={}){let{feedbackKeys:r,nameContains:n,limit:i,includeAllConfigs:s,isEnforced:a}=e,o=new URLSearchParams;r&&r.forEach(l=>{o.append("key",l)}),n&&o.append("name_contains",n),s&&o.append("include_all_configs","true"),a!==void 0&&o.append("is_enforced",a.toString()),o.append("limit",(i!==void 0?Math.min(i,100):100).toString());let c=0;for await(let l of this._getPaginated("/feedback-configs",o))if(yield*l,c+=l.length,i!==void 0&&c>=i)break}async updateFeedbackConfig(e,r={}){let{feedbackConfig:n,isLowerScoreBetter:i,configId:s}=r,a={feedback_key:e};return s!==void 0&&(a.id=T(s,"configId")),n!==void 0&&(a.feedback_config=n),i!==void 0&&(a.is_lower_score_better=i),this._patchFeedbackConfig(a)}async addFeedbackCategories(e,r,n={}){let i={feedback_key:e,add_categories:r};return n.configId!==void 0&&(i.id=T(n.configId,"configId")),this._patchFeedbackConfig(i)}async removeFeedbackCategories(e,r,n={}){let i={feedback_key:e,remove_categories:r};return n.configId!==void 0&&(i.id=T(n.configId,"configId")),this._patchFeedbackConfig(i)}async _patchFeedbackConfig(e){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(e)});return await S(n,"update feedback config"),n})).json()}async deleteFeedbackConfig(e,r={}){let{configId:n}=r;if(e===void 0==(n===void 0))throw new Error("Pass exactly one of feedbackKey or configId.");let i=new URLSearchParams(n!==void 0?{id:T(n,"configId")}:{feedback_key:e});await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/feedback-configs?${i}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(s,"delete feedback config",!0),s})}async*listAnnotationQueues(e={}){let{queueIds:r,name:n,nameContains:i,limit:s}=e,a=new URLSearchParams;r&&r.forEach((c,l)=>{T(c,`queueIds[${l}]`),a.append("ids",c)}),n&&a.append("name",n),i&&a.append("name_contains",i),a.append("limit",(s!==void 0?Math.min(s,100):100).toString());let o=0;for await(let c of this._getPaginated("/annotation-queues",a))if(yield*c,o++,s!==void 0&&o>=s)break}async createAnnotationQueue(e){let{name:r,description:n,queueId:i,rubricInstructions:s,rubricItems:a}=e,o={name:r,description:n,id:i||st(),rubric_instructions:s,rubric_items:a},c=JSON.stringify(Object.fromEntries(Object.entries(o).filter(([u,d])=>d!==void 0)));return(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await S(u,"create annotation queue"),u})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${T(e,"queueId")}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(n,"read annotation queue"),n})).json()}async updateAnnotationQueue(e,r){let{name:n,description:i,rubricInstructions:s,rubricItems:a}=r,o={};n!==void 0&&(o.name=n),i!==void 0&&(o.description=i),s!==void 0&&(o.rubric_instructions=s),a!==void 0&&(o.rubric_items=a);let c=JSON.stringify(o);await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/annotation-queues/${T(e,"queueId")}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await S(l,"update annotation queue",!0),l})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/annotation-queues/${T(e,"queueId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(r,"delete annotation queue",!0),r})}async addRunsToAnnotationQueue(e,r){let n=`${this.apiUrl}/annotation-queues/${T(e,"queueId")}/runs`,i=r.every(o=>typeof o=="string"),s,a;i?(K("Passing run IDs as strings to addRunsToAnnotationQueue() is deprecated and will be removed after Jan 31, 2027. Use RunKey[] instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration-feedback#annotation-queues-add-runs for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_ADD_RUNS_STRING_IDS"}),s=n,a=JSON.stringify(r.map((o,c)=>T(o,`runs[${c}]`).toString()))):(s=`${n}/by-key`,a=JSON.stringify(r.map((o,c)=>{let l={run_id:T(o.runId,`runs[${c}].runId`).toString(),session_id:T(o.sessionId,`runs[${c}].sessionId`).toString(),start_time:typeof o.startTime=="string"?o.startTime:new Date(o.startTime).toISOString()};return o.sourceProposedExampleId!=null&&(l.source_proposed_example_id=T(o.sourceProposedExampleId,`runs[${c}].sourceProposedExampleId`).toString()),l}))),await this.caller.call(async()=>{let o=await this._fetch(s,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await S(o,"add runs to annotation queue",!0),o})}async getRunFromAnnotationQueue(e,r){let n=`/annotation-queues/${T(e,"queueId")}/run`,s=await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${n}/${r}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(a,"get run from annotation queue"),a})).json();return lr(s)}async*listRunsFromAnnotationQueue(e,r={}){let{status:n,limit:i}=r,s=new URLSearchParams,a=i!==void 0&&Number.isFinite(i)?Math.min(i,100):100;n&&s.append("status",n),s.append("limit",a.toString());let o=0,c=`/annotation-queues/${T(e,"queueId")}/runs`;for await(let l of this._getPaginated(c,s))for(let u of l)if(yield lr(u),o++,o>=a)return}async deleteRunFromAnnotationQueue(e,r){await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${T(e,"queueId")}/runs/${T(r,"queueRunId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(n,"delete run from annotation queue",!0),n})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${T(e,"queueId")}/size`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(n,"get size from annotation queue"),n})).json()}async _currentTenantIsOwner(e){let r=await this._getSettings();return e=="-"||r.tenant_handle===e}async _ownerConflictError(e,r){let n=await this._getSettings();return new Error(`Cannot ${e} for another tenant.
|
|
158
|
+
|
|
159
|
+
Current tenant: ${n.tenant_handle}
|
|
160
|
+
|
|
161
|
+
Requested tenant: ${r}`)}async _getLatestCommitHash(e){let n=await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(i,"get latest commit hash"),i})).json();if(n.commits.length!==0)return n.commits[0].commit_hash}async _createCommitTags(e,r,n){let i=typeof n=="string"?[n]:n;await Promise.all(i.map(async s=>this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/repos/${e}/tags`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify({tag_name:s,commit_id:r})});return await S(a,"create commit tag"),a})))}async _likeOrUnlikePrompt(e,r){let[n,i,s]=ie(e),a=JSON.stringify({like:r});return(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/likes/${n}/${i}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await S(c,`${r?"like":"unlike"} prompt`),c})).json()}async _getPromptUrl(e){let[r,n,i]=ie(e);if(await this._currentTenantIsOwner(r)){let s=await this._getSettings();return i!=="latest"?`${this.getHostUrl()}/prompts/${n}/${i.substring(0,8)}?organizationId=${s.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${s.id}`}else return i!=="latest"?`${this.getHostUrl()}/hub/${r}/${n}/${i.substring(0,8)}`:`${this.getHostUrl()}/hub/${r}/${n}`}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){let[r,n,i]=ie(e);for await(let s of this._getPaginated(`/commits/${r}/${n}/`,new URLSearchParams,a=>a.commits))yield*s}async*listPrompts(e){let r=new URLSearchParams;r.append("sort_field",e?.sortField??"updated_at"),r.append("sort_direction","desc"),r.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&r.append("is_public",e.isPublic.toString()),e?.query&&r.append("query",e.query);for await(let n of this._getPaginated("/repos",r,i=>i.repos))yield*n}async getPrompt(e){let[r,n,i]=ie(e),a=await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return o?.status===404?null:(await S(o,"get prompt"),o)}))?.json();return a?.repo?a.repo:null}async createPrompt(e,r){let n=await this._getSettings();if(r?.isPublic&&!n.tenant_handle)throw new Error(`Cannot create a public prompt without first
|
|
162
|
+
|
|
163
|
+
creating a LangChain Hub handle.
|
|
164
|
+
You can add a handle by creating a public prompt at:
|
|
165
|
+
|
|
166
|
+
https://smith.langchain.com/prompts`);let[i,s,a]=ie(e);if(!await this._currentTenantIsOwner(i))throw await this._ownerConflictError("create a prompt",i);let o={repo_handle:s,...r?.description&&{description:r.description},...r?.readme&&{readme:r.readme},...r?.tags&&{tags:r.tags},is_public:!!r?.isPublic},c=JSON.stringify(o),l=await this.caller.call(async()=>{let d=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await S(d,"create prompt"),d}),{repo:u}=await l.json();return u}async createCommit(e,r,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[i,s,a]=ie(e),o=n?.parentCommitHash==="latest"||!n?.parentCommitHash?await this._getLatestCommitHash(`${i}/${s}`):n?.parentCommitHash,c={manifest:JSON.parse(JSON.stringify(r)),parent_commit:o,...n?.description!==void 0&&{description:n.description}},l=JSON.stringify(c),d=await(await this.caller.call(async()=>{let p=await this._fetch(`${this.apiUrl}/commits/${i}/${s}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await S(p,"create commit"),p})).json(),f=d.commit??d;return n?.tags&&await this._createCommitTags(`${i}/${s}`,f.id,n.tags),this._getPromptUrl(`${i}/${s}${f.commit_hash?`:${f.commit_hash}`:""}`)}async updateExamplesMultipart(e,r=[]){return this._updateExamplesMultipart(e,r)}async _updateExamplesMultipart(e,r=[]){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.");let n=new FormData;for(let a of r){let o=a.id,c={...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split}},l=se(c,`Serializing body for example with id: ${o}`),u=new Blob([l],{type:"application/json"});if(n.append(o,u),a.inputs){let d=se(a.inputs,`Serializing inputs for example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.inputs`,f)}if(a.outputs){let d=se(a.outputs,`Serializing outputs whle updating example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.outputs`,f)}if(a.attachments)for(let[d,f]of Object.entries(a.attachments)){let p,h;Array.isArray(f)?[p,h]=f:(p=f.mimeType,h=f.data);let m=new Blob([h],{type:`${p}; length=${h.byteLength}`});n.append(`${o}.attachment.${d}`,m)}if(a.attachments_operations){let d=se(a.attachments_operations,`Serializing attachments while updating example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.attachments_operations`,f)}}let i=e??r[0]?.dataset_id;return(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${i}/examples`)}`,{method:"PATCH",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await S(a,"update examples"),a})).json()}async uploadExamplesMultipart(e,r=[]){return this._uploadExamplesMultipart(e,r)}async _uploadExamplesMultipart(e,r=[]){for(let s of r)iu(s);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.");let n=new FormData;for(let s of r){let a=(s.id??st()).toString(),o={created_at:s.created_at,...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split},...s.source_run_id&&{source_run_id:s.source_run_id},...s.use_source_run_io&&{use_source_run_io:s.use_source_run_io},...s.use_source_run_attachments&&{use_source_run_attachments:s.use_source_run_attachments}},c=se(o,`Serializing body for uploaded example with id: ${a}`),l=new Blob([c],{type:"application/json"});if(n.append(a,l),s.inputs){let d=se(s.inputs,`Serializing inputs for uploaded example with id: ${a}`),f=new Blob([d],{type:"application/json"});n.append(`${a}.inputs`,f)}let u=iu(s);if(u!==void 0){let d=se(u,`Serializing outputs for uploaded example with id: ${a}`),f=new Blob([d],{type:"application/json"});n.append(`${a}.outputs`,f)}if(s.attachments)for(let[d,f]of Object.entries(s.attachments)){let p,h;Array.isArray(f)?[p,h]=f:(p=f.mimeType,h=f.data);let m=new Blob([h],{type:`${p}; length=${h.byteLength}`});n.append(`${a}.attachment.${d}`,m)}}return(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await S(s,"upload examples"),s})).json()}async updatePrompt(e,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[n,i]=ie(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);let s={};if(r?.description!==void 0&&(s.description=r.description),r?.readme!==void 0&&(s.readme=r.readme),r?.tags!==void 0&&(s.tags=r.tags),r?.isPublic!==void 0&&(s.is_public=r.isPublic),r?.isArchived!==void 0&&(s.is_archived=r.isArchived),Object.keys(s).length===0)throw new Error("No valid update options provided");let a=JSON.stringify(s);return(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/repos/${n}/${i}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await S(c,"update prompt"),c})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[r,n,i]=ie(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("delete a prompt",r);await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(s,"delete prompt",!0),s})}_getPromptCacheKey(e,r){return`${e}${r?":with_model":""}`}async _fetchPromptFromApi(e,r){let[n,i,s]=ie(e),o=await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/commits/${n}/${i}/${s}${r?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(c,"pull prompt commit"),c})).json();return{owner:n,repo:i,commit_hash:o.commit_hash,manifest:o.manifest,examples:o.examples,hub_model_config:o.model_config,hub_model_provider:o.model_provider}}async pullPromptCommit(e,r){xh(e,r?.dangerouslyPullPublicPrompt);let n=this._fetchPromptFromApi.bind(this,e,r);if(!r?.skipCache&&this._promptCache){let i=this._getPromptCacheKey(e,r?.includeModel),s=this._promptCache.get(i,n);if(s)return s;let a=await n();return this._promptCache.set(i,a,n),a}return this._fetchPromptFromApi(e,r)}async _pullPrompt(e,r){let n=await this.pullPromptCommit(e,{includeModel:r?.includeModel,skipCache:r?.skipCache,dangerouslyPullPublicPrompt:r?.dangerouslyPullPublicPrompt});return JSON.stringify(n.manifest)}async pushPrompt(e,r){return await this.promptExists(e)?r&&["description","readme","tags","isPublic"].some(i=>r[i]!==void 0)&&await this.updatePrompt(e,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}):await this.createPrompt(e,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}),r?.object?await this.createCommit(e,r?.object,{parentCommitHash:r?.parentCommitHash,tags:r?.commitTags,description:r?.commitDescription}):await this._getPromptUrl(e)}async agentExists(e){let[r,n]=ie(e);return this._repoExists(r,n)}async skillExists(e){let[r,n]=ie(e);return this._repoExists(r,n)}async pullAgent(e,r){return await this._pullDirectory(e,"agent",r?.version)}async pullSkill(e,r){return await this._pullDirectory(e,"skill",r?.version)}async pushAgent(e,r){return this._pushDirectory(e,"agent",r)}async pushSkill(e,r){return this._pushDirectory(e,"skill",r)}async deleteAgent(e){return this._deleteDirectory(e)}async deleteSkill(e){return this._deleteDirectory(e)}async*listAgents(e){yield*this._listReposByType("agent",e)}async*listSkills(e){yield*this._listReposByType("skill",e)}async*_listReposByType(e,r){let n=new URLSearchParams;n.append("repo_type",e),n.append("is_archived",(!!r?.isArchived).toString()),r?.isPublic!==void 0&&n.append("is_public",r.isPublic.toString()),r?.query&&n.append("query",r.query);for await(let i of this._getPaginated("/repos",n,s=>s.repos))yield*i}async _pullDirectory(e,r,n){let[i,s,a]=ie(e),o=n??(a!=="latest"?a:void 0),c=new URL(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${i}/${s}/directories`)}`);return c.searchParams.set("repo_type",r),o&&c.searchParams.set("commit",o),await(await this.caller.call(async()=>{let u=await this._fetch(c.toString(),{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(u,"pull directory"),u})).json()}async _pushDirectory(e,r,n){if(n.parentCommit!==void 0&&(n.parentCommit.length<8||n.parentCommit.length>64))throw new Error("parent_commit must be 8-64 characters");let[i,s]=ie(e);if(!await this._currentTenantIsOwner(i))throw await this._ownerConflictError(`push ${r}`,i);if(await this._repoExists(i,s))(n.description!==void 0||n.readme!==void 0||n.tags!==void 0||n.isPublic!==void 0)&&await this._updateRepoMetadata(i,s,n);else{let f=/^[a-z][a-z0-9-_]*$/;if(!f.test(s))throw new Error(`Invalid repo_handle ${JSON.stringify(s)}: must match ${f}`);await this._createRepo(s,r,n)}let a={files:n.files};n.parentCommit&&(a.parent_commit=n.parentCommit);let l=(await(await this.caller.call(async()=>{let f=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${i}/${s}/directories/commits`)}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(a)});return await S(f,`push ${r}`),f})).json()).commit.commit_hash,u=await this._getSettings(),d=new URLSearchParams({organizationId:u.id});return`${this.getHostUrl()}/context/${s}/${l.slice(0,8)}?${d.toString()}`}async _deleteDirectory(e){let[r,n]=ie(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("delete",r);await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${r}/${n}/directories`)}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(i,"delete directory"),i})}async _repoExists(e,r){try{return await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/repos/${e}/${r}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await S(n,"check repo exists"),n}),!0}catch(n){if(Pr(n))return!1;throw n}}async _createRepo(e,r,n){let i={repo_handle:e,repo_type:r,is_public:!!n.isPublic};n.description!==void 0&&(i.description=n.description),n.readme!==void 0&&(i.readme=n.readme),n.tags!==void 0&&(i.tags=n.tags);try{await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await S(s,`create ${r}`),s})}catch(s){if(Il(s))return;throw s}}async _updateRepoMetadata(e,r,n){let i={};n.description!==void 0&&(i.description=n.description),n.readme!==void 0&&(i.readme=n.readme),n.tags!==void 0&&(i.tags=n.tags),n.isPublic!==void 0&&(i.is_public=n.isPublic),Object.keys(i).length!==0&&await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/repos/${e}/${r}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await S(s,"update repo metadata"),s})}async clonePublicDataset(e,r={}){let{sourceApiUrl:n=this.apiUrl,datasetName:i}=r,[s,a]=this.parseTokenOrUrl(e,n),o=new t({apiUrl:s,apiKey:"placeholder"}),c=await o.readSharedDataset(a),l=i||c.name;try{if(await this.hasDataset({datasetId:l})){console.log(`Dataset ${l} already exists in your tenant. Skipping.`);return}}catch{}let u=await o.listSharedExamples(a),d=await this.createDataset(l,{description:c.description,dataType:c.data_type||"kv",inputsSchema:c.inputs_schema_definition??void 0,outputsSchema:c.outputs_schema_definition??void 0});try{await this.createExamples({inputs:u.map(f=>f.inputs),outputs:u.flatMap(f=>f.outputs?[f.outputs]:[]),datasetId:d.id})}catch(f){throw console.error(`An error occurred while creating dataset ${l}. You should delete it manually.`),f}}parseTokenOrUrl(e,r,n=2,i="dataset"){try{return T(e),[r,e]}catch{}try{let a=new URL(e).pathname.split("/").filter(o=>o!=="");if(a.length>=n){let o=a[a.length-n];return[r,o]}else throw new Error(`Invalid public ${i} URL: ${e}`)}catch{throw new Error(`Invalid public ${i} URL or token: ${e}`)}}cleanup(){this._promptCache&&this._promptCache.stop()}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();for(await new Promise(e=>setTimeout(e,1));this._pendingDrains.size>0;)await Promise.all([...this._pendingDrains]);for(let e=0;e<2;e++)for(clearTimeout(this._compressedFlushTimeout),this._compressedFlushTimeout=void 0,await this._flushCompressedBuffers();this._pendingDrains.size>0;)await Promise.all([...this._pendingDrains]);await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await mc()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}toString(){let e=[`apiUrl=${JSON.stringify(this.apiUrl)}`];return this.webUrl!==void 0&&e.push(`webUrl=${JSON.stringify(this.webUrl)}`),this.workspaceId!==void 0&&e.push(`workspaceId=${JSON.stringify(this.workspaceId)}`),`[LangSmithClient ${e.join(" ")}]`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}};Object.defineProperty(Ye,"_fallbackDirsCreated",{enumerable:!0,configurable:!0,writable:!0,value:new Set});function nu(t){return"dataset_id"in t||"dataset_name"in t}function iu(t){if(t.reference_outputs!==void 0&&t.outputs!==void 0)throw new Error("Cannot specify both reference_outputs and outputs");return t.reference_outputs??t.outputs}var Hn=t=>t!==void 0?t:!!["TRACING_V2","TRACING"].find(r=>$(r)==="true");var Cs=class{getStore(){}run(e,r){return r()}},Rs=Symbol.for("ls:tracing_async_local_storage"),kh=new Cs,Os=class{getInstance(){return globalThis[Rs]??kh}initializeGlobalInstance(e){globalThis[Rs]===void 0&&(globalThis[Rs]=e)}},Nh=new Os;function ks(t=!1){let e=Nh.getInstance().getStore();if(!t&&e===void 0)throw new Error(`Could not get the current run tree.
|
|
167
|
+
|
|
168
|
+
Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}function A0(t){return typeof t=="function"&&"langsmith:traceable"in t}var Ne,Lh=()=>typeof window<"u"&&typeof window.document<"u",Mh=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",$h=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),cu=()=>typeof globalThis.Deno<"u",jh=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!cu(),Cr=()=>Ne||(typeof Bun<"u"?Ne="bun":Lh()?Ne="browser":jh()?Ne="node":Mh()?Ne="webworker":$h()?Ne="jsdom":cu()?Ne="deno":Ne="other",Ne),Ns;function Dn(){if(Ns===void 0){let t=Cr(),e=Hh();Ns={library:"langsmith",runtime:t,sdk:"langsmith-js",sdk_version:de,...e}}return Ns}var Uh=["key","secret","token","password","passwd","pwd","credential","email"];function lu(t){let e=t.toLowerCase();return Uh.some(r=>e.includes(r))}function Ts(){let t=Dh(),e={},r=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_CONFIG_FILE","LANGSMITH_PROJECT","LANGSMITH_SESSION","LANGSMITH_AGENT_ID","LANGSMITH_AGENT_ENVIRONMENT"];for(let[i,s]of Object.entries(t))typeof s=="string"&&!r.includes(i)&&!lu(i)&&i!=="LANGSMITH_REVISION_ID"&&i!=="LANGCHAIN_REVISION_ID"&&(e[i]=s);let n=t.LANGSMITH_REVISION_ID||t.LANGCHAIN_REVISION_ID;return n&&(e.revision_id=n),e}function Dh(){let t={};try{if(typeof process<"u"&&process.env)for(let[e,r]of Object.entries(process.env))(e.startsWith("LANGCHAIN_")||e.startsWith("LANGSMITH_"))&&r!=null&&(lu(e)&&typeof r=="string"?t[e]=r.slice(0,2)+"*".repeat(r.length-4)+r.slice(-2):t[e]=r)}catch{}return t}function V(t){try{return typeof process<"u"?process.env?.[t]:void 0}catch{return}}function $(t){return V(`LANGSMITH_${t}`)||V(`LANGCHAIN_${t}`)}var Ls;function Hh(){if(Ls!==void 0)return Ls;let t=["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(let r of t){let n=V(r);n!==void 0&&(e[r]=n)}return Ls=e,e}function au(){return V("OTEL_ENABLED")==="true"||$("OTEL_ENABLED")==="true"}var ou=new Set(["langsmith","otel"]);function Yr(t){if(t!==void 0)return t;let e=$("TRACING_MODE");if(e!==void 0&&e!==""){let r=e.toLowerCase();if(!ou.has(r))throw new Error(`Invalid LANGSMITH_TRACING_MODE=${JSON.stringify(e)}. Must be one of: ${[...ou].sort().join(", ")}`);return au()&&console.warn("Both LANGSMITH_TRACING_MODE and the legacy OTEL_ENABLED / LANGSMITH_OTEL_ENABLED env vars are set. LANGSMITH_TRACING_MODE takes precedence."),r}return au()?"otel":"langsmith"}var Bh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Fh=/^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$/,uu=["local","development","staging","production"],Gh=/^lrn:agents\/([^/]+)\/environments\/([^/]+)$/,Ms=["LANGSMITH_AGENT_ID","LANGSMITH_AGENT_ENVIRONMENT"],ke=class extends Error{constructor(e){super(e),this.name="EnvAddressError"}};function Ps(t){if(t==null)return;if(typeof t!="object")throw new Error("address must be an AgentAddress, ExperimentAddress or EvaluatorAddress object.");let{kind:e,id:r,environment:n}=t;if(e==="EVALUATOR")return{kind:e};if(e==="EXPERIMENT"){if(typeof r!="string"||!Bh.test(r))throw new Error(`Experiment id must be a UUID, got ${JSON.stringify(r)}.`);return{kind:e,id:r.toLowerCase()}}if(e!=="AGENT")throw new Error("address must be an AgentAddress, ExperimentAddress or EvaluatorAddress object.");if(typeof r!="string"||!Fh.test(r))throw new Error(`Address agent id must be 1 to 63 lowercase ASCII letters, digits, or hyphens, start with a letter, and end with a letter or digit, got ${JSON.stringify(r)}. Use an id such as "support-agent".`);let i=typeof n=="string"?n.toLowerCase():void 0;if(i===void 0||!uu.includes(i))throw new Error(`Address environment must be one of ${uu.join(", ")}, got ${JSON.stringify(n)}.`);return{kind:e,id:r,environment:i.toUpperCase()}}function be(t){let e=Ps(t);if(e&&e.kind!=="AGENT")throw new Error(`Only an AgentAddress can receive traces, got ${e.kind}.`);return e}function Fe(t){return`lrn:agents/${t.id}/environments/${t.environment.toLowerCase()}`}function Pn(t){let e=typeof t=="string"?Gh.exec(t):null;if(!e)throw new Error("Not an agent address.");return be({kind:"AGENT",id:e[1],environment:e[2]})}function hs(){let t=Ms.map(e=>V(e));if(t.some(Boolean))try{let e=Ms.filter((r,n)=>!t[n]);if(e.length)throw new Error(`An address needs ${e.join(" and ")} as well.`);return be({kind:"AGENT",id:t[0],environment:t[1]})}catch(e){throw new ke(`The LANGSMITH_AGENT_* env vars can't address a run: ${e.message}`)}}function Sl(){return Ms}var Le=Symbol.for("lc:context_variables");var Bn=Symbol.for("langsmith:replica_trace_roots");function $s(t,e){if(Le in t)return t[Le][e]}function du(t,e,r){let n=Le in t?t[Le]:{};n[e]=r,t[Le]=n}var kr=36,zh="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function fu(t){let r=Object.keys(t).sort().map(n=>`${n}:${t[n]??""}`).join("|");return _i(r,zh)}function qh(t){return t.replace(/[-:.]/g,"")}function mu(t,e=1){let r=e.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(t).toISOString().slice(0,-1)}${r}Z`}function js(t,e,r=1){let n=mu(t,r);return{dottedOrder:qh(n)+e,microsecondPrecisionDatestring:n}}var Kh=new Set(["projectName","primary","updates","reroot","address"]);function pu(t){try{return Pn(t)}catch{console.warn("Ignoring an unusable address in a `baggage` header.");return}}function Vh(t){let e={};for(let r of Object.keys(t))r==="primary"&&typeof t[r]!="boolean"||Kh.has(r)&&(e[r]=t[r]);return e}var Fn=class t{constructor(e,r,n,i,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}),Object.defineProperty(this,"address",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=r,this.project_name=n,this.replicas=i,this.address=s}static fromHeader(e){let r=e.split(","),n={},i=[],s,a,o;for(let c of r){let[l,u]=c.split("="),d=decodeURIComponent(u);l==="langsmith-metadata"?n=JSON.parse(d):l==="langsmith-tags"?i=d.split(","):l==="langsmith-project"?s=d:l==="langsmith-address"?o=pu(d):l==="langsmith-replicas"&&(a=JSON.parse(d).flatMap(p=>{if(Array.isArray(p))return[p];let h=Vh(p),m=h.address;if(delete h.address,h.projectName||m==null)return[h];let w=pu(m);return w?[{...h,address:w}]:[]}))}return new t(n,i,s,a,o)}toHeader(){let 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)}`),this.address&&e.push(`langsmith-address=${encodeURIComponent(Fe(this.address))}`),e.join(",")}};function Wh(){let t=$("EXCLUDE_INPUTS_ON_PATCH");return t===void 0||t.toLowerCase()==="true"||t==="1"}var Ae=class t{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,"address",{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,"distributedParentId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_postedAttachmentNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_awaitInputsOnPost",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),_u(e)){Object.assign(this,{...e});return}let r=t.getDefaultConfig(),{metadata:n,...i}=e,s=i.client??t.getSharedClient(),a={...n,...i?.extra?.metadata};if(i.extra={...i.extra,metadata:a},"id"in i&&i.id==null&&delete i.id,Object.assign(this,{...r,...i,client:s}),this._resolveAddressing(i),this.execution_order??(this.execution_order=1),this.child_execution_order??(this.child_execution_order=1),this.dotted_order||(this._serialized_start_time=mu(this.start_time,this.execution_order)),this.id||(this.id=In(this._serialized_start_time??this.start_time)),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=Yh(this.replicas),!this.dotted_order){let{dottedOrder:o}=js(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+o:this.dotted_order=o}}_resolveAddressing(e){let r=be(e.address),n=e.project_name||void 0;if(Pt(n,r),n||r){this.project_name=n,this.address=r;return}try{[this.project_name,this.address]=Ir()}catch(i){if(!(i instanceof ke))throw i;Hn(this.tracingEnabled)&&Tn(i),this.project_name=void 0,this.address=void 0,this.tracingEnabled=!1}}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){let e=Date.now();return{run_type:"chain",child_runs:[],api_url:V("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:V("LANGCHAIN_API_KEY"),caller_options:{},start_time:e,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return t.sharedClient||(t.sharedClient=new Ye),t.sharedClient}createChild(e){let r=this.child_execution_order+1,n=this.replicas?.map(f=>{let{reroot:p,...h}=f;return h}),i=e.replicas??n,s=new t({...e,parent_run:this,project_name:this.project_name,address:this.address,replicas:i,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:r,child_execution_order:r}),a=this.extra?.metadata??{},o=s.extra?.metadata??{};Object.keys(a).length>0&&(s.extra={...s.extra,metadata:{...a,...o}}),Le in this&&(s[Le]=this[Le]);let c=Symbol.for("lc:child_config"),l=e.extra?.[c]??this.extra[c];if(Xh(l)){let f={...l},p=Jh(f.callbacks)?f.callbacks.copy?.():void 0;p&&(Object.assign(p,{_parentRunId:s.id}),p.handlers?.find(gu)?.updateFromRunTree?.(s),f.callbacks=p),s.extra[c]=f}let u=new Set,d=this;for(;d!=null&&!u.has(d.id);)u.add(d.id),d.child_execution_order=Math.max(d.child_execution_order,r),d=d.parent_run;return this.child_runs.push(s),s}async end(e,r,n=Date.now(),i){this.outputs=this.outputs??e,this.error=this.error??r,this.end_time=this.end_time??n,i&&Object.keys(i).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...i}}:{metadata:i})}_convertToCreate(e,r,n=!0){let i=e.extra??{};if(i?.runtime?.library===void 0&&(i.runtime||(i.runtime={}),r))for(let[o,c]of Object.entries(r))i.runtime[o]||(i.runtime[o]=c);let s=e.parent_run?.id??e.parent_run_id,a;return n?a=[]:a=e.child_runs.map(o=>this._convertToCreate(o,r,n)),{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:i,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,address:e.address,child_runs:a,parent_run_id:s,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments?{...e.attachments}:void 0,events:e.events}}_sliceParentId(e,r){if(r.dotted_order){let n=r.dotted_order.split("."),i=null;for(let s=0;s<n.length;s++)if(n[s].slice(-kr)===e){i=s;break}if(i!==null){let s=n.slice(i+1);r.dotted_order=s.join("."),s.length>0?r.trace_id=s[0].slice(-kr):r.trace_id=r.id}}r.parent_run_id===e&&(r.parent_run_id=void 0)}_setReplicaTraceRoot(e,r){let n=$s(this,Bn)??{};n[e]=r,du(this,Bn,n);for(let i of this.child_runs)i._setReplicaTraceRoot(e,r)}_replicaAddressing(e){let r=be(e.address);return e.projectName!=null?(Pt(e.projectName,r),[e.projectName,void 0]):r?[void 0,r]:[this.project_name,this.address]}_remapForProject(e){let{projectName:r,address:n,primary:i,runtimeEnv:s,excludeChildRuns:a=!0,reroot:o=!1,distributedParentId:c,apiUrl:l,apiKey:u,workspaceId:d}=e,f=this._convertToCreate(this,s,a);if(i===void 0&&!this.replicas?.some(v=>v.primary===!0)&&r===this.project_name&&(n?Fe(n):void 0)===(this.address?Fe(this.address):void 0))return{...f,session_name:r,address:n};let p=r??(n?Fe(n):void 0)??"agent//";if(o){if(c)this._sliceParentId(c,f);else if(f.parent_run_id=void 0,f.dotted_order){let M=f.dotted_order.split(".");M.length>0&&(f.dotted_order=M[M.length-1],f.trace_id=f.id)}let v=fu({projectName:p,apiUrl:l,apiKey:u,workspaceId:d});this._setReplicaTraceRoot(v,f.id)}let h;if(!o){let v=$s(this,Bn)??{},M=fu({projectName:p,apiUrl:l,apiKey:u,workspaceId:d});if(h=v[M],h&&(f.trace_id=h,f.dotted_order)){let k=f.dotted_order.split("."),N=null;for(let L=0;L<k.length;L++)if(k[L].slice(-kr)===h){N=L;break}if(N!==null){let L=k.slice(N);f.dotted_order=L.join(".")}}}if(i)return{...f,session_name:r,address:n};let m=f.id,w=sr(m,p),E;f.trace_id?E=sr(f.trace_id,p):E=w;let b;f.parent_run_id&&(b=sr(f.parent_run_id,p));let R;return f.dotted_order&&(R=f.dotted_order.split(".").map(k=>{let N=k.slice(-kr),L=sr(N,p);return k.slice(0,-kr)+L}).join(".")),{...f,id:w,trace_id:E,parent_run_id:b,dotted_order:R,session_name:r,address:n}}async postRun(e=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{let r=Dn(),n=new Set(Object.keys(this.attachments??{}));if(this.replicas&&this.replicas.length>0)for(let i of this.replicas){let{primary:s,apiKey:a,apiUrl:o,workspaceId:c,reroot:l,client:u}=i,[d,f]=this._replicaAddressing(i),p=this._remapForProject({projectName:d,address:f,primary:s,runtimeEnv:r,excludeChildRuns:!0,reroot:l,distributedParentId:this.distributedParentId,apiUrl:o,apiKey:a,workspaceId:c});await(u??this.client).createRun(p,{apiKey:a,apiUrl:o,workspaceId:c})}else{let i=this._convertToCreate(this,r,e);await this.client.createRun(i)}if(this._postedAttachmentNames=n,!e){K("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(let i of this.child_runs)await i.postRun(!1)}this.child_runs=[]}catch(r){console.error(`Error in postRun for run ${this.id}:`,r)}}_attachmentsToPatch(){let e=this._postedAttachmentNames,r=Object.entries(this.attachments??{}).filter(([n])=>!e?.has(n));return r.length>0?Object.fromEntries(r):void 0}async patchRun(e){let r=e?.excludeInputs??Wh(),n=this._attachmentsToPatch();if(this.replicas&&this.replicas.length>0)for(let i of this.replicas){let{primary:s,apiKey:a,apiUrl:o,workspaceId:c,updates:l,reroot:u,client:d}=i,[f,p]=this._replicaAddressing(i),h=this._remapForProject({projectName:f,address:p,primary:s,runtimeEnv:void 0,excludeChildRuns:!0,reroot:u,distributedParentId:this.distributedParentId,apiUrl:o,apiKey:a,workspaceId:c}),m={id:h.id,name:h.name,run_type:h.run_type,start_time:h.start_time,outputs:h.outputs,error:h.error,parent_run_id:h.parent_run_id,session_name:h.session_name,address:h.address,reference_example_id:h.reference_example_id,end_time:h.end_time,dotted_order:h.dotted_order,trace_id:h.trace_id,events:h.events,tags:h.tags,extra:h.extra,attachments:n,...l};r||(m.inputs=h.inputs),await(d??this.client).updateRun(h.id,m,{apiKey:a,apiUrl:o,workspaceId:c})}else try{let i={name:this.name,run_type:this.run_type,start_time:this._serialized_start_time??this.start_time,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:n,session_name:this.project_name,address:this.address};r||(i.inputs=this.inputs),await this.client.updateRun(this.id,i)}catch(i){console.error(`Error in patchRun for run ${this.id}`,i)}this.child_runs=[]}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,r){let n=e?.callbacks,i,s,a,o=Hn();if(n){let l=n?.getParentRunId?.()??"",u=n?.handlers?.find(d=>d?.name=="langchain_tracer");i=u?.getRun?.(l),s=u?.projectName,a=u?.client,o=o||!!u}return i?new t({name:i.name,id:i.id,trace_id:i.trace_id,dotted_order:i.dotted_order,client:a,tracingEnabled:o,project_name:s,tags:[...new Set((i?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...i?.extra?.metadata,...e?.metadata}}}).createChild(r):new t({...r,client:a,tracingEnabled:o,project_name:r.address?void 0:s})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,r){let n="get"in e&&typeof e.get=="function"?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,i=n["langsmith-trace"];if(!i||typeof i!="string")return;let s=i.trim(),a=s.split(".").map(u=>{let[d,f]=u.split("Z");return{strTime:d,time:Date.parse(d+"Z"),uuid:f}}),o=a[0].uuid,c={...r,name:r?.name??"parent",run_type:r?.run_type??"chain",start_time:r?.start_time??Date.now(),id:a.at(-1)?.uuid,trace_id:o,dotted_order:s};if(n.baggage&&typeof n.baggage=="string"){let u=Fn.fromHeader(n.baggage);if(c.metadata=u.metadata,c.tags=u.tags,u.project_name&&u.address){console.warn("Ignoring a `baggage` header that names both a project and an address.");return}u.project_name?(c.project_name=u.project_name,delete c.address):u.address&&(c.address=u.address,delete c.project_name),c.replicas=u.replicas}let l=new t(c);return l.distributedParentId=l.id,l}toHeaders(e){let r={"langsmith-trace":this.dotted_order,baggage:new Fn(this.extra?.metadata,this.tags,this.project_name,this.replicas,this.address).toHeader()};if(e)for(let[n,i]of Object.entries(r))e.set(n,i);return r}};Object.defineProperty(Ae,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function _u(t){return t!=null&&typeof t.createChild=="function"&&typeof t.postRun=="function"}function gu(t){return typeof t=="object"&&t!=null&&typeof t.name=="string"&&t.name==="langchain_tracer"}function hu(t){return Array.isArray(t)&&t.some(e=>gu(e))}function Jh(t){return typeof t=="object"&&t!=null&&Array.isArray(t.handlers)}function Xh(t){let e=t?.callbacks;return t!=null&&typeof e=="object"&&(hu(e?.handlers)||hu(e))}function Qh(){let t=V("LANGSMITH_RUNS_ENDPOINTS");if(!t)return[];try{let e=JSON.parse(t);if(Array.isArray(e)){let r=[];for(let n of e){if(typeof n!="object"||n===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof n}`);continue}if(typeof n.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_url}`);continue}if(typeof n.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_key}`);continue}if(n.project_name!==void 0&&n.project_name!==null&&typeof n.project_name!="string"){console.warn(`Invalid project_name type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.project_name}`);continue}if(n.workspace_id!==void 0&&n.workspace_id!==null&&typeof n.workspace_id!="string"&&(console.warn(`Invalid workspace_id type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.workspace_id}; ignoring it`),n.workspace_id=void 0),n.primary!==void 0&&typeof n.primary!="boolean"){console.warn(`Invalid primary type in LANGSMITH_RUNS_ENDPOINTS: expected boolean, got ${typeof n.primary}`);continue}r.push({apiUrl:n.api_url.replace(/\/$/,""),apiKey:n.api_key,projectName:n.project_name??void 0,workspaceId:n.workspace_id?.trim()||void 0,primary:n.primary??void 0})}return r}else if(typeof e=="object"&&e!==null){Zh(e);let r=[];for(let[n,i]of Object.entries(e)){let s=n.replace(/\/$/,"");if(typeof i=="string")r.push({apiUrl:s,apiKey:i});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${n}: expected string, got ${typeof i}`);continue}}return r}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 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(Pl(e))throw e;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}function Yh(t){let e=t?t.map(r=>{if(Array.isArray(r))return{projectName:r[0],updates:r[1]};let n=be(r.address);return n?{...r,address:n}:r}):Qh();if(e.filter(r=>r.primary===!0).length>1)throw new Error("Only one replica can be marked as primary.");return e}function Zh(t){if(Object.keys(t).length>0&&$("ENDPOINT"))throw new Rn}var SA=B({BaseTracer:()=>Nr,isBaseTracer:()=>Ct}),em=t=>{if(t)return t.events=t.events??[],t.child_runs=t.child_runs??[],t};function Ds(t,e){if(t)return new Ae({...t,start_time:t._serialized_start_time??t.start_time,parent_run:Ds(e),child_runs:t.child_runs.map(r=>Ds(r)).filter(r=>r!==void 0),extra:{...t.extra,runtime:li()},tracingEnabled:!1})}function Us(t,e){return t&&!Array.isArray(t)&&typeof t=="object"?t:{[e]:t}}function Ct(t){return typeof t._addRunToRunMap=="function"}var Nr=class extends it{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(t){super(...arguments)}copy(){return this}getRunById(t){if(t!==void 0)return this.usesRunTreeMap?em(this.runTreeMap.get(t)):this.runMap.get(t)}stringifyError(t){return t instanceof Error?t.message+(t?.stack?`
|
|
169
|
+
|
|
170
|
+
${t.stack}`:""):typeof t=="string"?t:`${t}`}_addChildRun(t,e){t.child_runs.push(e)}_addRunToRunMap(t){let{dottedOrder:e,microsecondPrecisionDatestring:r}=js(new Date(t.start_time).getTime(),t.id,t.execution_order),n={...t},i=this.getRunById(n.parent_run_id);if(n.parent_run_id!==void 0?i?(this._addChildRun(i,n),i.child_execution_order=Math.max(i.child_execution_order,n.child_execution_order),n.trace_id=i.trace_id,i.dotted_order!==void 0&&(n.dotted_order=[i.dotted_order,e].join("."),n._serialized_start_time=r)):n.parent_run_id=void 0:(n.trace_id=n.id,n.dotted_order=e,n._serialized_start_time=r),this.usesRunTreeMap){let s=Ds(n,i);s!==void 0&&this.runTreeMap.set(n.id,s)}else this.runMap.set(n.id,n);return n}async _endTrace(t){let e=t.parent_run_id!==void 0&&this.getRunById(t.parent_run_id);e?e.child_execution_order=Math.max(e.child_execution_order,t.child_execution_order):await this.persistRun(t),await this.onRunUpdate?.(t),this.usesRunTreeMap?this.runTreeMap.delete(t.id):this.runMap.delete(t.id)}_getExecutionOrder(t){let e=t!==void 0&&this.getRunById(t);return e?e.child_execution_order+1:1}_createRunForLLMStart(t,e,r,n,i,s,a,o){let c=this._getExecutionOrder(n),l=Date.now(),u=a?{...i,metadata:a}:i,d={id:r,name:o??t.id[t.id.length-1],parent_run_id:n,start_time:l,serialized:t,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{prompts:e},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:u??{},tags:s||[]};return this._addRunToRunMap(d)}async handleLLMStart(t,e,r,n,i,s,a,o){let c=this.getRunById(r)??this._createRunForLLMStart(t,e,r,n,i,s,a,o);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(t,e,r,n,i,s,a,o){let c=this._getExecutionOrder(n),l=Date.now(),u=a?{...i,metadata:a}:i,d={id:r,name:o??t.id[t.id.length-1],parent_run_id:n,start_time:l,serialized:t,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{messages:e},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:u??{},tags:s||[]};return this._addRunToRunMap(d)}async handleChatModelStart(t,e,r,n,i,s,a,o){let c=this.getRunById(r)??this._createRunForChatModelStart(t,e,r,n,i,s,a,o);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(t,e,r,n,i){let s=this.getRunById(e);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.outputs=t,s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...i},await this.onLLMEnd?.(s),await this._endTrace(s),s}async handleLLMError(t,e,r,n,i){let s=this.getRunById(e);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(t),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...i},await this.onLLMError?.(s),await this._endTrace(s),s}_createRunForChainStart(t,e,r,n,i,s,a,o,c){let l=this._getExecutionOrder(n),u=Date.now(),d={id:r,name:o??t.id[t.id.length-1],parent_run_id:n,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:e,execution_order:l,child_execution_order:l,run_type:a??"chain",child_runs:[],extra:s?{...c,metadata:s}:{...c},tags:i||[]};return this._addRunToRunMap(d)}async handleChainStart(t,e,r,n,i,s,a,o){let c=this.getRunById(r)??this._createRunForChainStart(t,e,r,n,i,s,a,o);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(t,e,r,n,i){let s=this.getRunById(e);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.outputs=Us(t,"output"),s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),i?.inputs!==void 0&&(s.inputs=Us(i.inputs,"input")),await this.onChainEnd?.(s),await this._endTrace(s),s}async handleChainError(t,e,r,n,i){let s=this.getRunById(e);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(t),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),i?.inputs!==void 0&&(s.inputs=Us(i.inputs,"input")),await this.onChainError?.(s),await this._endTrace(s),s}_createRunForToolStart(t,e,r,n,i,s,a,o){let c=this._getExecutionOrder(n),l=Date.now(),u={id:r,name:a??t.id[t.id.length-1],parent_run_id:n,start_time:l,serialized:t,events:[{name:"start",time:new Date(l).toISOString()}],inputs:typeof e=="string"?{input:e}:e,execution_order:c,child_execution_order:c,run_type:"tool",child_runs:[],extra:{...s?{metadata:s}:{},...o!==void 0?{tool_call_id:o}:{}},tags:i||[]};return this._addRunToRunMap(u)}async handleToolStart(t,e,r,n,i,s,a,o){let c=this.getRunById(r)??this._createRunForToolStart(t,e,r,n,i,s,a,o);return await this.onRunCreate?.(c),await this.onToolStart?.(c),c}async handleToolEnd(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:t},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onToolEnd?.(r),await this._endTrace(r),r}async handleToolError(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(t),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onToolError?.(r),await this._endTrace(r),r}async handleAgentAction(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="chain")return;let n=r;n.actions=n.actions||[],n.actions.push(t),n.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentAction?.(r)}async handleAgentEnd(t,e){let r=this.getRunById(e);!r||r?.run_type!=="chain"||(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentEnd?.(r))}_createRunForRetrieverStart(t,e,r,n,i,s,a){let o=this._getExecutionOrder(n),c=Date.now(),l={id:r,name:a??t.id[t.id.length-1],parent_run_id:n,start_time:c,serialized:t,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:e},execution_order:o,child_execution_order:o,run_type:"retriever",child_runs:[],extra:s?{metadata:s}:{},tags:i||[]};return this._addRunToRunMap(l)}async handleRetrieverStart(t,e,r,n,i,s,a){let o=this.getRunById(r)??this._createRunForRetrieverStart(t,e,r,n,i,s,a);return await this.onRunCreate?.(o),await this.onRetrieverStart?.(o),o}async handleRetrieverEnd(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:t},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onRetrieverEnd?.(r),await this._endTrace(r),r}async handleRetrieverError(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(t),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onRetrieverError?.(r),await this._endTrace(r),r}async handleText(t,e){let r=this.getRunById(e);!r||r?.run_type!=="chain"||(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:t}}),await this.onText?.(r))}async handleLLMNewToken(t,e,r,n,i,s){let a=this.getRunById(r);if(!a||a?.run_type!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return a.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:t,idx:e,chunk:s?.chunk}}),await this.onLLMNewToken?.(a,t,{chunk:s?.chunk}),a}};var RA=B({ConsoleCallbackHandler:()=>Gn}),bu={bold:{open:"\x1B[1m",close:"\x1B[22m"},color:{grey:{open:"\x1B[90m",close:"\x1B[39m"},green:{open:"\x1B[32m",close:"\x1B[39m"},cyan:{open:"\x1B[36m",close:"\x1B[39m"},red:{open:"\x1B[31m",close:"\x1B[39m"},blue:{open:"\x1B[34m",close:"\x1B[39m"}}};function ce(t,e){return`${t.open}${e}${t.close}`}function ve(t,e){try{return JSON.stringify(t,null,2)}catch{return e}}function yu(t){return typeof t=="string"?t.trim():t==null?t:ve(t,t.toString())}function Ze(t){if(!t.end_time)return"";let e=t.end_time-t.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}var{color:fe}=bu,Gn=class extends Nr{name="console_callback_handler";persistRun(t){return Promise.resolve()}getParents(t){let e=[],r=t;for(;r.parent_run_id;){let n=this.runMap.get(r.parent_run_id);if(n)e.push(n),r=n;else break}return e}getBreadcrumbs(t){let e=[...this.getParents(t).reverse(),t].map((r,n,i)=>{let s=`${r.execution_order}:${r.run_type}:${r.name}`;return n===i.length-1?ce(bu.bold,s):s}).join(" > ");return ce(fe.grey,e)}onChainStart(t){let e=this.getBreadcrumbs(t);console.log(`${ce(fe.green,"[chain/start]")} [${e}] Entering Chain run with input: ${ve(t.inputs,"[inputs]")}`)}onChainEnd(t){let e=this.getBreadcrumbs(t);console.log(`${ce(fe.cyan,"[chain/end]")} [${e}] [${Ze(t)}] Exiting Chain run with output: ${ve(t.outputs,"[outputs]")}`)}onChainError(t){let e=this.getBreadcrumbs(t);console.log(`${ce(fe.red,"[chain/error]")} [${e}] [${Ze(t)}] Chain run errored with error: ${ve(t.error,"[error]")}`)}onLLMStart(t){let e=this.getBreadcrumbs(t),r="prompts"in t.inputs?{prompts:t.inputs.prompts.map(n=>n.trim())}:t.inputs;console.log(`${ce(fe.green,"[llm/start]")} [${e}] Entering LLM run with input: ${ve(r,"[inputs]")}`)}onLLMEnd(t){let e=this.getBreadcrumbs(t);console.log(`${ce(fe.cyan,"[llm/end]")} [${e}] [${Ze(t)}] Exiting LLM run with output: ${ve(t.outputs,"[response]")}`)}onLLMError(t){let e=this.getBreadcrumbs(t);console.log(`${ce(fe.red,"[llm/error]")} [${e}] [${Ze(t)}] LLM run errored with error: ${ve(t.error,"[error]")}`)}onToolStart(t){let e=this.getBreadcrumbs(t);console.log(`${ce(fe.green,"[tool/start]")} [${e}] Entering Tool run with input: "${yu(t.inputs.input)}"`)}onToolEnd(t){let e=this.getBreadcrumbs(t);console.log(`${ce(fe.cyan,"[tool/end]")} [${e}] [${Ze(t)}] Exiting Tool run with output: "${yu(t.outputs?.output)}"`)}onToolError(t){let e=this.getBreadcrumbs(t);console.log(`${ce(fe.red,"[tool/error]")} [${e}] [${Ze(t)}] Tool run errored with error: ${ve(t.error,"[error]")}`)}onRetrieverStart(t){let e=this.getBreadcrumbs(t);console.log(`${ce(fe.green,"[retriever/start]")} [${e}] Entering Retriever run with input: ${ve(t.inputs,"[inputs]")}`)}onRetrieverEnd(t){let e=this.getBreadcrumbs(t);console.log(`${ce(fe.cyan,"[retriever/end]")} [${e}] [${Ze(t)}] Exiting Retriever run with output: ${ve(t.outputs,"[outputs]")}`)}onRetrieverError(t){let e=this.getBreadcrumbs(t);console.log(`${ce(fe.red,"[retriever/error]")} [${e}] [${Ze(t)}] Retriever run errored with error: ${ve(t.error,"[error]")}`)}onAgentAction(t){let e=t,r=this.getBreadcrumbs(t);console.log(`${ce(fe.blue,"[agent/action]")} [${r}] Agent selected action: ${ve(e.actions[e.actions.length-1],"[action]")}`)}};var Hs,zn=()=>{if(Hs===void 0){let t=Ee("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};Hs=new Ye(t)}return Hs};var wu=Symbol.for("langchain.trace_policy");function xu(t){return{}}var eI=B({LangChainTracer:()=>et,OVERRIDABLE_LANGSMITH_INHERITABLE_METADATA_KEYS:()=>Fs,omitPayload:()=>xu}),Fs=new Set(["ls_agent_type"]);function tm(t){let e;for(let r of t)for(let n of r)Mt.isInstance(n.message)&&n.message.usage_metadata!==void 0&&(e=Br(e,n.message.usage_metadata));return e}var et=class Bs extends Nr{fields;name="langchain_tracer";projectName;address;exampleId;client;replicas;usesRunTreeMap=!0;tracingMetadata;tracingTags=[];constructor(e={}){super(e),this.fields=e;let{exampleId:r,projectName:n,address:i,client:s,replicas:a,metadata:o,tags:c}=e;this.projectName=n,this.address=i,this.replicas=a,this.exampleId=r,this.client=s??zn(),this.tracingMetadata=o?{...o}:void 0,this.tracingTags=c??[];let l=Bs.getTraceableRunTree();l&&this.updateFromRunTree(l)}async persistRun(e){}async onRunCreate(e){if(vu(this,e),!e.extra?.lc_defers_inputs){let r=this.getRunTreeWithTracingConfig(e.id),n=r?this._applyTracePolicy(r):void 0;if(await r?.postRun(),n!==void 0)throw n}}async onRunUpdate(e){vu(this,e);let r=this.getRunTreeWithTracingConfig(e.id),n=r?this._applyTracePolicy(r):void 0;if(e.extra?.lc_defers_inputs?await r?.postRun():await r?.patchRun(),n!==void 0)throw n}_applyTracePolicy(e){let{[wu]:r,...n}=e.extra??{};if(r===void 0)return;let{processInputs:i,processOutputs:s}=r;e.extra=n;let a;if(i&&e.inputs!==void 0)try{e.inputs=i(e.inputs)}catch(o){e.inputs={},a=o}if(s&&e.outputs!==void 0)try{e.outputs=s(e.outputs)}catch(o){e.outputs=void 0,a??=o}return a!==void 0&&(e.error??=this.stringifyError(a)),a}onLLMEnd(e){let r=e.outputs;if(r?.generations){let n=tm(r.generations);if(n!==void 0){e.extra=e.extra??{};let i=e.extra.metadata??{};i.usage_metadata=n,e.extra.metadata=i}}}copyWithTracingConfig({metadata:e,tags:r}){let n;if(e===void 0)n=this.tracingMetadata?{...this.tracingMetadata}:void 0;else if(this.tracingMetadata===void 0)n={...e};else{n={...this.tracingMetadata};for(let[a,o]of Object.entries(e))(!Object.prototype.hasOwnProperty.call(n,a)||Fs.has(a))&&(n[a]=o)}let i=r?Array.from(new Set([...this.tracingTags,...r])):[...this.tracingTags],s=new Bs({...this.fields,metadata:n,tags:i});return s.runMap=this.runMap,s.runTreeMap=this.runTreeMap,s}_getRunStoreKey(){return this.runTreeMap}getRun(e){return this.runTreeMap.get(e)}updateFromRunTree(e){this.runTreeMap.set(e.id,e);let r=e,n=new Set;for(;r.parent_run&&!(n.has(r.id)||(n.add(r.id),!r.parent_run));)r=r.parent_run;n.clear();let i=[r];for(;i.length>0;){let s=i.shift();!s||n.has(s.id)||(n.add(s.id),this.runTreeMap.set(s.id,s),s.child_runs&&i.push(...s.child_runs))}this.client=e.client??this.client,this.replicas=e.replicas??this.replicas,(e.project_name||e.address)&&(this.projectName=e.project_name,this.address=e.address),this.exampleId=e.reference_example_id??this.exampleId,this.fields={...this.fields,client:this.client,replicas:this.replicas,projectName:this.projectName,address:this.address,exampleId:this.exampleId}}getRunTreeWithTracingConfig(e){let r=this.runTreeMap.get(e);if(!r)return;let n={...r,client:this.client,project_name:this.projectName,address:this.address,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0};return n.project_name==null&&delete n.project_name,n.address==null&&delete n.address,new Ae(n)}static getTraceableRunTree(){try{return ks(!0)}catch{return}}static[Symbol.hasInstance](e){if(typeof e!="object"||e===null)return!1;let r=e;return"name"in r&&r.name==="langchain_tracer"&&"copyWithTracingConfig"in r&&typeof r.copyWithTracingConfig=="function"&&"getRunTreeWithTracingConfig"in r&&typeof r.getRunTreeWithTracingConfig=="function"}};function vu(t,e){if(t.tracingMetadata){e.extra??={};let r=e.extra.metadata??{},n=!1;for(let[i,s]of Object.entries(t.tracingMetadata))(!Object.prototype.hasOwnProperty.call(r,i)||Fs.has(i))&&r[i]!==s&&(r[i]=s,n=!0);n&&(e.extra.metadata=r)}t.tracingTags.length>0&&(e.tags=Array.from(new Set([...e.tags??[],...t.tracingTags])))}var Eu=Symbol.for("ls:tracing_async_local_storage"),tt=Symbol.for("lc:context_variables"),Su=t=>{globalThis[Eu]=t},rt=()=>globalThis[Eu];var qn=Js(Hi(),1),Ot;function rm(){return new("default"in qn.default?qn.default.default:qn.default)({autoStart:!0,concurrency:1})}function nm(){return typeof Ot>"u"&&(Ot=rm()),Ot}async function F(t,e){if(e===!0){let r=rt();r!==void 0?await r.run(void 0,async()=>t()):await t()}else Ot=nm(),Ot.add(async()=>{let r=rt();r!==void 0?await r.run(void 0,async()=>t()):await t()})}async function Au(){let t=zn();await Promise.allSettled([typeof Ot<"u"?Ot.onIdle():Promise.resolve(),t.awaitPendingTraceBatches()])}var cI=B({awaitAllCallbacks:()=>Au,consumeCallback:()=>F});var Iu=t=>t!==void 0?t:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>Ee(e)==="true");function Gs(t){let e=rt();if(e!==void 0)return e.getStore()?.[tt]?.[t]}var im=Symbol("lc:configure_hooks"),Tu=()=>Gs(im)||[];var TI=B({BaseCallbackManager:()=>Ru,BaseRunManager:()=>Mr,CallbackManager:()=>Ge,CallbackManagerForChainRun:()=>Ou,CallbackManagerForLLMRun:()=>qs,CallbackManagerForRetrieverRun:()=>Cu,CallbackManagerForToolRun:()=>ku,ensureHandler:()=>ur,parseCallbackConfigArg:()=>om});function zs(t){return t._getRunStoreKey?.()??t}function sm(t,e){return t===e?t:t.copyWithTracingConfig({metadata:e.tracingMetadata,tags:e.tracingTags})}function am(t,e){let r=new Set(e),n=new Map,i=[],s=o=>{let c=zs(o),l=r.has(o),u=n.get(c);if(u===void 0){n.set(c,{index:i.length,tracer:o,hasInheritable:l}),i.push(o);return}l&&!u.hasInheritable?(u.tracer=o,u.hasInheritable=!0):(l||!u.hasInheritable)&&(u.tracer=sm(u.tracer,o)),i[u.index]=u.tracer};for(let o of t)o instanceof et?s(o):i.push(o);for(let o of e)o instanceof et&&!n.has(zs(o))&&s(o);let a=new Set;return{handlers:i,inheritableHandlers:e.flatMap(o=>{if(!(o instanceof et))return[o];let c=zs(o);return a.has(c)?[]:(a.add(c),[n.get(c)?.tracer??o])})}}function om(t){return t?Array.isArray(t)||"name"in t?{callbacks:t}:t:{}}var Ru=class{setHandler(t){return this.setHandlers([t])}},Mr=class{runId;handlers;inheritableHandlers;tags;inheritableTags;metadata;inheritableMetadata;_parentRunId;constructor(t,e,r,n,i,s,a,o){this.runId=t,this.handlers=e,this.inheritableHandlers=r,this.tags=n,this.inheritableTags=i,this.metadata=s,this.inheritableMetadata=a,this._parentRunId=o}get parentRunId(){return this._parentRunId}async handleText(t){await Promise.all(this.handlers.map(e=>F(async()=>{try{await e.handleText?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleText: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleCustomEvent(t,e,r,n,i){await Promise.all(this.handlers.map(s=>F(async()=>{try{await s.handleCustomEvent?.(t,e,this.runId,this.tags,this.metadata)}catch(a){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleCustomEvent: ${a}`),s.raiseError)throw a}},s.awaitHandlers)))}},Cu=class extends Mr{getChild(t){let e=new Ge(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleRetrieverEnd(t){await Promise.all(this.handlers.map(e=>F(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetriever`),e.raiseError)throw r}},e.awaitHandlers)))}async handleRetrieverError(t){await Promise.all(this.handlers.map(e=>F(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverError?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetrieverError: ${r}`),e.raiseError)throw t}},e.awaitHandlers)))}},qs=class extends Mr{async handleLLMNewToken(t,e,r,n,i,s){await Promise.all(this.handlers.map(a=>F(async()=>{if(!a.ignoreLLM)try{await a.handleLLMNewToken?.(t,e??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,s)}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMNewToken: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}async handleChatModelStreamEvent(t){await Promise.all(this.handlers.map(e=>F(async()=>{if(!e.ignoreLLM)try{await e.handleChatModelStreamEvent?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleChatModelStreamEvent: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleLLMError(t,e,r,n,i){await Promise.all(this.handlers.map(s=>F(async()=>{if(!s.ignoreLLM)try{await s.handleLLMError?.(t,this.runId,this._parentRunId,this.tags,i)}catch(a){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMError: ${a}`),s.raiseError)throw a}},s.awaitHandlers)))}async handleLLMEnd(t,e,r,n,i){await Promise.all(this.handlers.map(s=>F(async()=>{if(!s.ignoreLLM)try{await s.handleLLMEnd?.(t,this.runId,this._parentRunId,this.tags,i)}catch(a){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMEnd: ${a}`),s.raiseError)throw a}},s.awaitHandlers)))}},Ou=class extends Mr{getChild(t){let e=new Ge(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleChainError(t,e,r,n,i){await Promise.all(this.handlers.map(s=>F(async()=>{if(!s.ignoreChain)try{await s.handleChainError?.(t,this.runId,this._parentRunId,this.tags,i)}catch(a){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleChainError: ${a}`),s.raiseError)throw a}},s.awaitHandlers)))}async handleChainEnd(t,e,r,n,i){await Promise.all(this.handlers.map(s=>F(async()=>{if(!s.ignoreChain)try{await s.handleChainEnd?.(t,this.runId,this._parentRunId,this.tags,i)}catch(a){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleChainEnd: ${a}`),s.raiseError)throw a}},s.awaitHandlers)))}async handleAgentAction(t){await Promise.all(this.handlers.map(e=>F(async()=>{if(!e.ignoreAgent)try{await e.handleAgentAction?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentAction: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleAgentEnd(t){await Promise.all(this.handlers.map(e=>F(async()=>{if(!e.ignoreAgent)try{await e.handleAgentEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},ku=class extends Mr{getChild(t){let e=new Ge(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleToolError(t){await Promise.all(this.handlers.map(e=>F(async()=>{if(!e.ignoreAgent)try{await e.handleToolError?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolError: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleToolEvent(t){await Promise.all(this.handlers.map(e=>F(async()=>{if(!e.ignoreAgent)try{await e.handleToolEvent?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if(e.raiseError)throw r}},e.awaitHandlers)))}async handleToolEnd(t){await Promise.all(this.handlers.map(e=>F(async()=>{if(!e.ignoreAgent)try{await e.handleToolEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},Ge=class Lr extends Ru{handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor(e,r){super(),this.handlers=r?.handlers??this.handlers,this.inheritableHandlers=r?.inheritableHandlers??this.inheritableHandlers,this.tags=r?.tags??this.tags,this.inheritableTags=r?.inheritableTags??this.inheritableTags,this.metadata=r?.metadata??this.metadata,this.inheritableMetadata=r?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,r,n=void 0,i=void 0,s=void 0,a=void 0,o=void 0,c=void 0){return Promise.all(r.map(async(l,u)=>{let d=u===0&&n?n:Ie();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return Ct(f)&&f._createRunForLLMStart(e,[l],d,this._parentRunId,s,this.tags,this.metadata,c),F(async()=>{try{await f.handleLLMStart?.(e,[l],d,this._parentRunId,s,this.tags,this.metadata,c)}catch(p){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${p}`),f.raiseError)throw p}},f.awaitHandlers)})),new qs(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,r,n=void 0,i=void 0,s=void 0,a=void 0,o=void 0,c=void 0){return Promise.all(r.map(async(l,u)=>{let d=u===0&&n?n:Ie();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return Ct(f)&&f._createRunForChatModelStart(e,[l],d,this._parentRunId,s,this.tags,this.metadata,c),F(async()=>{try{if(f.handleChatModelStart)await f.handleChatModelStart?.(e,[l],d,this._parentRunId,s,this.tags,this.metadata,c);else if(f.handleLLMStart){let p=co(l);await f.handleLLMStart?.(e,[p],d,this._parentRunId,s,this.tags,this.metadata,c)}}catch(p){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${p}`),f.raiseError)throw p}},f.awaitHandlers)})),new qs(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,r,n=Ie(),i=void 0,s=void 0,a=void 0,o=void 0,c=void 0,l=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreChain)return Ct(u)&&u._createRunForChainStart(e,r,n,this._parentRunId,this.tags,this.metadata,i,o,l),F(async()=>{try{await u.handleChainStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,i,o,l)}catch(d){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleChainStart: ${d}`),u.raiseError)throw d}},u.awaitHandlers)})),new Ou(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,r,n=Ie(),i=void 0,s=void 0,a=void 0,o=void 0,c=void 0){return await Promise.all(this.handlers.map(l=>{if(!l.ignoreAgent)return Ct(l)&&l._createRunForToolStart(e,r,n,this._parentRunId,this.tags,this.metadata,o,c),F(async()=>{try{await l.handleToolStart?.(e,typeof r=="string"?r:JSON.stringify(r),n,this._parentRunId,this.tags,this.metadata,o,c)}catch(u){if((l.raiseError?console.error:console.warn)(`Error in handler ${l.constructor.name}, handleToolStart: ${u}`),l.raiseError)throw u}},l.awaitHandlers)})),new ku(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,r,n=Ie(),i=void 0,s=void 0,a=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreRetriever)return Ct(c)&&c._createRunForRetrieverStart(e,r,n,this._parentRunId,this.tags,this.metadata,o),F(async()=>{try{await c.handleRetrieverStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,o)}catch(l){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleRetrieverStart: ${l}`),c.raiseError)throw l}},c.awaitHandlers)})),new Cu(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,r,n,i,s){await Promise.all(this.handlers.map(a=>F(async()=>{if(!a.ignoreCustomEvent)try{await a.handleCustomEvent?.(e,r,n,this.tags,this.metadata)}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleCustomEvent: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}addHandler(e,r=!0){this.handlers.push(e),r&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(r=>r!==e),this.inheritableHandlers=this.inheritableHandlers.filter(r=>r!==e)}setHandlers(e,r=!0){this.handlers=[],this.inheritableHandlers=[];for(let n of e)this.addHandler(n,r)}addTags(e,r=!0){this.removeTags(e),this.tags.push(...e),r&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(r=>!e.includes(r)),this.inheritableTags=this.inheritableTags.filter(r=>!e.includes(r))}addMetadata(e,r=!0){this.metadata={...this.metadata,...e},r&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(let r of Object.keys(e))delete this.metadata[r],delete this.inheritableMetadata[r]}copy(e=[],r=!0){let n=new Lr(this._parentRunId);for(let i of this.handlers){let s=this.inheritableHandlers.includes(i);n.addHandler(i,s)}for(let i of this.tags){let s=this.inheritableTags.includes(i);n.addTags([i],s)}for(let i of Object.keys(this.metadata)){let s=Object.keys(this.inheritableMetadata).includes(i);n.addMetadata({[i]:this.metadata[i]},s)}for(let i of e)n.handlers.filter(s=>s.name==="console_callback_handler").some(s=>s.name===i.name)||n.addHandler(i,r);return n}static fromHandlers(e){class r extends it{name=Ie();constructor(){super(),Object.assign(this,e)}}let n=new this;return n.addHandler(new r),n}static configure(e,r,n,i,s,a,o){return this._configureSync(e,r,n,i,s,a,o)}static _configureSync(e,r,n,i,s,a,o){let c;(e||r)&&(Array.isArray(e)||!e?(c=new Lr,c.setHandlers(e?.map(ur)??[],!0)):c=e,c=c.copy(Array.isArray(r)?r.map(ur):r?.handlers,!1));let l=Ee("LANGCHAIN_VERBOSE")==="true"||o?.verbose,u=et.getTraceableRunTree(),d=u?.tracingEnabled??Iu();if(u?.tracingEnabled===!1&&c){let m=c.handlers.filter(w=>w.name==="langchain_tracer");for(let w of m)c.removeHandler(w)}let f=d||(Ee("LANGCHAIN_TRACING")??!1);if(l||f){if(c||(c=new Lr),l&&!c.handlers.some(m=>m.name===Gn.prototype.name)){let m=new Gn;c.addHandler(m,!0)}if(f&&!c.handlers.some(m=>m.name==="langchain_tracer")&&d){let m=new et;c.addHandler(m,!0)}d&&u&&c._parentRunId===void 0&&(c._parentRunId=u.id,c.handlers.find(m=>m.name==="langchain_tracer")?.updateFromRunTree(u))}for(let{contextVar:m,inheritable:w=!0,handlerClass:E,envVar:b}of Tu()){let R=b&&Ee(b)==="true"&&E,v,M=m!==void 0?Gs(m):void 0;M&&ui(M)?v=M:R&&(v=new E({})),v!==void 0&&(c||(c=new Lr),c.handlers.some(k=>k.name===v.name)||c.addHandler(v,w))}(n||i)&&c&&(c.addTags(n??[]),c.addTags(i??[],!1)),(s||a)&&c&&(c.addMetadata(s??{}),c.addMetadata(a??{},!1));let p=o?.tracerInheritableMetadata,h=o?.tracerInheritableTags;if(c&&(p||h)){let m=new Map,w=E=>{if(!(E instanceof et))return E;let b=m.get(E);if(b!==void 0)return b;let R=E.copyWithTracingConfig({metadata:p,tags:h});return m.set(E,R),R};c.handlers=c.handlers.map(w),c.inheritableHandlers=c.inheritableHandlers.map(w)}if(c){let m=am(c.handlers,c.inheritableHandlers),w=Pu(m.inheritableHandlers),E=new Map(w.map(b=>[Ks(b),b]));c.handlers=Pu(m.handlers).map(b=>E.get(Ks(b))??b),c.inheritableHandlers=w}return c}},Nu=Symbol("handlerSource");function Ks(t){return t[Nu]??t}function Pu(t){let e=new Set;return t.filter(r=>{let n=Ks(r);return e.has(n)?!1:(e.add(n),!0)})}function ur(t){if("name"in t)return t;let e=it.fromMethods(t);return Object.defineProperty(e,Nu,{value:t}),e}var Vs=class{getStore(){}run(t,e){return e()}enterWith(t){}},cm=new Vs,Lu=Symbol.for("lc:child_config"),lm=class{getInstance(){return rt()??cm}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[Lu]}runWithConfig(t,e,r){let n=Ge._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata),i=this.getInstance(),s=i.getStore(),a=n?.getParentRunId(),o=n?.handlers?.find(l=>l?.name==="langchain_tracer"),c;return o&&a?c=o.getRunTreeWithTracingConfig(a):r||(c=new Ae({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[Lu]:t}),s!==void 0&&s[tt]!==void 0&&(c===void 0&&(c={}),c[tt]=s[tt]),i.run(c,e)}initializeGlobalInstance(t){rt()===void 0&&Su(t)}},Kn=new lm;var zI=B({AsyncLocalStorageProviderSingleton:()=>Kn,MockAsyncLocalStorage:()=>Vs,_CONTEXT_VARIABLES_KEY:()=>tt});var um=new Set(["api_key"]),dm=new Set(["string","number","boolean"]);function fm(t){let e=t.configurable??{},r=t.metadata??{},n={};for(let[i,s]of Object.entries(e))!i.startsWith("__")&&!Object.prototype.hasOwnProperty.call(r,i)&&!um.has(i)&&dm.has(typeof s)&&(n[i]=s);return Object.keys(n).length>0?n:void 0}async function JI(t){return Ge._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata,void 0,{tracerInheritableMetadata:t?fm(t):void 0})}function XI(...t){let e={};for(let r of t.filter(n=>!!n))for(let n of Object.keys(r))if(n==="metadata")e[n]={...e[n],...r[n]};else if(n==="tags"){let i=e[n]??[];e[n]=[...new Set(i.concat(r[n]??[]))]}else if(n==="configurable")e[n]={...e[n],...r[n]};else if(n==="timeout")e.timeout===void 0?e.timeout=r.timeout:r.timeout!==void 0&&(e.timeout=Math.min(e.timeout,r.timeout));else if(n==="signal")e.signal===void 0?e.signal=r.signal:r.signal!==void 0&&("any"in AbortSignal?e.signal=AbortSignal.any([e.signal,r.signal]):e.signal=r.signal);else if(n==="callbacks"){let i=e.callbacks,s=r.callbacks;if(Array.isArray(s))if(!i)e.callbacks=s;else if(Array.isArray(i))e.callbacks=i.concat(s);else{let a=i.copy();for(let o of s)a.addHandler(ur(o),!0);e.callbacks=a}else if(s)if(!i)e.callbacks=s;else if(Array.isArray(i)){let a=s.copy();for(let o of i)a.addHandler(ur(o),!0);e.callbacks=a}else e.callbacks=new Ge(s._parentRunId,{handlers:i.handlers.concat(s.handlers),inheritableHandlers:i.inheritableHandlers.concat(s.inheritableHandlers),tags:Array.from(new Set(i.tags.concat(s.tags))),inheritableTags:Array.from(new Set(i.inheritableTags.concat(s.inheritableTags))),metadata:{...i.metadata,...s.metadata}})}else{let i=n;e[i]=r[i]??e[i]}return e}function pm(t){let e=Kn.getRunnableConfig(),r={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(e){let{runId:n,runName:i,...s}=e;r=Object.entries(s).reduce((a,[o,c])=>(c!==void 0&&(a[o]=c),a),r)}if(t&&(r=Object.entries(t).reduce((n,[i,s])=>(s!==void 0&&(n[i]=s),n),r)),r?.configurable&&typeof r.configurable.model=="string"&&r.metadata?.model===void 0&&(r.metadata||(r.metadata={}),r.metadata.model=r.configurable.model),r.timeout!==void 0){if(r.timeout<=0)throw new Error("Timeout must be a positive number");let n=r.timeout,i=AbortSignal.timeout(n);r.metadata||(r.metadata={}),r.metadata.timeoutMs===void 0&&(r.metadata.timeoutMs=n),r.signal!==void 0?"any"in AbortSignal&&(r.signal=AbortSignal.any([r.signal,i])):r.signal=i,delete r.timeout}return r}function QI(t={},{callbacks:e,maxConcurrency:r,recursionLimit:n,runName:i,configurable:s,runId:a}={}){let o=pm(t);return e!==void 0&&(delete o.runName,o.callbacks=e),n!==void 0&&(o.recursionLimit=n),r!==void 0&&(o.maxConcurrency=r),i!==void 0&&(o.runName=i),s!==void 0&&(o.configurable={...o.configurable,...s}),a!==void 0&&delete o.runId,o}function YI(t){if(t)return{configurable:t.configurable,recursionLimit:t.recursionLimit,callbacks:t.callbacks,tags:t.tags,metadata:t.metadata,maxConcurrency:t.maxConcurrency,timeout:t.timeout,signal:t.signal,store:t.store,context:t.context}}export{jy as a,Hd as b,Bd as c,Fd as d,Ie as e,Gd as f,hm as g,Ys as h,Bu as i,Zs as j,wm as k,jr as l,Nt as m,Hy as n,Oo as o,Ee as p,Ky as q,Kd as r,Vd as s,it as t,Hi as u,Ye as v,A0 as w,SA as x,Nr as y,RA as z,$_ as A,ti as B,Fr as C,gd as D,yd as E,bd as F,wd as G,Za as H,H_ as I,B_ as J,z_ as K,ri as L,ze as M,na as N,ia as O,vm as P,sa as Q,Em as R,Sm as S,Wn as T,Am as U,_a as V,ue as W,va as X,ae as Y,qm as Z,rd as _,z as $,Lt as aa,Ea as ba,me as ca,Aa as da,Ia as ea,Km as fa,qa as ga,Br as ha,Qm as ia,ad as ja,Hr as ka,od as la,Yn as ma,cd as na,ld as oa,Mt as pa,Dg as qa,Hg as ra,oo as sa,ni as ta,to as ua,V_ as va,W_ as wa,ro as xa,no as ya,Y_ as za,Z_ as Aa,zr as Ba,io as Ca,ig as Da,sg as Ea,so as Fa,Kr as Ga,ao as Ha,pg as Ia,hg as Ja,Pg as Ka,Rg as La,co as Ma,Td as Na,Cg as Oa,Og as Pa,kg as Qa,lo as Ra,wu as Sa,eI as Ta,cI as Ua,TI as Va,om as Wa,Ge as Xa,ur as Ya,Kn as Za,zI as _a,JI as $a,XI as ab,pm as bb,QI as cb,YI as db};
|