PageSourceSearch

https://www.wyzerai.com/_next/static/chunks/589c24b9-162546ce97e21705.js

js wyzerai.com collected 2026-10-09 22:25:18 UTC 86,825 bytes, 24 lines download raw bytes

1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[6013],{93645:(t,e,i)=>{i.d(e,{Kj:()=>j});var a=i(45778),r=i(54568),s=i(79675),n=i(72211),o=i(17204),l=i(82851),h=i(68742),d=i(68360),u=i(30491),c=i(34544),p=i(57861),m=i(85759),f=i(2510),g=i(67568),_=i(33725),w=i(47415),y=i(37771),b=i(59619),v=i(52107),S=i(49641).Buffer;function $(t){return"string"!=typeof t||!(t.length>0)||t.includes("Z")||t.includes("+")||t.includes("-",10)?t:t+"Z"}function O(t){return{...t,start_time:$(t.start_time),end_time:$(t.end_time)}}function P(t,e,i){if(i)return t;let a=(0,l.Ec)(),r=e??(0,l.I6)(),s=t.extra??{},n=s.metadata;return t.extra={...s,runtime:{...a,...s?.runtime},metadata:{...r,...r.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??r.revision_id}:{},...n}},t}async function A(t){let e=[];for await(let i of t)e.push(i);return e}function E(t){if(void 0!==t)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}let T=async t=>{if(t?.status===429){let e=1e3*parseInt(t.headers.get("retry-after")??"10",10);if(e>0)return await new Promise(t=>setTimeout(t,e)),!0}return!1};function U(t){return"number"==typeof t?Number(t.toFixed(4)):t}class I{constructor(t){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=t??0x40000000}peek(){return this.items[0]}push(t){let e,i=new Promise(t=>{e=t}),a=(0,b.a)(t.item).size;return this.sizeBytes+a>this.maxSizeBytes&&this.items.length>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${t.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${a} bytes.`),e()):(this.items.push({action:t.action,payload:t.item,otelContext:t.otelContext,apiKey:t.apiKey,apiUrl:t.apiUrl,itemPromiseResolve:e,itemPromise:i,size:a}),this.sizeBytes+=a),i}pop({upToSizeBytes:t,upToSize:e}){if(t<1)throw Error("Number of bytes to pop off may not be less than 1.");let i=[],a=0;for(;a+(this.peek()?.size??0)<t&&this.items.length>0&&i.length<e;){let t=this.items.shift();t&&(i.push(t),a+=t.size,this.sizeBytes-=t.size)}if(0===i.length&&this.items.length>0){let t=this.items.shift();i.push(t),a+=t.size,this.sizeBytes-=t.size}return[i.map(t=>({action:t.action,item:t.payload,otelContext:t.otelContext,apiKey:t.apiKey,apiUrl:t.apiUrl,size:t.size})),()=>i.forEach(t=>t.itemPromiseResolve())]}}class j{get tracingMode(){return this._tracingMode}get _fetch(){let t=this.fetchImplementation||(0,w.Yx)(this.debug);return async(e,i)=>{let a,r=this.getProfileManagedAuthorizationHeader(i);return void 0!==this.apiKey?a={name:"x-api-key",value:`${this.apiKey}`}:this.hasExplicitAuthHeader(i,r)||(a=await this.profileAuth?.getAuthHeader(t,i?.signal)),t(e,this.applyCurrentAuthHeaders(i,a,r))}}getProfileManagedAuthorizationHeader(t){if(!t?.headers||!this.profileAuth)return;let e=new Headers(t.headers).get("Authorization");if((0,y.a4)(e))return this.profileAuth.isProfileAuthorizationHeader(e??"")?e??void 0:void 0}isProfileManagedAuthorizationHeader(t,e){return t===e||this.profileAuth?.isProfileAuthorizationHeader(t)===!0}hasExplicitAuthHeader(t,e){if(!t?.headers)return!1;let i=new Headers(t.headers);if((0,y.a4)(i.get("x-api-key")))return!0;let a=i.get("Authorization");return!!(0,y.a4)(a)&&!this.isProfileManagedAuthorizationHeader(a??"",e)}applyCurrentAuthHeaders(t,e,i){if(!e)return t;let a=t=>{if(void 0!==this.apiKey&&"x-api-key"===e.name)return t.delete("Authorization"),t.has("x-api-key")||t.set("x-api-key",e.value),t;if("Authorization"===e.name){if((0,y.a4)(t.get("x-api-key")))return t;let a=t.get("Authorization");return(0,y.a4)(a)&&!this.isProfileManagedAuthorizationHeader(a??"",i)||t.set("Authorization",e.value),t}let a=t.get("Authorization");return(0,y.a4)(a)&&!this.isProfileManagedAuthorizationHeader(a??"",i)||((0,y.a4)(a)&&t.delete("Authorization"),t.has("x-api-key")||t.set("x-api-key",e.value)),t};if(!t)return{headers:{[e.name]:e.value}};if(t.headers instanceof Headers||Array.isArray(t.headers))return{...t,headers:a(new Headers(t.headers))};let r={...t.headers??{}},s=t=>Object.keys(r).find(e=>e.toLowerCase()===t),n=t=>{let e=s(t);return e?r[e]:void 0},o=(0,y.a4)(n("x-api-key")),l=n("authorization"),h=(0,y.a4)(l)&&!this.isProfileManagedAuthorizationHeader(l??"",i);if(void 0!==this.apiKey&&"x-api-key"===e.name){let i=s("authorization");return i&&delete r[i],o||(r["x-api-key"]=e.value),{...t,headers:r}}if("Authorization"===e.name){if(!o&&!h){let t=s("authorization");t&&"Authorization"!==t&&delete r[t],r.Authorization=e.value}return{...t,headers:r}}if(!h){let t=s("authorization");t&&delete r[t],o||(r["x-api-key"]=e.value)}return{...t,headers:r}}_trackDrain(t){this._pendingDrains.add(t),t.finally(()=>{this._pendingDrains.delete(t)})}async _serializeBody(t,e){if(this.manualFlushMode||!(0,v.zo)(t)||(void 0===this._serializeWorker&&(this._serializeWorker=(0,v.AA)()),null===this._serializeWorker))return(0,b.l)(t,e);try{let i=await this._serializeWorker.serialize(t);if(null===i)return this._serializeWorker=null,(0,b.l)(t,e);return i}catch{return(0,b.l)(t,e)}}constructor(t={}){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,"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,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value: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,"openAPIClient",{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:"false"===(0,l.Az)("LANGSMITH_TRACING_BACKGROUND")}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_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,"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}
1),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:"true"===(0,l.Jz)("DISABLE_MULTIPART_STREAMING")}),Object.defineProperty(this,"_multipartDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_runCompressionDisabled",{enumerable:!0,configurable:!0,writable:!0,value:"true"===(0,l.Jz)("DISABLE_RUN_COMPRESSION")}),Object.defineProperty(this,"failedTracesDir",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"failedTracesMaxBytes",{enumerable:!0,configurable:!0,writable:!0,value:0x6400000}),Object.defineProperty(this,"_customHeaders",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:"true"===(0,l.Az)("LANGSMITH_DEBUG")});let e=j.getDefaultClientConfig();this.tracingSampleRate=(t=>{let e=t?.toString()??(0,l.Jz)("TRACING_SAMPLING_RATE");if(void 0===e)return;let i=parseFloat(e);if(i<0||i>1)throw Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${i}`);return i})(t.tracingSamplingRate),this.apiUrl=E(t.apiUrl??e.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1));let i=E(t.apiKey??e.apiKey);if(this.apiKey=(0,y.a4)(i)?i:void 0,this.profileAuth=void 0!==this.apiKey?void 0:e.profileAuth,this.webUrl=E(t.webUrl??e.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=E(t.workspaceId??e.workspaceId),this.timeout_ms=t.timeout_ms??9e4,this.caller=new n.g({...t.callerOptions??{},maxRetries:4,debug:t.debug??this.debug}),this.traceBatchConcurrency=t.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw Error("Trace batch concurrency must be positive.");this.debug=t.debug??this.debug,this.fetchImplementation=t.fetchImplementation,this.failedTracesDir=(0,l.Jz)("FAILED_TRACES_DIR")||void 0;let a=(0,l.Jz)("FAILED_TRACES_MAX_MB");if(a){let t=parseInt(a,10);Number.isFinite(t)&&t>0&&(this.failedTracesMaxBytes=1024*t*1024)}let s=t.maxIngestMemoryBytes??0x40000000;this.batchIngestCaller=new n.g({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:s,...t.callerOptions??{},onFailedResponseHook:T,debug:t.debug??this.debug}),this.hideInputs=t.hideInputs??t.anonymizer??e.hideInputs,this.hideOutputs=t.hideOutputs??t.anonymizer??e.hideOutputs,this.hideMetadata=t.hideMetadata??e.hideMetadata,this.omitTracedRuntimeInfo=t.omitTracedRuntimeInfo??!1,this.autoBatchTracing=t.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new I(s),this.blockOnRootRunFinalization=t.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=t.batchSizeBytesLimit,this.batchSizeLimit=t.batchSizeLimit,this.fetchOptions=t.fetchOptions||{},this.openAPIClient=this._newOpenAPIClient(),this.manualFlushMode=t.manualFlushMode??this.manualFlushMode,this._tracingMode=(0,l.wD)(t.tracingMode),"otel"===this._tracingMode&&(this.langSmithToOTELTranslator=new r.T),this.cachedLSEnvVarsForMetadata=(0,l.I6)(),void 0!==t.cache&&t.disablePromptCache&&(0,c.m)("Both 'cache' and 'disablePromptCache' were provided. The 'cache' parameter is deprecated and will be removed in a future version. Using 'cache' parameter value."),void 0!==t.cache?((0,c.m)("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."),!1===t.cache?this._promptCache=void 0:!0===t.cache?this._promptCache=g.MP:this._promptCache=t.cache):t.disablePromptCache||(this._promptCache=g.MP),this._customHeaders=t.headers??{}}static getDefaultClientConfig(){let t=(0,y.P0)(),e=(0,l.Jz)("API_KEY"),i=(0,l.Jz)("ENDPOINT"),a=(0,l.Jz)("WORKSPACE_ID"),r=(0,y.a4)(e),s=i??t.apiUrl??y.rK,n=a??t.workspaceId,o="true"===(0,l.Jz)("HIDE_INPUTS");return{apiUrl:s,apiKey:e,webUrl:void 0,hideInputs:o,hideOutputs:"true"===(0,l.Jz)("HIDE_OUTPUTS"),hideMetadata:"true"===(0,l.Jz)("HIDE_METADATA"),workspaceId:n,oauthAccessToken:r?void 0:t.oauthAccessToken,oauthRefreshToken:r?void 0:t.oauthRefreshToken,profileAuth:r?void 0:t.profileAuth}}getHostUrl(){if(this.webUrl)return this.webUrl;if((t=>{let e=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return"localhost"===e||"127.0.0.1"===e||"::1"===e})(this.apiUrl))return this.webUrl="http://localhost:3000",this.webUrl;if(this.apiUrl.endsWith("/api/v1"))return this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl;if(this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api"))return this.webUrl=this.apiUrl.replace("/api",""),this.webUrl;if(this.apiUrl.split(".",1)[0].includes("dev"))return this.webUrl="https://dev.smith.langchain.com",this.webUrl;else if(this.apiUrl.split(".",1)[0].includes("eu"))return this.webUrl="https://eu.smith.langchain.com",this.webUrl;else if(this.apiUrl.split(".",1)[0].includes("aws"))return this.webUrl="https://aws.smith.langchain.com",this.webUrl;else if(this.apiUrl.split(".",1)[0].includes("apac"))return this.webUrl="https://apac.smith.langchain.com",this.webUrl;else if(this.apiUrl.split(".",1)[0].includes("beta"))return this.webUrl="https://beta.smith.langchain.com",this.webUrl;else return this.webUrl="https://smith.langchain.com",this.webUrl}get _mergedHeaders(){let t={"User-Agent":`langsmith-js/${h.Ls}`,...this._customHeaders};if(void 0!==this.apiKey)t["x-api-key"]=`${this.apiKey}`;else{let e=this.profileAuth?.currentAuthHeader();e&&(t[e.name]=e.value)}return this.workspaceId&&(t["x-tenant-id"]=this.workspaceId),t}get headers(){return this._customHeaders}set headers(t){this._customHeaders=t??{}}_getOpenAPIBaseUrl(){return this.apiUrl.endsWith("/v1")?this.apiUrl.slice(0,-3):this.apiUrl}
1_newOpenAPIClient(){let t=void 0===this.apiKey&&void 0===this.workspaceId?{"X-API-Key":null}:void 0,{method:e,headers:i,body:a,signal:r,...s}=this.fetchOptions;return new d.ER({apiKey:this.apiKey,tenantID:this.workspaceId,baseURL:this._getOpenAPIBaseUrl(),timeout:this.timeout_ms,fetch:this._fetch,fetchOptions:s,defaultHeaders:t})}_getPlatformEndpointPath(t){return"/v1"!==this.apiUrl.slice(-3)&&"/v1/"!==this.apiUrl.slice(-4)?`/v1/platform/${t}`:`/platform/${t}`}get onlineEvaluators(){return this.openAPIClient.onlineEvaluators}async processInputs(t){return!1===this.hideInputs?t:!0===this.hideInputs?{}:"function"==typeof this.hideInputs?this.hideInputs(t):t}async processOutputs(t){return!1===this.hideOutputs?t:!0===this.hideOutputs?{}:"function"==typeof this.hideOutputs?this.hideOutputs(t):t}async processMetadata(t){return!1===this.hideMetadata?t:!0===this.hideMetadata?{}:"function"==typeof this.hideMetadata?this.hideMetadata(t):t}_filterNewTokenEvents(t){return t&&0!==t.length?t.map(t=>{if("new_token"===t.name){let{kwargs:e,...i}=t;return i}return t}):t}async prepareRunCreateOrUpdateInputs(t){let e={...t};return void 0!==e.inputs&&(e.inputs=await this.processInputs(e.inputs)),void 0!==e.outputs&&(e.outputs=await this.processOutputs(e.outputs)),null!=e.extra&&"metadata"in e.extra&&(e.extra={...e.extra,metadata:await this.processMetadata(e.extra.metadata)}),void 0!==e.events&&(e.events=this._filterNewTokenEvents(e.events)),e}async _getResponse(t,e){let i=e?.toString()??"",a=`${this.apiUrl}${t}?${i}`;return await this.caller.call(async()=>{let e=await this._fetch(a,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(e,`fetch ${t}`),e})}async _get(t,e){return(await this._getResponse(t,e)).json()}async *_getPaginated(t,e=new URLSearchParams,i){let a=Number(e.get("offset"))||0,r=Number(e.get("limit"))||100;for(;;){e.set("offset",String(a)),e.set("limit",String(r));let s=`${this.apiUrl}${t}?${e}`,n=await this.caller.call(async()=>{let e=await this._fetch(s,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(e,`fetch ${t}`),e}),o=i?i(await n.json()):await n.json();if(0===o.length||(yield o,o.length<r))break;a+=o.length}}async *_getCursorPaginatedList(t,e=null,i="POST",a="runs"){let r=e?{...e}:{};for(;;){let e=JSON.stringify(r),s=await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${t}`,{method:i,headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await (0,f.gJ)(a,`fetch ${t}`),a}),n=await s.json();if(!n||!n[a])break;yield n[a];let o=n.cursors;if(!o||!o.next)break;r.cursor=o.next}}_shouldSample(){return void 0===this.tracingSampleRate||Math.random()<this.tracingSampleRate}_filterForSampling(t,e=!1){if(void 0===this.tracingSampleRate)return t;if(e){let e=[];for(let i of t)this.filteredPostUuids.has(i.trace_id)?i.id===i.trace_id&&this.filteredPostUuids.delete(i.trace_id):e.push(i);return e}{let e=[];for(let i of t){let t=i.trace_id??i.id;this.filteredPostUuids.has(t)||(i.id===t?this._shouldSample()?e.push(i):this.filteredPostUuids.add(t):e.push(i))}return e}}async _getBatchSizeLimitBytes(){let t=await this._ensureServerInfo();return this.batchSizeBytesLimit??t?.batch_ingest_config?.size_limit_bytes??0x1800000}async _getBatchSizeLimit(){let t=await this._ensureServerInfo();return this.batchSizeLimit??t?.batch_ingest_config?.size_limit??100}async _getDatasetExamplesMultiPartSupport(){let t=await this._ensureServerInfo();return t.instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:t,batchSizeLimit:e}){let i=[];for(;this.autoBatchQueue.items.length>0;){let[a,r]=this.autoBatchQueue.pop({upToSizeBytes:t,upToSize:e});if(!a.length){r();break}let s=a.reduce((t,e)=>{let i=e.apiUrl??this.apiUrl,a=e.apiKey??this.apiKey,r=e.apiKey===this.apiKey&&e.apiUrl===this.apiUrl?"default":`${i}|${a}`;return t[r]||(t[r]=[]),t[r].push(e),t},{}),n=[];for(let[t,e]of Object.entries(s)){let i=this._processBatch(e,{apiUrl:"default"===t?void 0:t.split("|")[0],apiKey:"default"===t?void 0:t.split("|")[1]});n.push(i)}
1let o=Promise.all(n).finally(r);i.push(o)}return Promise.all(i)}static async _writeTraceToFallbackDir(t,e,i,r,s){try{let n="string"==typeof e?S.from(e,"utf8"):S.from(e),o=JSON.stringify({version:1,endpoint:r,headers:i,body_base64:n.toString("base64")}),l=`trace_${Date.now()}_${a.v4().slice(0,8)}.json`,h=_.Ae.join(t,l);if(j._fallbackDirsCreated.has(t)||(await _.Ck(t),j._fallbackDirsCreated.add(t)),void 0!==s&&s>0)try{let e=(await _.Cy(t)).filter(t=>t.startsWith("trace_")&&t.endsWith(".json")),i=0;for(let a of e){let{size:e}=await _.dJ(_.Ae.join(t,a));i+=e}if(i>=s)return void console.warn(`Could not write trace to fallback dir ${t} as it's already over size limit (${i} bytes >= ${s} bytes). Increase LANGSMITH_FAILED_TRACES_MAX_MB if possible.`)}catch{}await _.Zf(h,o),console.warn(`LangSmith trace upload failed; data saved to ${h} for later replay.`)}catch(e){console.error(`LangSmith tracing error: could not write trace to fallback dir ${t}:`,e)}}async _processBatch(t,e){if(!t.length)return;let i=t.reduce((t,e)=>t+(e.size??0),0);try{if(void 0!==this.langSmithToOTELTranslator)this._sendBatchToOTELTranslator(t);else{let a={runCreates:t.filter(t=>"create"===t.action).map(t=>t.item),runUpdates:t.filter(t=>"update"===t.action).map(t=>t.item)},r=await this._ensureServerInfo();if(!this._multipartDisabled&&(r?.batch_ingest_config?.use_multipart_endpoint??!0)){let t=!this._runCompressionDisabled&&r?.instance_flags?.gzip_body_enabled;try{await this.multipartIngestRuns(a,{...e,useGzip:t,sizeBytes:i})}catch(t){if((0,f.xJ)(t))this._multipartDisabled=!0,await this.batchIngestRuns(a,{...e,sizeBytes:i});else throw t}}else await this.batchIngestRuns(a,{...e,sizeBytes:i})}}catch(t){console.error("Error exporting batch:",t)}}_sendBatchToOTELTranslator(t){if(void 0!==this.langSmithToOTELTranslator){let e=new Map,i=[];for(let a of t)a.item.id&&a.otelContext&&(e.set(a.item.id,a.otelContext),"create"===a.action?i.push({operation:"post",id:a.item.id,trace_id:a.item.trace_id??a.item.id,run:a.item}):i.push({operation:"patch",id:a.item.id,trace_id:a.item.trace_id??a.item.id,run:a.item}));this.langSmithToOTELTranslator.exportBatch(i,e)}}async processRunOperation(t){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,t.item=P(t.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);let e=this.autoBatchQueue.push(t);if(this.manualFlushMode)return e;let i=await this._getBatchSizeLimitBytes(),a=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>i||this.autoBatchQueue.items.length>a)&&this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:i,batchSizeLimit:a})),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:i,batchSizeLimit:a}))},this.autoBatchAggregationDelayMs)),e}async _getServerInfo(){let t=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(1e4),...this.fetchOptions});return await (0,f.gJ)(t,"get server info"),t}),e=await t.json();return this.debug&&console.log("\n=== LangSmith Server Configuration ===\n"+JSON.stringify(e,null,2)+"\n"),e}async _ensureServerInfo(){return void 0===this._getServerInfoPromise&&(this._getServerInfoPromise=(async()=>{if(void 0===this._serverInfo)try{this._serverInfo=await this._getServerInfo(),this._serverInfo?.version&&function(t,e=p.U){let i=t=>t.split(".").map(t=>parseInt(t,10)),[a,r,s]=i(t),[n,o,l]=i(e);if(isNaN(a)||isNaN(r)||isNaN(s)||isNaN(n)||isNaN(o)||isNaN(l))return console.warn(`[LANGSMITH]: Could not parse backend version ${JSON.stringify(t)} for compatibility check.`);(a<n||a===n&&r<o||a===n&&r===o&&s<l)&&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.`)}(this._serverInfo.version)}catch(t){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${t.status??"Unspecified status code"} ${t.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(t=>(void 0===this._serverInfo&&(this._getServerInfoPromise=void 0),t))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let t=await this._getBatchSizeLimitBytes(),e=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:t,batchSizeLimit:e})}_cloneCurrentOTELContext(){let t=(0,s.sW)(),e=(0,s.wb)();if(void 0!==this.langSmithToOTELTranslator){let i=t.getActiveSpan();if(i)return t.setSpan(e.active(),i)}}
1async createRun(t,e){if(!this._filterForSampling([t]).length)return;let i={...this._mergedHeaders,"Content-Type":"application/json"},a=t.project_name;delete t.project_name;let r=await this.prepareRunCreateOrUpdateInputs({session_name:a,...t,start_time:t.start_time??Date.now()});if(this.autoBatchTracing&&void 0!==r.trace_id&&void 0!==r.dotted_order){let t=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:r,otelContext:t,apiKey:e?.apiKey,apiUrl:e?.apiUrl}).catch(console.error);return}let s=P(r,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);e?.apiKey!==void 0&&(i["x-api-key"]=e.apiKey),e?.workspaceId!==void 0&&(i["x-tenant-id"]=e.workspaceId);let n=(0,b.l)(s,`Creating run with id: ${s.id}`);await this.caller.call(async()=>{let t=await this._fetch(`${e?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:i,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await (0,f.gJ)(t,"create run",!0),t})}async batchIngestRuns({runCreates:t,runUpdates:e},i){if(void 0===t&&void 0===e)return;let a=await Promise.all(t?.map(t=>this.prepareRunCreateOrUpdateInputs(t))??[]),r=await Promise.all(e?.map(t=>this.prepareRunCreateOrUpdateInputs(t))??[]);if(a.length>0&&r.length>0){let t=a.reduce((t,e)=>(e.id&&(t[e.id]=e),t),{}),e=[];for(let i of r)void 0!==i.id&&t[i.id]?t[i.id]={...t[i.id],...i}:e.push(i);a=Object.values(t),r=e}let s={post:a,patch:r};if(!s.post.length&&!s.patch.length)return;let n={post:[],patch:[]};for(let t of["post","patch"]){let e=s[t].reverse(),i=e.pop();for(;void 0!==i;)n[t].push(i),i=e.pop()}if(n.post.length>0||n.patch.length>0){let t=n.post.map(t=>t.id).concat(n.patch.map(t=>t.id)).join(",");await this._postBatchIngestRuns(await this._serializeBody(n,`Ingesting runs with ids: ${t}`),i)}}async _postBatchIngestRuns(t,e){let i={...this._mergedHeaders,"Content-Type":"application/json",Accept:"application/json"};e?.apiKey!==void 0&&(i["x-api-key"]=e.apiKey),await this.batchIngestCaller.callWithOptions({sizeBytes:e?.sizeBytes},async()=>{let a=await this._fetch(`${e?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:i,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:t});return await (0,f.gJ)(a,"batch create run",!0),a})}async multipartIngestRuns({runCreates:t,runUpdates:e},i){if(void 0===t&&void 0===e)return;let a={},r=[];for(let e of t??[]){let t=await this.prepareRunCreateOrUpdateInputs(e);void 0!==t.id&&void 0!==t.attachments&&(a[t.id]=t.attachments),delete t.attachments,r.push(t)}let s=[];for(let t of e??[])s.push(await this.prepareRunCreateOrUpdateInputs(t));if(void 0!==r.find(t=>void 0===t.trace_id||void 0===t.dotted_order))throw Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(void 0!==s.find(t=>void 0===t.trace_id||void 0===t.dotted_order))throw Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(r.length>0&&s.length>0){let t=r.reduce((t,e)=>(e.id&&(t[e.id]=e),t),{}),e=[];for(let i of s)void 0!==i.id&&t[i.id]?t[i.id]={...t[i.id],...i}:e.push(i);r=Object.values(t),s=e}if(0===r.length&&0===s.length)return;let n=[],o=[];for(let[t,e]of[["post",r],["patch",s]])for(let i of e){let{inputs:e,outputs:r,events:s,extra:l,error:h,serialized:d,attachments:u,...c}=i,p={inputs:e,outputs:r,events:s,extra:l,error:h,serialized:d},m=await this._serializeBody(c,`Serializing for multipart ingestion of run with id: ${c.id}`);for(let[e,i]of(o.push({name:`${t}.${c.id}`,payload:new Blob([m],{type:`application/json; length=${m.length}`})}),Object.entries(p))){if(void 0===i)continue;let a=await this._serializeBody(i,`Serializing ${e} for multipart ingestion of run with id: ${c.id}`);o.push({name:`${t}.${c.id}.${e}`,payload:new Blob([a],{type:`application/json; length=${a.length}`})})}if(void 0!==c.id){let t=a[c.id];if(t)for(let[e,i]of(delete a[c.id],Object.entries(t))){let t,a;if(Array.isArray(i)?[t,a]=i:(t=i.mimeType,a=i.data),e.includes(".")){console.warn(`Skipping attachment '${e}' for run ${c.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}o.push({name:`attachment.${c.id}.${e}`,payload:new Blob([a],{type:`${t}; length=${a.byteLength}`})})}}n.push(`trace=${c.trace_id},id=${c.id}`)}
1await this._sendMultipartRequest(o,n.join("; "),i)}async _createNodeFetchBody(t,e){let i=[];for(let a of t)i.push(new Blob([`--${e}\r
2`])),i.push(new Blob([`Content-Disposition: form-data; name="${a.name}"\r
3`,`Content-Type: ${a.payload.type}\r
4\r
5`])),i.push(a.payload),i.push(new Blob(["\r\n"]));i.push(new Blob([`--${e}--\r
6`]));let a=new Blob(i);return await a.arrayBuffer()}async _createMultipartStream(t,e){let i=new TextEncoder;return new ReadableStream({async start(a){let r=async t=>{"string"==typeof t?a.enqueue(i.encode(t)):a.enqueue(t)};for(let i of t){await r(`--${e}\r
7`),await r(`Content-Disposition: form-data; name="${i.name}"\r
8`),await r(`Content-Type: ${i.payload.type}\r
9\r
10`);let t=i.payload.stream().getReader();try{let e;for(;!(e=await t.read()).done;)a.enqueue(e.value)}finally{t.releaseLock()}await r("\r\n")}await r(`--${e}--\r
11`),a.close()}})}async _sendMultipartRequest(t,e,i){let a="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),r=()=>this._createNodeFetchBody(t,a),s=()=>this._createMultipartStream(t,a),n=async t=>this.batchIngestCaller.callWithOptions({sizeBytes:i?.sizeBytes},async()=>{let e=await t(),r={...this._mergedHeaders,"Content-Type":`multipart/form-data; boundary=${a}`};i?.apiKey!==void 0&&(r["x-api-key"]=i.apiKey);let s=e;i?.useGzip&&"object"==typeof e&&"pipeThrough"in e&&(s=e.pipeThrough(new CompressionStream("gzip")),r["Content-Encoding"]="gzip");let n=await this._fetch(`${i?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:r,body:s,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(n,"Failed to send multipart request",!0),n});try{let t,a=!1;(0,w.xb)()&&!this.multipartStreamingDisabled&&"bun"!==(0,l._$)()?(a=!0,t=await n(s)):t=await n(r),(!this.multipartStreamingDisabled||a)&&422===t.status&&(i?.apiUrl??this.apiUrl)!==y.rK&&(console.warn(`Streaming multipart upload to ${i?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${e}".`),this.multipartStreamingDisabled=!0,t=await n(r))}catch(i){if((0,f.xJ)(i))throw i;if(console.warn(`${i.message.trim()}
12
13Context: ${e}`),this.failedTracesDir){let e=await this._createNodeFetchBody(t,a).catch(()=>null);e&&await j._writeTraceToFallbackDir(this.failedTracesDir,e,{"Content-Type":`multipart/form-data; boundary=${a}`},"runs/multipart",this.failedTracesMaxBytes)}}}async updateRun(t,e,i){(0,u.AD)(t),e.inputs&&(e.inputs=await this.processInputs(e.inputs)),e.outputs&&(e.outputs=await this.processOutputs(e.outputs)),null!=e.extra&&"metadata"in e.extra&&(e.extra={...e.extra,metadata:await this.processMetadata(e.extra.metadata)}),e.events&&(e.events=this._filterNewTokenEvents(e.events));let a={...e,id:t};if(!this._filterForSampling([a],!0).length)return;if(this.autoBatchTracing&&void 0!==a.trace_id&&void 0!==a.dotted_order){let t=this._cloneCurrentOTELContext();return void 0!==e.end_time&&void 0===a.parent_run_id&&this.blockOnRootRunFinalization&&!this.manualFlushMode?void await this.processRunOperation({action:"update",item:a,otelContext:t,apiKey:i?.apiKey,apiUrl:i?.apiUrl}).catch(console.error):void this.processRunOperation({action:"update",item:a,otelContext:t,apiKey:i?.apiKey,apiUrl:i?.apiUrl}).catch(console.error)}let r={...this._mergedHeaders,"Content-Type":"application/json"};i?.apiKey!==void 0&&(r["x-api-key"]=i.apiKey),i?.workspaceId!==void 0&&(r["x-tenant-id"]=i.workspaceId);let s=(0,b.l)(e,`Serializing payload to update run with id: ${t}`);await this.caller.call(async()=>{let e=await this._fetch(`${i?.apiUrl??this.apiUrl}/runs/${t}`,{method:"PATCH",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await (0,f.gJ)(e,"update run",!0),e})}async readRun(t,{loadChildRuns:e}={loadChildRuns:!1}){(0,u.AD)(t);let i=O(await this._get(`/runs/${t}`));return e&&(i=await this._loadChildRuns(i)),i}async getRunUrl({runId:t,run:e,projectOpts:i}){if(void 0!==e){let t;t=e.session_id?e.session_id:i?.projectName?(await this.readProject({projectName:i?.projectName})).id:i?.projectId?i?.projectId:(await this.readProject({projectName:(0,l.Jz)("PROJECT")||"default"})).id;let a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${t}/r/${e.id}?poll=true`}if(void 0!==t){let e=await this.readRun(t);if(!e.app_path)throw Error(`Run ${t} has no app_path`);let i=this.getHostUrl();return`${i}${e.app_path}`}
13throw Error("Must provide either runId or run")}async _loadChildRuns(t){let e=await A(this.listRuns({isRoot:!1,projectId:t.session_id,traceId:t.trace_id})),i={},a={};for(let r of(e.sort((t,e)=>(t?.dotted_order??"").localeCompare(e?.dotted_order??"")),e)){if(null===r.parent_run_id||void 0===r.parent_run_id)throw Error(`Child run ${r.id} has no parent`);r.dotted_order?.startsWith(t.dotted_order??"")&&r.id!==t.id&&(r.parent_run_id in i||(i[r.parent_run_id]=[]),i[r.parent_run_id].push(r),a[r.id]=r)}for(let e in t.child_runs=i[t.id]||[],i)e!==t.id&&(a[e].child_runs=i[e]);return t}async *listRuns(t){let{projectId:e,projectName:i,parentRunId:a,traceId:r,referenceExampleId:s,startTime:n,executionOrder:o,isRoot:l,runType:h,error:d,id:u,query:p,filter:m,traceFilter:f,treeFilter:g,limit:_,select:w,order:y}=t,b=[];if(e&&(b=Array.isArray(e)?e:[e]),i){let t=Array.isArray(i)?i:[i],e=await Promise.all(t.map(t=>this.readProject({projectName:t}).then(t=>t.id)));b.push(...e)}let v={session:b.length?b:null,run_type:h,reference_example:s,query:p,filter:m,trace_filter:f,tree_filter:g,execution_order:o,parent_run:a,start_time:n?n.toISOString():null,error:d,id:u,limit:_,trace:r,select:w||["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"],is_root:l,order:y};v.select.includes("child_run_ids")&&(0,c.m)("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let S=0;for await(let t of this._getCursorPaginatedList("/runs/query",v)){let e=t.map(O);if(_){if(S>=_)break;if(e.length+S>_){let t=e.slice(0,_-S);yield*t;break}S+=e.length,yield*e}else yield*e}}async *listGroupRuns(t){let{projectId:e,projectName:i,groupBy:a,filter:r,startTime:s,endTime:n,limit:o,offset:l}=t,h={session_id:e||(await this.readProject({projectName:i})).id,group_by:a,filter:r,start_time:s?s.toISOString():null,end_time:n?n.toISOString():null,limit:Number(o)||100},d=Number(l)||0,u="/runs/group",c=`${this.apiUrl}${u}`;for(;;){let t=JSON.stringify(Object.fromEntries(Object.entries({...h,offset:d}).filter(([t,e])=>void 0!==e))),e=await this.caller.call(async()=>{let e=await this._fetch(c,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:t});return await (0,f.gJ)(e,`Failed to fetch ${u}`),e}),{groups:i,total:a}=await e.json();if(0===i.length)break;for(let t of i)yield t;if((d+=i.length)>=a)break}}async *readThread(t){let{threadId:e,projectId:i,projectName:a,isRoot:r=!0,limit:s,filter:n,order:o="asc"}=t;if(!i&&!a)throw Error("threadId requires projectId or projectName");let l=`eq(thread_id, ${JSON.stringify(e)})`,h=n?`and(${l}, ${n})`:l;yield*this.listRuns({projectId:i??void 0,projectName:a??void 0,isRoot:r,limit:s,filter:h,order:o})}async listThreads(t){let{projectId:e,projectName:i,limit:a,offset:r=0,filter:s,startTime:n,isRoot:o=!0}=t;if(!e&&!i)throw Error("Either projectId or projectName must be provided");if(e&&i)throw Error("Provide exactly one of projectId or projectName");let l=e??(await this.readProject({projectName:i})).id,h={session:[l],is_root:o,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:(n??new Date(Date.now()-864e5)).toISOString()};null!=s&&(h.filter=s);let d=new Map;for await(let t of this._getCursorPaginatedList("/runs/query",h))for(let e of t){let t=O(e),i=t.thread_id;if(i){let e=d.get(i)??[];e.push(t),d.set(i,e)}}let u=[];for(let[t,e]of d.entries()){e.sort((t,e)=>{let i=t.start_time??"",a=e.start_time??"";if(i!==a)return i.localeCompare(a);let r=t.dotted_order??"",s=e.dotted_order??"";return r.localeCompare(s)});let i=[...e.map(t=>
13t.start_time).filter(Boolean)].sort(),a=i.length?i[0]:"",r=i.length?i[i.length-1]:"";u.push({thread_id:t,runs:e,count:e.length,filter:"",total_tokens:0,total_cost:null,min_start_time:a,max_start_time:r,latency_p50:0,latency_p99:0,feedback_stats:null,first_inputs:"",last_outputs:"",last_error:null})}u.sort((t,e)=>{let i=t.max_start_time??"";return(e.max_start_time??"").localeCompare(i)});let c=r>0?u.slice(r):u;return void 0!==a?c.slice(0,a):c}async getRunStats({id:t,trace:e,parentRun:i,runType:a,projectNames:r,projectIds:s,referenceExampleIds:n,startTime:o,endTime:l,error:h,query:d,filter:u,traceFilter:c,treeFilter:p,isRoot:m,dataSourceType:g}){let _=s||[];r&&(_=[...s||[],...await Promise.all(r.map(t=>this.readProject({projectName:t}).then(t=>t.id)))]);let w=JSON.stringify(Object.fromEntries(Object.entries({id:t,trace:e,parent_run:i,run_type:a,session:_,reference_example:n,start_time:o,end_time:l,error:h,query:d,filter:u,trace_filter:c,tree_filter:p,is_root:m,data_source_type:g}).filter(([t,e])=>void 0!==e))),y=await this.caller.call(async()=>{let t=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:w});return await (0,f.gJ)(t,"get run stats"),t});return await y.json()}async shareRun(t,{shareId:e}={}){let i={run_id:t,share_token:e||a.v4()};(0,u.AD)(t);let r=JSON.stringify(i),s=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/runs/${t}/share`,{method:"PUT",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await (0,f.gJ)(e,"share run"),e}),n=await s.json();if(null===n||!("share_token"in n))throw Error("Invalid response from server");return`${this.getHostUrl()}/public/${n.share_token}/r`}async unshareRun(t){(0,u.AD)(t),await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/runs/${t}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(e,"unshare run",!0),e})}async readRunSharedLink(t){(0,u.AD)(t);let e=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/runs/${t}/share`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(e,"read run shared link"),e}),i=await e.json();if(null!==i&&"share_token"in i)return`${this.getHostUrl()}/public/${i.share_token}/r`}async listSharedRuns(t,{runIds:e}={}){let i=new URLSearchParams({share_token:t});if(void 0!==e)for(let t of e)i.append("id",t);(0,u.AD)(t);let a=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/public/${t}/runs${i}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(e,"list shared runs"),e});return(await a.json()).map(O)}async readDatasetSharedSchema(t,e){if(!t&&!e)throw Error("Either datasetId or datasetName must be given");t||(t=(await this.readDataset({datasetName:e})).id),(0,u.AD)(t);let i=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets/${t}/share`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(e,"read dataset shared schema"),e}),a=await i.json();return a.url=`${this.getHostUrl()}/public/${a.share_token}/d`,a}async shareDataset(t,e){if(!t&&!e)throw Error("Either datasetId or datasetName must be given");t||(t=(await this.readDataset({datasetName:e})).id);let i={dataset_id:t};(0,u.AD)(t);let a=JSON.stringify(i),r=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets/${t}/share`,{method:"PUT",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await (0,f.gJ)(e,"share dataset"),e}),s=await r.json();return s.url=`${this.getHostUrl()}/public/${s.share_token}/d`,s}async unshareDataset(t){(0,u.AD)(t),await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets/${t}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(e,"unshare dataset",!0),e})}async readSharedDataset(t){(0,u.AD)(t);let e=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/public/${t}/datasets`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(e,"read shared dataset"),e});return await e.json()}async listSharedExamples(t,e){let i={};e?.exampleIds&&(i.id=e.exampleIds);let a=new URLSearchParams;
13Object.entries(i).forEach(([t,e])=>{Array.isArray(e)?e.forEach(e=>a.append(t,e)):a.append(t,e)});let r=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/public/${t}/examples?${a.toString()}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(e,"list shared examples"),e}),s=await r.json();if(!r.ok){if("detail"in s)throw Error(`Failed to list shared examples.
14Status: ${r.status}
15Message: ${Array.isArray(s.detail)?s.detail.join("\n"):"Unspecified error"}`);throw Error(`Failed to list shared examples: ${r.status} ${r.statusText}`)}return s.map(t=>({...t,_hostUrl:this.getHostUrl()}))}async createProject({projectName:t,description:e=null,metadata:i=null,upsert:a=!1,projectExtra:r=null,referenceDatasetId:s=null,numExamples:n=null,numRepetitions:o=null,evaluatorKeys:l=null}){let h=`${this.apiUrl}/sessions${a?"?upsert=true":""}`,d=r||{};i&&(d.metadata=i);let u={name:t,extra:d,description:e};null!==s&&(u.reference_dataset_id=s),null!=n&&(u.num_examples=n),null!=o&&(u.num_repetitions=o),null!=l&&l.length>0&&(u.evaluator_keys=l);let c=JSON.stringify(u),p=await this.caller.call(async()=>{let t=await this._fetch(h,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await (0,f.gJ)(t,"create project"),t});return await p.json()}async updateProject(t,{name:e=null,description:i=null,metadata:a=null,projectExtra:r=null,endTime:s=null}){let n=`${this.apiUrl}/sessions/${t}`,o=r;a&&(o={...o||{},metadata:a});let l=JSON.stringify({name:e,extra:o,description:i,end_time:s?new Date(s).toISOString():null}),h=await this.caller.call(async()=>{let t=await this._fetch(n,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await (0,f.gJ)(t,"update project"),t});return await h.json()}async hasProject({projectId:t,projectName:e}){let i="/sessions",a=new URLSearchParams;if(void 0!==t&&void 0!==e)throw Error("Must provide either projectName or projectId, not both");if(void 0!==t)(0,u.AD)(t),i+=`/${t}`;else if(void 0!==e)a.append("name",e);else throw Error("Must provide projectName or projectId");let r=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}${i}?${a}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(t,"has project"),t});try{let t=await r.json();if(!r.ok)return!1;if(Array.isArray(t))return t.length>0;return!0}catch(t){return!1}}async readProject({projectId:t,projectName:e,includeStats:i}){let a,r="/sessions",s=new URLSearchParams;if(void 0!==t&&void 0!==e)throw Error("Must provide either projectName or projectId, not both");if(void 0!==t)(0,u.AD)(t),r+=`/${t}`;else if(void 0!==e)s.append("name",e);else throw Error("Must provide projectName or projectId");void 0!==i&&s.append("include_stats",i.toString());let n=await this._get(r,s);if(Array.isArray(n)){if(0===n.length)throw Error(`Project[id=${t}, name=${e}] not found`);a=n[0]}else a=n;return a}async getProjectUrl({projectId:t,projectName:e}){if(void 0===t&&void 0===e)throw Error("Must provide either projectName or projectId");let i=await this.readProject({projectId:t,projectName:e}),a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${i.id}`}async getDatasetUrl({datasetId:t,datasetName:e}){if(void 0===t&&void 0===e)throw Error("Must provide either datasetName or datasetId");let i=await this.readDataset({datasetId:t,datasetName:e}),a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/datasets/${i.id}`}async _getTenantId(){if(null!==this._tenantId)return this._tenantId;let t=new URLSearchParams({limit:"1"});for await(let e of this._getPaginated("/sessions",t))return this._tenantId=e[0].tenant_id,e[0].tenant_id;throw Error("No projects found to resolve tenant.")}async *listProjects({projectIds:t,name:e,nameContains:i,referenceDatasetId:a,referenceDatasetName:r,includeStats:s,datasetVersion:n,referenceFree:o,metadata:l}={}){let h=new URLSearchParams;if(void 0!==t)for(let e of t)h.append("id",e);if(void 0!==e&&h.append("name",e),void 0!==i&&h.append("name_contains",i),void 0!==a)h.append("reference_dataset",a);else if(void 0!==r){let t=await this.readDataset({datasetName:r});h.append("reference_dataset",t.id)}for await(let t of(void 0!==s&&h.append("include_stats",s.toString()),void 0!==n&&h.append("dataset_version",n),void 0!==o&&h.append("reference_free",o.toString()),void 0!==l&&h.append("metadata",JSON.stringify(l)),this._getPaginated("/sessions",h)))yield*t}async deleteProject({projectId:t,projectName:e}){let i;
15if(void 0===t&&void 0===e)throw Error("Must provide projectName or projectId");if(void 0!==t&&void 0!==e)throw Error("Must provide either projectName or projectId, not both");i=void 0===t?(await this.readProject({projectName:e})).id:t,(0,u.AD)(i),await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/sessions/${i}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(t,`delete session ${i} (${e})`,!0),t})}async uploadCsv({csvFile:t,fileName:e,inputKeys:i,outputKeys:a,description:r,dataType:s,name:n}){let o=`${this.apiUrl}/datasets/upload`,l=new FormData,h=new Blob([t],{type:"text/csv"});l.append("file",h,e),i.forEach(t=>{l.append("input_keys",t)}),a.forEach(t=>{l.append("output_keys",t)}),r&&l.append("description",r),s&&l.append("data_type",s),n&&l.append("name",n);let d=await this.caller.call(async()=>{let t=await this._fetch(o,{method:"POST",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await (0,f.gJ)(t,"upload CSV"),t});return await d.json()}async createDataset(t,{description:e,dataType:i,inputsSchema:a,outputsSchema:r,metadata:s}={}){let n={name:t,description:e,extra:{source:"sdk",...s?{metadata:s}:{}}};i&&(n.data_type=i),a&&(n.inputs_schema_definition=a),r&&(n.outputs_schema_definition=r);let o=JSON.stringify(n),l=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await (0,f.gJ)(t,"create dataset"),t});return await l.json()}async readDataset({datasetId:t,datasetName:e}){let i,a="/datasets",r=new URLSearchParams({limit:"1"});if(t&&e)throw Error("Must provide either datasetName or datasetId, not both");if(t)(0,u.AD)(t),a+=`/${t}`;else if(e)r.append("name",e);else throw Error("Must provide datasetName or datasetId");let s=await this._get(a,r);if(Array.isArray(s)){if(0===s.length)throw Error(`Dataset[id=${t}, name=${e}] not found`);i=s[0]}else i=s;return i}async hasDataset({datasetId:t,datasetName:e}){try{return await this.readDataset({datasetId:t,datasetName:e}),!0}catch(t){if(t instanceof Error&&t.message.toLocaleLowerCase().includes("not found"))return!1;throw t}}async diffDatasetVersions({datasetId:t,datasetName:e,fromVersion:i,toVersion:a}){let r=t;if(void 0===r&&void 0===e)throw Error("Must provide either datasetName or datasetId");if(void 0!==r&&void 0!==e)throw Error("Must provide either datasetName or datasetId, not both");void 0===r&&(r=(await this.readDataset({datasetName:e})).id);let s=new URLSearchParams({from_version:"string"==typeof i?i:i.toISOString(),to_version:"string"==typeof a?a:a.toISOString()});return await this._get(`/datasets/${r}/versions/diff`,s)}async readDatasetOpenaiFinetuning({datasetId:t,datasetName:e}){if(void 0!==t);else if(void 0!==e)t=(await this.readDataset({datasetName:e})).id;else throw Error("Must provide either datasetName or datasetId");let i=await this._getResponse(`/datasets/${t}/openai_ft`);return(await i.text()).trim().split("\n").map(t=>JSON.parse(t))}async *listDatasets({limit:t=100,offset:e=0,datasetIds:i,datasetName:a,datasetNameContains:r,metadata:s}={}){let n=new URLSearchParams({limit:t.toString(),offset:e.toString()});if(void 0!==i)for(let t of i)n.append("id",t);for await(let t of(void 0!==a&&n.append("name",a),void 0!==r&&n.append("name_contains",r),void 0!==s&&n.append("metadata",JSON.stringify(s)),this._getPaginated("/datasets",n)))yield*t}async updateDataset(t){let{datasetId:e,datasetName:i,...a}=t;if(!e&&!i)throw Error("Must provide either datasetName or datasetId");
15let r=e??(await this.readDataset({datasetName:i})).id;(0,u.AD)(r);let s=JSON.stringify(a),n=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/datasets/${r}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await (0,f.gJ)(t,"update dataset"),t});return await n.json()}async updateDatasetTag(t){let{datasetId:e,datasetName:i,asOf:a,tag:r}=t;if(!e&&!i)throw Error("Must provide either datasetName or datasetId");let s=e??(await this.readDataset({datasetName:i})).id;(0,u.AD)(s);let n=JSON.stringify({as_of:"string"==typeof a?a:a.toISOString(),tag:r});await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/datasets/${s}/tags`,{method:"PUT",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await (0,f.gJ)(t,"update dataset tags",!0),t})}async deleteDataset({datasetId:t,datasetName:e}){let i="/datasets",a=t;if(void 0!==t&&void 0!==e)throw Error("Must provide either datasetName or datasetId, not both");if(void 0!==e&&(a=(await this.readDataset({datasetName:e})).id),void 0!==a)(0,u.AD)(a),i+=`/${a}`;else throw Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{let t=await this._fetch(this.apiUrl+i,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(t,`delete ${i}`,!0),t})}async createExample(t,e,i){let r;if(k(t)&&(void 0!==e||void 0!==i))throw Error("Cannot provide outputs or options when using ExampleCreate object");let s=e?i?.datasetId:t.dataset_id,n=e?i?.datasetName:t.dataset_name;if(void 0===s&&void 0===n)throw Error("Must provide either datasetName or datasetId");if(void 0!==s&&void 0!==n)throw Error("Must provide either datasetName or datasetId, not both");void 0===s&&(s=(await this.readDataset({datasetName:n})).id);let o=(e?i?.createdAt:t.created_at)||new Date;r=k(t)?t:{inputs:t,outputs:e,created_at:o?.toISOString(),id:i?.exampleId,metadata:i?.metadata,split:i?.split,source_run_id:i?.sourceRunId,use_source_run_io:i?.useSourceRunIO,use_source_run_attachments:i?.useSourceRunAttachments,attachments:i?.attachments};let l=await this._uploadExamplesMultipart(s,[r]);return await this.readExample(l.example_ids?.[0]??a.v4())}async createExamples(t){if(Array.isArray(t)){if(0===t.length)return[];let e=t[0].dataset_id,i=t[0].dataset_name;if(void 0===e&&void 0===i)throw Error("Must provide either datasetName or datasetId");if(void 0!==e&&void 0!==i)throw Error("Must provide either datasetName or datasetId, not both");void 0===e&&(e=(await this.readDataset({datasetName:i})).id);let a=await this._uploadExamplesMultipart(e,t);return await Promise.all(a.example_ids.map(t=>this.readExample(t)))}let{inputs:e,outputs:i,metadata:a,splits:r,sourceRunIds:s,useSourceRunIOs:n,useSourceRunAttachments:o,attachments:l,exampleIds:h,datasetId:d,datasetName:u}=t;if(void 0===e)throw Error("Must provide inputs when using legacy parameters");let c=d;if(void 0===c&&void 0===u)throw Error("Must provide either datasetName or datasetId");if(void 0!==c&&void 0!==u)throw Error("Must provide either datasetName or datasetId, not both");void 0===c&&(c=(await this.readDataset({datasetName:u})).id);let p=e.map((t,e)=>({dataset_id:c,inputs:t,outputs:i?.[e],metadata:a?.[e],split:r?.[e],id:h?.[e],attachments:l?.[e],source_run_id:s?.[e],use_source_run_io:n?.[e],use_source_run_attachments:o?.[e]})),m=await this._uploadExamplesMultipart(c,p);return await Promise.all(m.example_ids.map(t=>this.readExample(t)))}async createLLMExample(t,e,i){return this.createExample({input:t},{output:e},i)}async createChatExample(t,e,i){let a=t.map(t=>(0,o.$)(t)?(0,o.T)(t):t),r=(0,o.$)(e)?(0,o.T)(e):e;return this.createExample({input:a},{output:r},i)}async readExample(t){(0,u.AD)(t);let e=`/examples/${t}`,{attachment_urls:i,...a}=await this._get(e);return i&&(a.attachments=Object.entries(i).reduce((t,[e,i])=>(t[e.slice(11)]={presigned_url:i.presigned_url,mime_type:i.mime_type},t),{})),a}async *listExamples({datasetId:t,datasetName:e,exampleIds:i,asOf:a,splits:r,inlineS3Urls:s,metadata:n,limit:o,offset:l,filter:h,includeAttachments:d}={}){let u;
15if(void 0!==t&&void 0!==e)throw Error("Must provide either datasetName or datasetId, not both");if(void 0!==t)u=t;else if(void 0!==e)u=(await this.readDataset({datasetName:e})).id;else throw Error("Must provide a datasetName or datasetId");let c=new URLSearchParams({dataset:u}),p=a?"string"==typeof a?a:a?.toISOString():void 0;if(p&&c.append("as_of",p),c.append("inline_s3_urls",(s??!0).toString()),void 0!==i)for(let t of i)c.append("id",t);if(void 0!==r)for(let t of r)c.append("splits",t);if(void 0!==n){let t=JSON.stringify(n);c.append("metadata",t)}void 0!==o&&c.append("limit",o.toString()),void 0!==l&&c.append("offset",l.toString()),void 0!==h&&c.append("filter",h),!0===d&&["attachment_urls","outputs","metadata"].forEach(t=>c.append("select",t));let m=0;for await(let t of this._getPaginated("/examples",c)){for(let e of t){let{attachment_urls:t,...i}=e;t&&(i.attachments=Object.entries(t).reduce((t,[e,i])=>(t[e.slice(11)]={presigned_url:i.presigned_url,mime_type:i.mime_type||void 0},t),{})),yield i,m++}if(void 0!==o&&m>=o)break}}async deleteExample(t){(0,u.AD)(t);let e=`/examples/${t}`;await this.caller.call(async()=>{let t=await this._fetch(this.apiUrl+e,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(t,`delete ${e}`,!0),t})}async deleteExamples(t,e){if(t.forEach(t=>(0,u.AD)(t)),e?.hardDelete){let e=this._getPlatformEndpointPath("datasets/examples/delete");await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}${e}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},body:JSON.stringify({example_ids:t,hard_delete:!0}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(i,"hard delete examples",!0),i})}else{let e=new URLSearchParams;t.forEach(t=>e.append("example_ids",t)),await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/examples?${e.toString()}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(t,"delete examples",!0),t})}}async updateExample(t,e){let i,a,r;return i=e?t:t.id,(0,u.AD)(i),r=void 0!==(a=e?{id:i,...e}:t).dataset_id?a.dataset_id:(await this.readExample(i)).dataset_id,this._updateExamplesMultipart(r,[a])}async updateExamples(t){let e;return e=void 0===t[0].dataset_id?(await this.readExample(t[0].id)).dataset_id:t[0].dataset_id,this._updateExamplesMultipart(e,t)}async readDatasetVersion({datasetId:t,datasetName:e,asOf:i,tag:a}){let r;if(r=t||(await this.readDataset({datasetName:e})).id,(0,u.AD)(r),i&&a||!i&&!a)throw Error("Exactly one of asOf and tag must be specified.");let s=new URLSearchParams;void 0!==i&&s.append("as_of","string"==typeof i?i:i.toISOString()),void 0!==a&&s.append("tag",a);let n=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/datasets/${r}/version?${s.toString()}`,{method:"GET",headers:{...this._mergedHeaders},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(t,"read dataset version"),t});return await n.json()}async listDatasetSplits({datasetId:t,datasetName:e,asOf:i}){let a;if(void 0===t&&void 0===e)throw Error("Must provide dataset name or ID");if(void 0!==t&&void 0!==e)throw Error("Must provide either datasetName or datasetId, not both");a=void 0===t?(await this.readDataset({datasetName:e})).id:t,(0,u.AD)(a);let r=new URLSearchParams,s=i?"string"==typeof i?i:i?.toISOString():void 0;return s&&r.append("as_of",s),await this._get(`/datasets/${a}/splits`,r)}async updateDatasetSplits({datasetId:t,datasetName:e,splitName:i,exampleIds:a,remove:r=!1}){let s;if(void 0===t&&void 0===e)throw Error("Must provide dataset name or ID");if(void 0!==t&&void 0!==e)throw Error("Must provide either datasetName or datasetId, not both");s=void 0===t?(await this.readDataset({datasetName:e})).id:t,(0,u.AD)(s);let n=JSON.stringify({split_name:i,examples:a.map(t=>((0,u.AD)(t),t)),remove:r});await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/datasets/${s}/splits`,{method:"PUT",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await (0,f.gJ)(t,"update dataset splits",!0),t})}async createFeedback(t,e,{score:i,value:r,correction:s,comment:n,sourceInfo:o,feedbackSourceType:l="api",sourceRunId:h,feedbackId:d,feedbackConfig:c,projectId:p,comparativeExperimentId:m,sessionId:g,startTime:_,extendTraceRetention:w}){if(!t&&!p)throw Error("One of runId or projectId must be provided");
15if(t&&p)throw Error("Only one of runId or projectId can be provided");let y={type:l??"api",metadata:o??{}};void 0===h||y?.metadata===void 0||y.metadata.__run||(y.metadata.__run={run_id:h}),y?.metadata!==void 0&&y.metadata.__run?.run_id!==void 0&&(0,u.AD)(y.metadata.__run.run_id);let b={id:d??a.v7(),run_id:t,key:e,score:U(i),value:r,correction:s,comment:n,feedback_source:y,comparative_experiment_id:m,feedbackConfig:c,session_id:g??p,start_time:_,extend_trace_retention:w},v=JSON.stringify(b),S=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{let t=await this._fetch(S,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:v});return await (0,f.gJ)(t,"create feedback",!0),t}),b}async updateFeedback(t,{score:e,value:i,correction:a,comment:r}){let s={};null!=e&&(s.score=U(e)),null!=i&&(s.value=i),null!=a&&(s.correction=a),null!=r&&(s.comment=r),(0,u.AD)(t);let n=JSON.stringify(s);await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/feedback/${t}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await (0,f.gJ)(e,"update feedback",!0),e})}async readFeedback(t){(0,u.AD)(t);let e=`/feedback/${t}`;return await this._get(e)}async deleteFeedback(t){(0,u.AD)(t);let e=`/feedback/${t}`;await this.caller.call(async()=>{let t=await this._fetch(this.apiUrl+e,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(t,`delete ${e}`,!0),t})}async *listFeedback({runIds:t,feedbackKeys:e,feedbackSourceTypes:i}={}){let a=new URLSearchParams;if(t)for(let e of t)(0,u.AD)(e),a.append("run",e);if(e)for(let t of e)a.append("key",t);if(i)for(let t of i)a.append("source",t);for await(let t of this._getPaginated("/feedback",a))yield*t}async createPresignedFeedbackToken(t,e,{expiration:i,feedbackConfig:a}={}){let r={run_id:t,feedback_key:e,feedback_config:a};i?"string"==typeof i?r.expires_at=i:(i?.hours||i?.minutes||i?.days)&&(r.expires_in=i):r.expires_in={hours:3};let s=JSON.stringify(r),n=await this.caller.call(async()=>{let t=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:s});return await (0,f.gJ)(t,"create presigned feedback token"),t});return await n.json()}async createComparativeExperiment({name:t,experimentIds:e,referenceDatasetId:i,createdAt:a,description:r,metadata:s,id:n}){if(0===e.length)throw Error("At least one experiment is required");if(i||(i=(await this.readProject({projectId:e[0]})).reference_dataset_id),null==!i)throw Error("A reference dataset is required");let o={id:n,name:t,experiment_ids:e,reference_dataset_id:i,description:r,created_at:(a??new Date)?.toISOString(),extra:{}};s&&(o.extra.metadata=s);let l=JSON.stringify(o);return(await this.caller.call(async()=>{let t=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 (0,f.gJ)(t,"create comparative experiment"),t})).json()}async *listPresignedFeedbackTokens(t){(0,u.AD)(t);let e=new URLSearchParams({run_id:t});for await(let t of this._getPaginated("/feedback/tokens",e))yield*t}_selectEvalResults(t){return"results"in t?t.results:Array.isArray(t)?t:[t]}async _logEvaluationFeedback(t,e,i){let a=this._selectEvalResults(t),r=[];for(let t of a){let a=i||{};t.evaluatorInfo&&(a={...t.evaluatorInfo,...a});let s=null;t.targetRunId?s=t.targetRunId:e&&(s=e.id),r.push(await this.createFeedback(s,t.key,{score:t.score,value:t.value,comment:t.comment,correction:t.correction,sourceInfo:a,sourceRunId:t.sourceRunId,feedbackConfig:t.feedbackConfig,feedbackSourceType:"model",sessionId:e?.session_id,startTime:e?.start_time}))}return[a,r]}async logEvaluationFeedback(t,e,i){let[a]=await this._logEvaluationFeedback(t,e,i);return a}
15async createFeedbackConfig(t){let{feedbackKey:e,feedbackConfig:i,isLowerScoreBetter:a=!1}=t,r={feedback_key:e,feedback_config:i,is_lower_score_better:a};return(await this.caller.call(async()=>{let t=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(r)});return await (0,f.gJ)(t,"create feedback config"),t})).json()}async *listFeedbackConfigs(t={}){let{feedbackKeys:e,nameContains:i,limit:a}=t,r=new URLSearchParams;e&&e.forEach(t=>{r.append("key",t)}),i&&r.append("name_contains",i),r.append("limit",(void 0!==a?Math.min(a,100):100).toString());let s=0;for await(let t of this._getPaginated("/feedback-configs",r))if(yield*t,s+=t.length,void 0!==a&&s>=a)break}async updateFeedbackConfig(t,e={}){let{feedbackConfig:i,isLowerScoreBetter:a}=e,r={feedback_key:t};return void 0!==i&&(r.feedback_config=i),void 0!==a&&(r.is_lower_score_better=a),(await this.caller.call(async()=>{let t=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(r)});return await (0,f.gJ)(t,"update feedback config"),t})).json()}async deleteFeedbackConfig(t){let e=new URLSearchParams({feedback_key:t});await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/feedback-configs?${e}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(t,"delete feedback config",!0),t})}async *listAnnotationQueues(t={}){let{queueIds:e,name:i,nameContains:a,limit:r}=t,s=new URLSearchParams;e&&e.forEach((t,e)=>{(0,u.AD)(t,`queueIds[${e}]`),s.append("ids",t)}),i&&s.append("name",i),a&&s.append("name_contains",a),s.append("limit",(void 0!==r?Math.min(r,100):100).toString());let n=0;for await(let t of this._getPaginated("/annotation-queues",s))if(yield*t,n++,void 0!==r&&n>=r)break}async createAnnotationQueue(t){let{name:e,description:i,queueId:r,rubricInstructions:s,rubricItems:n}=t,o=JSON.stringify(Object.fromEntries(Object.entries({name:e,description:i,id:r||a.v4(),rubric_instructions:s,rubric_items:n}).filter(([t,e])=>void 0!==e)));return(await this.caller.call(async()=>{let t=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:o});return await (0,f.gJ)(t,"create annotation queue"),t})).json()}async readAnnotationQueue(t){return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/annotation-queues/${(0,u.AD)(t,"queueId")}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(e,"read annotation queue"),e})).json()}async updateAnnotationQueue(t,e){let{name:i,description:a,rubricInstructions:r,rubricItems:s}=e,n={};void 0!==i&&(n.name=i),void 0!==a&&(n.description=a),void 0!==r&&(n.rubric_instructions=r),void 0!==s&&(n.rubric_items=s);let o=JSON.stringify(n);await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/annotation-queues/${(0,u.AD)(t,"queueId")}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await (0,f.gJ)(e,"update annotation queue",!0),e})}async deleteAnnotationQueue(t){await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/annotation-queues/${(0,u.AD)(t,"queueId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(e,"delete annotation queue",!0),e})}async addRunsToAnnotationQueue(t,e){let i=JSON.stringify(e.map((t,e)=>(0,u.AD)(t,`runIds[${e}]`).toString()));await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/annotation-queues/${(0,u.AD)(t,"queueId")}/runs`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await (0,f.gJ)(e,"add runs to annotation queue",!0),e})}async getRunFromAnnotationQueue(t,e){let i=`/annotation-queues/${(0,u.AD)(t,"queueId")}/run`,a=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}${i}/${e}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(t,"get run from annotation queue"),t});return O(await a.json())}async *listRunsFromAnnotationQueue(t,e={}){let{status:i,limit:a}=e,r=new URLSearchParams,s=void 0!==a&&Number.isFinite(a)?Math.min(a,100):100;i&&r.append("status",i),r.append("limit",s.toString());let n=0,o=`/annotation-queues/${(0,u.AD)(t,"queueId")}/runs`;for await(let t of this._getPaginated(o,r))for(let e of t)if(yield O(e),++n>=s)return}async deleteRunFromAnnotationQueue(t,e){await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/annotation-queues/${(0,u.AD)(t,"queueId")}
15/runs/${(0,u.AD)(e,"queueRunId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(i,"delete run from annotation queue",!0),i})}async getSizeFromAnnotationQueue(t){return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/annotation-queues/${(0,u.AD)(t,"queueId")}/size`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(e,"get size from annotation queue"),e})).json()}async _currentTenantIsOwner(t){let e=await this._getSettings();return"-"==t||e.tenant_handle===t}async _ownerConflictError(t,e){let i=await this._getSettings();return Error(`Cannot ${t} for another tenant.
16
17      Current tenant: ${i.tenant_handle}
18
19      Requested tenant: ${e}`)}async _getLatestCommitHash(t){let e=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/commits/${t}/?limit=1&offset=0`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(e,"get latest commit hash"),e}),i=await e.json();if(0!==i.commits.length)return i.commits[0].commit_hash}async _createCommitTags(t,e,i){await Promise.all(("string"==typeof i?[i]:i).map(async i=>this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/repos/${t}/tags`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify({tag_name:i,commit_id:e})});return await (0,f.gJ)(a,"create commit tag"),a})))}async _likeOrUnlikePrompt(t,e){let[i,a,r]=(0,m._)(t),s=JSON.stringify({like:e});return(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/likes/${i}/${a}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await (0,f.gJ)(t,`${e?"like":"unlike"} prompt`),t})).json()}async _getPromptUrl(t){let[e,i,a]=(0,m._)(t);if(await this._currentTenantIsOwner(e)){let t=await this._getSettings();return"latest"!==a?`${this.getHostUrl()}/prompts/${i}/${a.substring(0,8)}?organizationId=${t.id}`:`${this.getHostUrl()}/prompts/${i}?organizationId=${t.id}`}return"latest"!==a?`${this.getHostUrl()}/hub/${e}/${i}/${a.substring(0,8)}`:`${this.getHostUrl()}/hub/${e}/${i}`}async promptExists(t){return!!await this.getPrompt(t)}async likePrompt(t){return this._likeOrUnlikePrompt(t,!0)}async unlikePrompt(t){return this._likeOrUnlikePrompt(t,!1)}async *listCommits(t){let[e,i,a]=(0,m._)(t);for await(let t of this._getPaginated(`/commits/${e}/${i}/`,new URLSearchParams,t=>t.commits))yield*t}async *listPrompts(t){let e=new URLSearchParams;for await(let i of(e.append("sort_field",t?.sortField??"updated_at"),e.append("sort_direction","desc"),e.append("is_archived",(!!t?.isArchived).toString()),t?.isPublic!==void 0&&e.append("is_public",t.isPublic.toString()),t?.query&&e.append("query",t.query),this._getPaginated("/repos",e,t=>t.repos)))yield*i}async getPrompt(t){let[e,i,a]=(0,m._)(t),r=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/repos/${e}/${i}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return t?.status===404?null:(await (0,f.gJ)(t,"get prompt"),t)}),s=await r?.json();return s?.repo?s.repo:null}async createPrompt(t,e){let i=await this._getSettings();if(e?.isPublic&&!i.tenant_handle)throw Error(`Cannot create a public prompt without first
20
21        creating a LangChain Hub handle.
22        You can add a handle by creating a public prompt at:
23
24        https://smith.langchain.com/prompts`);let[a,r,s]=(0,m._)(t);if(!await this._currentTenantIsOwner(a))throw await this._ownerConflictError("create a prompt",a);let n=JSON.stringify({repo_handle:r,...e?.description&&{description:e.description},...e?.readme&&{readme:e.readme},...e?.tags&&{tags:e.tags},is_public:!!e?.isPublic}),o=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await (0,f.gJ)(t,"create prompt"),t}),{repo:l}=await o.json();return l}async createCommit(t,e,i){if(!await this.promptExists(t))throw Error("Prompt does not exist, you must create it first.");let[a,r,s]=(0,m._)(t),n=i?.parentCommitHash!=="latest"&&i?.parentCommitHash?i?.parentCommitHash:await this._getLatestCommitHash(`${a}/${r}`),o=JSON.stringify({manifest:JSON.parse(JSON.stringify(e)),parent_commit:n,...i?.description!==void 0&&{description:i.description}}),l=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/commits/${a}/${r}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await (0,f.gJ)(t,"create commit"),t}),h=await l.json(),d=h.commit??h;return i?.tags&&await this._createCommitTags(`${a}/${r}`,d.id,i.tags),this._getPromptUrl(`${a}/${r}${d.commit_hash?`:${d.commit_hash}`:""}`)}async updateExamplesMultipart(t,e=[]){return this._updateExamplesMultipart(t,e)}async _updateExamplesMultipart(t,e=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let i=new FormData;for(let t of e){let e=t.id,a={...t.metadata&&{metadata:t.metadata},...t.split&&{split:t.split}},r=new Blob([(0,b.l)(a,`Serializing body for example with id: ${e}`)],{type:"application/json"});
24if(i.append(e,r),t.inputs){let a=new Blob([(0,b.l)(t.inputs,`Serializing inputs for example with id: ${e}`)],{type:"application/json"});i.append(`${e}.inputs`,a)}if(t.outputs){let a=new Blob([(0,b.l)(t.outputs,`Serializing outputs whle updating example with id: ${e}`)],{type:"application/json"});i.append(`${e}.outputs`,a)}if(t.attachments)for(let[a,r]of Object.entries(t.attachments)){let t,s;Array.isArray(r)?[t,s]=r:(t=r.mimeType,s=r.data);let n=new Blob([s],{type:`${t}; length=${s.byteLength}`});i.append(`${e}.attachment.${a}`,n)}if(t.attachments_operations){let a=new Blob([(0,b.l)(t.attachments_operations,`Serializing attachments while updating example with id: ${e}`)],{type:"application/json"});i.append(`${e}.attachments_operations`,a)}}let a=t??e[0]?.dataset_id;return(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${a}/examples`)}`,{method:"PATCH",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await (0,f.gJ)(t,"update examples"),t})).json()}async uploadExamplesMultipart(t,e=[]){return this._uploadExamplesMultipart(t,e)}async _uploadExamplesMultipart(t,e=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let i=new FormData;for(let t of e){let e=(t.id??a.v4()).toString(),r={created_at:t.created_at,...t.metadata&&{metadata:t.metadata},...t.split&&{split:t.split},...t.source_run_id&&{source_run_id:t.source_run_id},...t.use_source_run_io&&{use_source_run_io:t.use_source_run_io},...t.use_source_run_attachments&&{use_source_run_attachments:t.use_source_run_attachments}},s=new Blob([(0,b.l)(r,`Serializing body for uploaded example with id: ${e}`)],{type:"application/json"});if(i.append(e,s),t.inputs){let a=new Blob([(0,b.l)(t.inputs,`Serializing inputs for uploaded example with id: ${e}`)],{type:"application/json"});i.append(`${e}.inputs`,a)}if(t.outputs){let a=new Blob([(0,b.l)(t.outputs,`Serializing outputs for uploaded example with id: ${e}`)],{type:"application/json"});i.append(`${e}.outputs`,a)}if(t.attachments)for(let[a,r]of Object.entries(t.attachments)){let t,s;Array.isArray(r)?[t,s]=r:(t=r.mimeType,s=r.data);let n=new Blob([s],{type:`${t}; length=${s.byteLength}`});i.append(`${e}.attachment.${a}`,n)}}return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${t}/examples`)}`,{method:"POST",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await (0,f.gJ)(e,"upload examples"),e})).json()}async updatePrompt(t,e){if(!await this.promptExists(t))throw Error("Prompt does not exist, you must create it first.");let[i,a]=(0,m._)(t);if(!await this._currentTenantIsOwner(i))throw await this._ownerConflictError("update a prompt",i);let r={};if(e?.description!==void 0&&(r.description=e.description),e?.readme!==void 0&&(r.readme=e.readme),e?.tags!==void 0&&(r.tags=e.tags),e?.isPublic!==void 0&&(r.is_public=e.isPublic),e?.isArchived!==void 0&&(r.is_archived=e.isArchived),0===Object.keys(r).length)throw Error("No valid update options provided");let s=JSON.stringify(r);return(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/repos/${i}/${a}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await (0,f.gJ)(t,"update prompt"),t})).json()}async deletePrompt(t){if(!await this.promptExists(t))throw Error("Prompt does not exist, you must create it first.");let[e,i,a]=(0,m._)(t);if(!await this._currentTenantIsOwner(e))throw await this._ownerConflictError("delete a prompt",e);return(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/repos/${e}/${i}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(t,"delete prompt"),t})).json()}_getPromptCacheKey(t,e){return`${t}${e?":with_model":""}`}async _fetchPromptFromApi(t,e){let[i,a,r]=(0,m._)(t),s=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/commits/${i}/${a}/${r}${e?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(t,"pull prompt commit"),t}),n=await s.json();return{owner:i,repo:a,commit_hash:n.commit_hash,manifest:n.manifest,examples:n.examples,hub_model_config:n.model_config,hub_model_provider:n.model_provider}}async pullPromptCommit(t,e){var i=e?.dangerouslyPullPublicPrompt;let[a]=(0,m._)(t);
24if("-"!==a&&!i)throw 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.");let r=this._fetchPromptFromApi.bind(this,t,e);if(!e?.skipCache&&this._promptCache){let i=this._getPromptCacheKey(t,e?.includeModel),a=this._promptCache.get(i,r);if(a)return a;let s=await r();return this._promptCache.set(i,s,r),s}return this._fetchPromptFromApi(t,e)}async _pullPrompt(t,e){return JSON.stringify((await this.pullPromptCommit(t,{includeModel:e?.includeModel,skipCache:e?.skipCache,dangerouslyPullPublicPrompt:e?.dangerouslyPullPublicPrompt})).manifest)}async pushPrompt(t,e){return(await this.promptExists(t)?e&&["description","readme","tags","isPublic"].some(t=>void 0!==e[t])&&await this.updatePrompt(t,{description:e?.description,readme:e?.readme,tags:e?.tags,isPublic:e?.isPublic}):await this.createPrompt(t,{description:e?.description,readme:e?.readme,tags:e?.tags,isPublic:e?.isPublic}),e?.object)?await this.createCommit(t,e?.object,{parentCommitHash:e?.parentCommitHash,tags:e?.commitTags,description:e?.commitDescription}):await this._getPromptUrl(t)}async agentExists(t){let[e,i]=(0,m._)(t);return this._repoExists(e,i)}async skillExists(t){let[e,i]=(0,m._)(t);return this._repoExists(e,i)}async pullAgent(t,e){return await this._pullDirectory(t,"agent",e?.version)}async pullSkill(t,e){return await this._pullDirectory(t,"skill",e?.version)}async pushAgent(t,e){return this._pushDirectory(t,"agent",e)}async pushSkill(t,e){return this._pushDirectory(t,"skill",e)}async deleteAgent(t){return this._deleteDirectory(t)}async deleteSkill(t){return this._deleteDirectory(t)}async *listAgents(t){yield*this._listReposByType("agent",t)}async *listSkills(t){yield*this._listReposByType("skill",t)}async *_listReposByType(t,e){let i=new URLSearchParams;for await(let a of(i.append("repo_type",t),i.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&i.append("is_public",e.isPublic.toString()),e?.query&&i.append("query",e.query),this._getPaginated("/repos",i,t=>t.repos)))yield*a}async _pullDirectory(t,e,i){let[a,r,s]=(0,m._)(t),n=i??("latest"!==s?s:void 0),o=new URL(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${a}/${r}/directories`)}`);o.searchParams.set("repo_type",e),n&&o.searchParams.set("commit",n);let l=await this.caller.call(async()=>{let t=await this._fetch(o.toString(),{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(t,"pull directory"),t});return await l.json()}async _pushDirectory(t,e,i){if(void 0!==i.parentCommit&&(i.parentCommit.length<8||i.parentCommit.length>64))throw Error("parent_commit must be 8-64 characters");let[a,r]=(0,m._)(t);if(!await this._currentTenantIsOwner(a))throw await this._ownerConflictError(`push ${e}`,a);if(await this._repoExists(a,r))(void 0!==i.description||void 0!==i.readme||void 0!==i.tags||void 0!==i.isPublic)&&await this._updateRepoMetadata(a,r,i);else{let t=/^[a-z][a-z0-9-_]*$/;if(!t.test(r))throw Error(`Invalid repo_handle ${JSON.stringify(r)}: must match ${t}`);await this._createRepo(r,e,i)}let s={files:i.files};i.parentCommit&&(s.parent_commit=i.parentCommit);let n=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${a}/${r}/directories/commits`)}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(s)});return await (0,f.gJ)(t,`push ${e}`),t}),o=(await n.json()).commit.commit_hash,l=new URLSearchParams({organizationId:(await this._getSettings()).id});return`${this.getHostUrl()}/context/${r}/${o.slice(0,8)}?${l.toString()}`}async _deleteDirectory(t){let[e,i]=(0,m._)(t);if(!await this._currentTenantIsOwner(e))throw await this._ownerConflictError("delete",e);await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${e}/${i}/directories`)}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(t,"delete directory"),t})}async _repoExists(t,e){try{return await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/repos/${t}/${e}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await (0,f.gJ)(i,"check repo exists"),i}),!0}catch(t){if((0,f.xJ)(t))return!1;throw t}}async _createRepo(t,e,i){let a={repo_handle:t,repo_type:e,is_public:!!i.isPublic};void 0!==i.description&&(a.description=i.description),void 0!==i.readme&&(a.readme=i.readme),void 0!==i.tags&&(a.tags=i.tags);try{await this.caller.call(async()=>{let t=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(a)});return await (0,f.gJ)(t,`create ${e}`),t})}catch(t){if((0,f.I$)(t))return;throw t}}
24async _updateRepoMetadata(t,e,i){let a={};void 0!==i.description&&(a.description=i.description),void 0!==i.readme&&(a.readme=i.readme),void 0!==i.tags&&(a.tags=i.tags),void 0!==i.isPublic&&(a.is_public=i.isPublic),0!==Object.keys(a).length&&await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/repos/${t}/${e}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(a)});return await (0,f.gJ)(i,"update repo metadata"),i})}async clonePublicDataset(t,e={}){let{sourceApiUrl:i=this.apiUrl,datasetName:a}=e,[r,s]=this.parseTokenOrUrl(t,i),n=new j({apiUrl:r,apiKey:"placeholder"}),o=await n.readSharedDataset(s),l=a||o.name;try{if(await this.hasDataset({datasetId:l}))return void console.log(`Dataset ${l} already exists in your tenant. Skipping.`)}catch(t){}let h=await n.listSharedExamples(s),d=await this.createDataset(l,{description:o.description,dataType:o.data_type||"kv",inputsSchema:o.inputs_schema_definition??void 0,outputsSchema:o.outputs_schema_definition??void 0});try{await this.createExamples({inputs:h.map(t=>t.inputs),outputs:h.flatMap(t=>t.outputs?[t.outputs]:[]),datasetId:d.id})}catch(t){throw console.error(`An error occurred while creating dataset ${l}. You should delete it manually.`),t}}parseTokenOrUrl(t,e,i=2,a="dataset"){try{return(0,u.AD)(t),[e,t]}catch(t){}try{let r=new URL(t).pathname.split("/").filter(t=>""!==t);if(r.length>=i){let t=r[r.length-i];return[e,t]}throw Error(`Invalid public ${a} URL: ${t}`)}catch(e){throw Error(`Invalid public ${a} URL or token: ${t}`)}}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(t=>setTimeout(t,1));this._pendingDrains.size>0;)await Promise.all([...this._pendingDrains]);await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:t})=>t),this.batchIngestCaller.queue.onIdle()]),void 0!==this.langSmithToOTELTranslator&&await (0,s.aF)()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}toString(){let t=[`apiUrl=${JSON.stringify(this.apiUrl)}`];return void 0!==this.webUrl&&t.push(`webUrl=${JSON.stringify(this.webUrl)}`),void 0!==this.workspaceId&&t.push(`workspaceId=${JSON.stringify(this.workspaceId)}`),`[LangSmithClient ${t.join(" ")}]`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}function k(t){return"dataset_id"in t||"dataset_name"in t}Object.defineProperty(j,"_fallbackDirsCreated",{enumerable:!0,configurable:!0,writable:!0,value:new Set})}}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.