@mcp-use/inspector 0.4.6 → 0.4.7-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/cli.js +14 -2
  2. package/dist/client/assets/{api_chain-C23oJnEu.js → api_chain-D_Zy5tB_.js} +1 -1
  3. package/dist/client/assets/{combine_docs_chain-DL4SSw1r.js → combine_docs_chain-Cu-lsaxm.js} +1 -1
  4. package/dist/client/assets/console-D61Zb5pP.js +44 -0
  5. package/dist/client/assets/{few_shot-BNXy_2Ql.js → few_shot-B8HftAst.js} +1 -1
  6. package/dist/client/assets/{index-CPBnAlyU.css → index-3KbVdD5D.css} +1 -1
  7. package/dist/client/assets/{index-AFI-b3hA.js → index-BECEFYOZ.js} +5 -5
  8. package/dist/client/assets/{index-DkAopXco.js → index-C5GpJHbP.js} +99 -99
  9. package/dist/client/assets/index-DfnjN0Kh.js +4 -0
  10. package/dist/client/assets/{index-De9tTo6D.js → index-Dqs2kCKZ.js} +6 -6
  11. package/dist/client/assets/{index-Bgtt--Zu.js → index-DreE1WNB.js} +1 -1
  12. package/dist/client/assets/{index-DBFF1lMx.js → index-Dz7Ky9St.js} +4 -4
  13. package/dist/client/assets/{json-BGsjO6Of.js → json-KkEljCxR.js} +2 -2
  14. package/dist/client/assets/{langfuse-YA2S23SM-DhR-jd9m.js → langfuse-YA2S23SM-BaAcgQMN.js} +5 -5
  15. package/dist/client/assets/llm_chain-CRyVOhwQ.js +1 -0
  16. package/dist/client/assets/{sequential_chain-CMeHtLVI.js → sequential_chain-De_uWRgK.js} +1 -1
  17. package/dist/client/assets/types-CrSsHZBZ.js +38 -0
  18. package/dist/client/assets/{vector_db_qa-B2yinyB2.js → vector_db_qa-Dhc3YYTA.js} +2 -2
  19. package/dist/client/assets/{zodToJsonSchema-B4lr8sxI.js → zodToJsonSchema-t7UzpXtO.js} +1 -1
  20. package/dist/client/index.html +3 -3
  21. package/dist/server/{chunk-PHIMHO3V.js → chunk-72QXQFWZ.js} +1 -1
  22. package/dist/server/{chunk-O5RJ7JZN.js → chunk-DNYI44U5.js} +6 -6
  23. package/dist/server/{chunk-PELF3XGD.js → chunk-DZ4Q7WNY.js} +1 -1
  24. package/dist/server/{chunk-JIJ5PZK3.js → chunk-KLSPQ537.js} +13 -1
  25. package/dist/server/{chunk-X2NAWSXV.js → chunk-WF3LG4SC.js} +14 -2
  26. package/dist/server/cli.js +4 -4
  27. package/dist/server/index.js +5 -5
  28. package/dist/server/middleware.js +5 -5
  29. package/dist/server/server.js +4 -4
  30. package/dist/server/shared-routes.js +2 -2
  31. package/dist/server/shared-static.js +2 -2
  32. package/dist/server/shared-utils-browser.d.ts.map +1 -1
  33. package/dist/server/shared-utils-browser.js +1 -1
  34. package/dist/server/shared-utils.d.ts.map +1 -1
  35. package/dist/server/shared-utils.js +1 -1
  36. package/package.json +2 -2
  37. package/dist/client/assets/index-BOE1bu_0.js +0 -4
  38. package/dist/client/assets/llm_chain-BjPpdLtn.js +0 -1
  39. package/dist/client/assets/types-dtvs-u87.js +0 -81
package/dist/cli.js CHANGED
@@ -274,7 +274,7 @@ function generateWidgetContainerHtml(basePath, toolId) {
274
274
  (async function() {
275
275
  try {
276
276
  // Change URL to "/" BEFORE loading widget (for React Router)
277
- history.replaceState(null, '', '/');
277
+ //history.replaceState(null, '', '/');
278
278
 
279
279
  // Fetch the actual widget HTML using toolId
280
280
  const response = await fetch('${basePath}/api/resources/widget-content/${toolId}');
@@ -337,6 +337,7 @@ function generateWidgetContentHtml(widgetData) {
337
337
  const openaiAPI = {
338
338
  toolInput: ${safeToolInput},
339
339
  toolOutput: ${safeToolOutput},
340
+ toolResponseMetadata: null,
340
341
  displayMode: 'inline',
341
342
  maxHeight: 600,
342
343
  theme: 'dark',
@@ -410,6 +411,13 @@ function generateWidgetContentHtml(widgetData) {
410
411
  async sendFollowUpMessage(args) {
411
412
  const prompt = typeof args === 'string' ? args : (args?.prompt || '');
412
413
  return this.sendFollowupTurn(prompt);
414
+ },
415
+
416
+ openExternal(payload) {
417
+ const href = typeof payload === 'string' ? payload : payload?.href;
418
+ if (href) {
419
+ window.open(href, '_blank', 'noopener,noreferrer');
420
+ }
413
421
  }
414
422
  };
415
423
 
@@ -429,9 +437,13 @@ function generateWidgetContentHtml(widgetData) {
429
437
 
430
438
  setTimeout(() => {
431
439
  try {
432
- const globalsEvent = new CustomEvent('webplus:set_globals', {
440
+ const globalsEvent = new CustomEvent('openai:set_globals', {
433
441
  detail: {
434
442
  globals: {
443
+ toolInput: openaiAPI.toolInput,
444
+ toolOutput: openaiAPI.toolOutput,
445
+ toolResponseMetadata: openaiAPI.toolResponseMetadata || null,
446
+ widgetState: openaiAPI.widgetState,
435
447
  displayMode: openaiAPI.displayMode,
436
448
  maxHeight: openaiAPI.maxHeight,
437
449
  theme: openaiAPI.theme,
@@ -1,4 +1,4 @@
1
- import{P as u,a as c}from"./langfuse-YA2S23SM-DhR-jd9m.js";import{LLMChain as r}from"./llm_chain-BjPpdLtn.js";import"./zodToJsonSchema-B4lr8sxI.js";import"./index-DkAopXco.js";import"./deep-compare-strict-DtUHXpbW.js";import"./v4-BKrj-4V8.js";const p=`You are given the below API Documentation:
1
+ import{P as u,a as c}from"./langfuse-YA2S23SM-BaAcgQMN.js";import{LLMChain as r}from"./llm_chain-CRyVOhwQ.js";import"./zodToJsonSchema-t7UzpXtO.js";import"./index-C5GpJHbP.js";import"./deep-compare-strict-DtUHXpbW.js";import"./v4-BKrj-4V8.js";const p=`You are given the below API Documentation:
2
2
  {api_docs}
3
3
  Using this documentation, generate the full API url to call for answering the user question.
4
4
  You should build the API url in order to get a response that is as short as possible, while still getting the necessary information to answer the question. Pay attention to deliberately exclude any unnecessary pieces of data in the API call.
@@ -1,3 +1,3 @@
1
- import"./zodToJsonSchema-B4lr8sxI.js";import{a as h,P as w}from"./langfuse-YA2S23SM-DhR-jd9m.js";import{LLMChain as l}from"./llm_chain-BjPpdLtn.js";import"./index-DkAopXco.js";import"./deep-compare-strict-DtUHXpbW.js";import"./v4-BKrj-4V8.js";class p extends h{static lc_name(){return"StuffDocumentsChain"}get inputKeys(){return[this.inputKey,...this.llmChain.inputKeys].filter(e=>e!==this.documentVariableName)}get outputKeys(){return this.llmChain.outputKeys}constructor(e){super(e),Object.defineProperty(this,"llmChain",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputKey",{enumerable:!0,configurable:!0,writable:!0,value:"input_documents"}),Object.defineProperty(this,"documentVariableName",{enumerable:!0,configurable:!0,writable:!0,value:"context"}),this.llmChain=e.llmChain,this.documentVariableName=e.documentVariableName??this.documentVariableName,this.inputKey=e.inputKey??this.inputKey}_prepInputs(e){if(!(this.inputKey in e))throw new Error(`Document key ${this.inputKey} not found.`);const{[this.inputKey]:t,...i}=e,r=t.map(({pageContent:u})=>u).join(`
1
+ import"./zodToJsonSchema-t7UzpXtO.js";import{a as h,P as w}from"./langfuse-YA2S23SM-BaAcgQMN.js";import{LLMChain as l}from"./llm_chain-CRyVOhwQ.js";import"./index-C5GpJHbP.js";import"./deep-compare-strict-DtUHXpbW.js";import"./v4-BKrj-4V8.js";class p extends h{static lc_name(){return"StuffDocumentsChain"}get inputKeys(){return[this.inputKey,...this.llmChain.inputKeys].filter(e=>e!==this.documentVariableName)}get outputKeys(){return this.llmChain.outputKeys}constructor(e){super(e),Object.defineProperty(this,"llmChain",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputKey",{enumerable:!0,configurable:!0,writable:!0,value:"input_documents"}),Object.defineProperty(this,"documentVariableName",{enumerable:!0,configurable:!0,writable:!0,value:"context"}),this.llmChain=e.llmChain,this.documentVariableName=e.documentVariableName??this.documentVariableName,this.inputKey=e.inputKey??this.inputKey}_prepInputs(e){if(!(this.inputKey in e))throw new Error(`Document key ${this.inputKey} not found.`);const{[this.inputKey]:t,...i}=e,r=t.map(({pageContent:u})=>u).join(`
2
2
 
3
3
  `);return{...i,[this.documentVariableName]:r}}async _call(e,t){return await this.llmChain.call(this._prepInputs(e),t?.getChild("combine_documents"))}_chainType(){return"stuff_documents_chain"}static async deserialize(e){if(!e.llm_chain)throw new Error("Missing llm_chain");return new p({llmChain:await l.deserialize(e.llm_chain)})}serialize(){return{_type:this._chainType(),llm_chain:this.llmChain.serialize()}}}class f extends h{static lc_name(){return"MapReduceDocumentsChain"}get inputKeys(){return[this.inputKey,...this.combineDocumentChain.inputKeys]}get outputKeys(){return this.combineDocumentChain.outputKeys}constructor(e){super(e),Object.defineProperty(this,"llmChain",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputKey",{enumerable:!0,configurable:!0,writable:!0,value:"input_documents"}),Object.defineProperty(this,"documentVariableName",{enumerable:!0,configurable:!0,writable:!0,value:"context"}),Object.defineProperty(this,"returnIntermediateSteps",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:3e3}),Object.defineProperty(this,"maxIterations",{enumerable:!0,configurable:!0,writable:!0,value:10}),Object.defineProperty(this,"ensureMapStep",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"combineDocumentChain",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.llmChain=e.llmChain,this.combineDocumentChain=e.combineDocumentChain,this.documentVariableName=e.documentVariableName??this.documentVariableName,this.ensureMapStep=e.ensureMapStep??this.ensureMapStep,this.inputKey=e.inputKey??this.inputKey,this.maxTokens=e.maxTokens??this.maxTokens,this.maxIterations=e.maxIterations??this.maxIterations,this.returnIntermediateSteps=e.returnIntermediateSteps??!1}async _call(e,t){if(!(this.inputKey in e))throw new Error(`Document key ${this.inputKey} not found.`);const{[this.inputKey]:i,...n}=e;let r=i,u=[];for(let c=0;c<this.maxIterations;c+=1){const m=r.map(s=>({[this.documentVariableName]:s.pageContent,...n}));if(c!==0||!this.ensureMapStep){const s=await this.combineDocumentChain.llmChain.prompt.format(this.combineDocumentChain._prepInputs({[this.combineDocumentChain.inputKey]:r,...n}));if(await this.combineDocumentChain.llmChain._getNumTokens(s)<this.maxTokens)break}const b=await this.llmChain.apply(m,t?Array.from({length:m.length},(s,d)=>t.getChild(`map_${d+1}`)):void 0),{outputKey:y}=this.llmChain;this.returnIntermediateSteps&&(u=u.concat(b.map(s=>s[y]))),r=b.map(s=>({pageContent:s[y],metadata:{}}))}const a={[this.combineDocumentChain.inputKey]:r,...n},o=await this.combineDocumentChain.call(a,t?.getChild("combine_documents"));return this.returnIntermediateSteps?{...o,intermediateSteps:u}:o}_chainType(){return"map_reduce_documents_chain"}static async deserialize(e){if(!e.llm_chain)throw new Error("Missing llm_chain");if(!e.combine_document_chain)throw new Error("Missing combine_document_chain");return new f({llmChain:await l.deserialize(e.llm_chain),combineDocumentChain:await p.deserialize(e.combine_document_chain)})}serialize(){return{_type:this._chainType(),llm_chain:this.llmChain.serialize(),combine_document_chain:this.combineDocumentChain.serialize()}}}class _ extends h{static lc_name(){return"RefineDocumentsChain"}get defaultDocumentPrompt(){return new w({inputVariables:["page_content"],template:"{page_content}"})}get inputKeys(){return[...new Set([this.inputKey,...this.llmChain.inputKeys,...this.refineLLMChain.inputKeys])].filter(e=>e!==this.documentVariableName&&e!==this.initialResponseName)}get outputKeys(){return[this.outputKey]}constructor(e){super(e),Object.defineProperty(this,"llmChain",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputKey",{enumerable:!0,configurable:!0,writable:!0,value:"input_documents"}),Object.defineProperty(this,"outputKey",{enumerable:!0,configurable:!0,writable:!0,value:"output_text"}),Object.defineProperty(this,"documentVariableName",{enumerable:!0,configurable:!0,writable:!0,value:"context"}),Object.defineProperty(this,"initialResponseName",{enumerable:!0,configurable:!0,writable:!0,value:"existing_answer"}),Object.defineProperty(this,"refineLLMChain",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"documentPrompt",{enumerable:!0,configurable:!0,writable:!0,value:this.defaultDocumentPrompt}),this.llmChain=e.llmChain,this.refineLLMChain=e.refineLLMChain,this.documentVariableName=e.documentVariableName??this.documentVariableName,this.inputKey=e.inputKey??this.inputKey,this.outputKey=e.outputKey??this.outputKey,this.documentPrompt=e.documentPrompt??this.documentPrompt,this.initialResponseName=e.initialResponseName??this.initialResponseName}async _constructInitialInputs(e,t){const i={page_content:e.pageContent,...e.metadata},n={};return this.documentPrompt.inputVariables.forEach(a=>{n[a]=i[a]}),{...{[this.documentVariableName]:await this.documentPrompt.format({...n})},...t}}async _constructRefineInputs(e,t){const i={page_content:e.pageContent,...e.metadata},n={};this.documentPrompt.inputVariables.forEach(a=>{n[a]=i[a]});const r={[this.documentVariableName]:await this.documentPrompt.format({...n})};return{[this.initialResponseName]:t,...r}}async _call(e,t){if(!(this.inputKey in e))throw new Error(`Document key ${this.inputKey} not found.`);const{[this.inputKey]:i,...n}=e,r=i,u=await this._constructInitialInputs(r[0],n);let a=await this.llmChain.predict({...u},t?.getChild("answer"));for(let o=1;o<r.length;o+=1){const m={...await this._constructRefineInputs(r[o],a),...n};a=await this.refineLLMChain.predict({...m},t?.getChild("refine"))}return{[this.outputKey]:a}}_chainType(){return"refine_documents_chain"}static async deserialize(e){const t=e.llm_chain;if(!t)throw new Error("Missing llm_chain");const i=e.refine_llm_chain;if(!i)throw new Error("Missing refine_llm_chain");return new _({llmChain:await l.deserialize(t),refineLLMChain:await l.deserialize(i)})}serialize(){return{_type:this._chainType(),llm_chain:this.llmChain.serialize(),refine_llm_chain:this.refineLLMChain.serialize()}}}export{f as MapReduceDocumentsChain,_ as RefineDocumentsChain,p as StuffDocumentsChain};
@@ -0,0 +1,44 @@
1
+ import{s as it,P as te,p as st,v as B,a as _e,b as ke}from"./zodToJsonSchema-t7UzpXtO.js";function Wr(n,e=Le){n=n.trim();const t=n.indexOf("```");if(t===-1)return e(n);let r=n.substring(t+3);r.startsWith(`json
2
+ `)?r=r.substring(5):r.startsWith("json")?r=r.substring(4):r.startsWith(`
3
+ `)&&(r=r.substring(1));const a=r.indexOf("```");let i=r;return a!==-1&&(i=r.substring(0,a)),e(i.trim())}function Le(n){if(typeof n>"u")return null;try{return JSON.parse(n)}catch{}let e="";const t=[];let r=!1,a=!1;for(let i of n){if(r)i==='"'&&!a?r=!1:i===`
4
+ `&&!a?i="\\n":i==="\\"?a=!a:a=!1;else if(i==='"')r=!0,a=!1;else if(i==="{")t.push("}");else if(i==="[")t.push("]");else if(i==="}"||i==="]")if(t&&t[t.length-1]===i)t.pop();else return null;e+=i}r&&(e+='"');for(let i=t.length-1;i>=0;i-=1)e+=t[i];try{return JSON.parse(e)}catch{return null}}function nt(n,e){return e?.[n]||it(n)}function ot(n,e,t){const r={};for(const a in n)Object.hasOwn(n,a)&&(r[e(a,t)]=n[a]);return r}function ge(n){return Array.isArray(n)?[...n]:{...n}}function lt(n,e){const t=ge(n);for(const[r,a]of Object.entries(e)){const[i,...s]=r.split(".").reverse();let o=t;for(const l of s.reverse()){if(o[l]===void 0)break;o[l]=ge(o[l]),o=o[l]}o[i]!==void 0&&(o[i]={lc:1,type:"secret",id:[a]})}return t}function Ue(n){const e=Object.getPrototypeOf(n);return typeof n.lc_name=="function"&&(typeof e.lc_name!="function"||n.lc_name()!==e.lc_name())?n.lc_name():n.name}class q{static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Ue(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...t){Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([r])=>this.lc_serializable_keys?.includes(r))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof q||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const e={},t={},r=Object.keys(this.lc_kwargs).reduce((a,i)=>(a[i]=i in this?this[i]:this.lc_kwargs[i],a),{});for(let a=Object.getPrototypeOf(this);a;a=Object.getPrototypeOf(a))Object.assign(e,Reflect.get(a,"lc_aliases",this)),Object.assign(t,Reflect.get(a,"lc_secrets",this)),Object.assign(r,Reflect.get(a,"lc_attributes",this));return Object.keys(t).forEach(a=>{let i=this,s=r;const[o,...l]=a.split(".").reverse();for(const c of l.reverse()){if(!(c in i)||i[c]===void 0)return;(!(c in s)||s[c]===void 0)&&(typeof i[c]=="object"&&i[c]!=null?s[c]={}:Array.isArray(i[c])&&(s[c]=[])),i=i[c],s=s[c]}o in i&&i[o]!==void 0&&(s[o]=s[o]||i[o])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:ot(Object.keys(t).length?lt(r,t):r,nt,e)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}}function K(n){return typeof n=="object"&&n!==null&&"type"in n&&typeof n.type=="string"&&"source_type"in n&&(n.source_type==="url"||n.source_type==="base64"||n.source_type==="text"||n.source_type==="id")}function Qr(n){return K(n)&&n.source_type==="url"&&"url"in n&&typeof n.url=="string"}function Vr(n){return K(n)&&n.source_type==="base64"&&"data"in n&&typeof n.data=="string"}function Yr(n){if(K(n)){if(n.source_type==="url")return{type:"image_url",image_url:{url:n.url}};if(n.source_type==="base64"){if(!n.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${n.mime_type};base64,${n.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function Xr(n){const e=n.split(";")[0].split("/");if(e.length!==2)throw new Error(`Invalid mime type: "${n}" - does not match type/subtype format.`);const t=e[0].trim(),r=e[1].trim();if(t===""||r==="")throw new Error(`Invalid mime type: "${n}" - type or subtype is empty.`);const a={};for(const i of n.split(";").slice(1)){const s=i.split("=");if(s.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${n}".`);const o=s[0].trim(),l=s[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${n}".`);a[o]=l}return{type:t,subtype:r,parameters:a}}function Zr({dataUrl:n,asTypedArray:e=!1}){const t=n.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let r;if(t){r=t[1].toLowerCase();const a=e?Uint8Array.from(atob(t[2]),i=>i.charCodeAt(0)):t[2];return{mime_type:r,data:a}}}function ea(n,e){if(n.type==="text"){if(!e.fromStandardTextBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardTextBlock\` method.`);return e.fromStandardTextBlock(n)}if(n.type==="image"){if(!e.fromStandardImageBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardImageBlock\` method.`);return e.fromStandardImageBlock(n)}if(n.type==="audio"){if(!e.fromStandardAudioBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardAudioBlock\` method.`);return e.fromStandardAudioBlock(n)}if(n.type==="file"){if(!e.fromStandardFileBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardFileBlock\` method.`);return e.fromStandardFileBlock(n)}throw new Error(`Unable to convert content block type '${n.type}' to provider-specific format: not recognized.`)}function H(n,e){return typeof n=="string"?n===""?e:typeof e=="string"?n+e:Array.isArray(e)&&e.some(t=>K(t))?[{type:"text",source_type:"text",text:n},...e]:[{type:"text",text:n},...e]:Array.isArray(e)?ee(n,e)??[...n,...e]:e===""?n:Array.isArray(n)&&n.some(t=>K(t))?[...n,{type:"file",source_type:"text",text:e}]:[...n,{type:"text",text:e}]}function ct(n,e){return n==="error"||e==="error"?"error":"success"}function ut(n,e){function t(r,a){if(typeof r!="object"||r===null||r===void 0)return r;if(a>=e)return Array.isArray(r)?"[Array]":"[Object]";if(Array.isArray(r))return r.map(s=>t(s,a+1));const i={};for(const s of Object.keys(r))i[s]=t(r[s],a+1);return i}return JSON.stringify(t(n,0),null,2)}class G extends q{get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(e=>typeof e=="string"?e:e.type==="text"?e.text:"").join(""):""}getType(){return this._getType()}constructor(e,t){typeof e=="string"&&(e={content:e,additional_kwargs:t,response_metadata:{}}),e.additional_kwargs||(e.additional_kwargs={}),e.response_metadata||(e.response_metadata={}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","messages"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"content",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"additional_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"response_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.content=e.content,this.additional_kwargs=e.additional_kwargs,this.response_metadata=e.response_metadata,this.id=e.id}toDict(){return{type:this._getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;const t=ut(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}}function I(n,e){const t={...n};for(const[r,a]of Object.entries(e))if(t[r]==null)t[r]=a;else{if(a==null)continue;if(typeof t[r]!=typeof a||Array.isArray(t[r])!==Array.isArray(a))throw new Error(`field[${r}] already exists in the message chunk, but with a different type.`);if(typeof t[r]=="string"){if(r==="type")continue;["id","name","output_version","model_provider"].includes(r)?t[r]=a:t[r]+=a}else if(typeof t[r]=="object"&&!Array.isArray(t[r]))t[r]=I(t[r],a);else if(Array.isArray(t[r]))t[r]=ee(t[r],a);else{if(t[r]===a)continue;console.warn(`field[${r}] already exists in this message chunk and value has unsupported type.`)}}return t}function ee(n,e){if(!(n===void 0&&e===void 0)){if(n===void 0||e===void 0)return n||e;{const t=[...n];for(const r of e)if(typeof r=="object"&&r!==null&&"index"in r&&typeof r.index=="number"){const a=t.findIndex(i=>{const s=typeof i=="object",o="index"in i&&i.index===r.index,l="id"in i&&"id"in r&&i?.id===r?.id,c=!("id"in i)||!i?.id||!("id"in r)||!r?.id;return s&&o&&(l||c)});a!==-1&&typeof t[a]=="object"&&t[a]!==null?t[a]=I(t[a],r):t.push(r)}else{if(typeof r=="object"&&r!==null&&"text"in r&&r.text==="")continue;t.push(r)}return t}}}function dt(n,e){if(!n&&!e)throw new Error("Cannot merge two undefined objects.");if(!n||!e)return n||e;if(typeof n!=typeof e)throw new Error(`Cannot merge objects of different types.
5
+ Left ${typeof n}
6
+ Right ${typeof e}`);if(typeof n=="string"&&typeof e=="string")return n+e;if(Array.isArray(n)&&Array.isArray(e))return ee(n,e);if(typeof n=="object"&&typeof e=="object")return I(n,e);if(n===e)return n;throw new Error(`Can not merge objects of different types.
7
+ Left ${n}
8
+ Right ${e}`)}class z extends G{}function ta(n){return typeof n.role=="string"}function ht(n){return typeof n?._getType=="function"}function ra(n){return ht(n)&&typeof n.concat=="function"}class aa extends G{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}constructor(e,t,r){typeof e=="string"&&(e={content:e,name:r,tool_call_id:t}),super(e),Object.defineProperty(this,"lc_direct_tool_output",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status,this.metadata=e.metadata}_getType(){return"tool"}static isInstance(e){return e._getType()==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}}class Me extends z{constructor(e){super(e),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}_getType(){return"tool"}concat(e){return new Me({content:H(this.content,e.content),additional_kwargs:I(this.additional_kwargs,e.additional_kwargs),response_metadata:I(this.response_metadata,e.response_metadata),artifact:dt(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:ct(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}}function pt(n){const e=[],t=[];for(const r of n)if(r.function){const a=r.function.name;try{const i=JSON.parse(r.function.arguments),s={name:a||"",args:i||{},id:r.id};e.push(s)}catch{t.push({name:a,args:r.function.arguments,id:r.id,error:"Malformed args."})}}else continue;return[e,t]}function ia(n){return n._getType()==="tool"}class sa extends G{get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}constructor(e,t){let r;if(typeof e=="string")r={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:t??{}};else{r=e;const a=r.additional_kwargs?.tool_calls,i=r.tool_calls;a!=null&&a.length>0&&(i===void 0||i.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
9
+
10
+ Please upgrade your packages to versions that set`,"message tool calls. e.g., `yarn add @langchain/anthropic`,","yarn add @langchain/openai`, etc."].join(" "));try{if(a!=null&&i===void 0){const[s,o]=pt(a);r.tool_calls=s??[],r.invalid_tool_calls=o??[]}else r.tool_calls=r.tool_calls??[],r.invalid_tool_calls=r.invalid_tool_calls??[]}catch{r.tool_calls=[],r.invalid_tool_calls=[]}}super(r),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),typeof r!="string"&&(this.tool_calls=r.tool_calls??this.tool_calls,this.invalid_tool_calls=r.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=r.usage_metadata}static lc_name(){return"AIMessage"}_getType(){return"ai"}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}}function na(n){return n._getType()==="ai"}function oa(n){return n._getType()==="ai"}class De extends z{constructor(e){let t;if(typeof e=="string")t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0)t={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0};else{const r=e.tool_call_chunks.reduce((s,o)=>{const l=s.findIndex(([c])=>"id"in o&&o.id&&"index"in o&&o.index!==void 0?o.id===c.id&&o.index===c.index:"id"in o&&o.id?o.id===c.id:"index"in o&&o.index!==void 0?o.index===c.index:!1);return l!==-1?s[l].push(o):s.push([o]),s},[]),a=[],i=[];for(const s of r){let o={};const l=s[0]?.name??"",c=s.map(h=>h.args||"").join(""),u=c.length?c:"{}",d=s[0]?.id;try{if(o=Le(u),!d||o===null||typeof o!="object"||Array.isArray(o))throw new Error("Malformed tool call chunk args.");a.push({name:l,args:o,id:d,type:"tool_call"})}catch{i.push({name:l,args:u,id:d,error:"Malformed args.",type:"invalid_tool_call"})}}t={...e,tool_calls:a,invalid_tool_calls:i,usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0}}super(t),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tool_call_chunks",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_chunks=t.tool_call_chunks??this.tool_call_chunks,this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=t.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks"}}static lc_name(){return"AIMessageChunk"}_getType(){return"ai"}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){const t={content:H(this.content,e.content),additional_kwargs:I(this.additional_kwargs,e.additional_kwargs),response_metadata:I(this.response_metadata,e.response_metadata),tool_call_chunks:[],id:this.id??e.id};if(this.tool_call_chunks!==void 0||e.tool_call_chunks!==void 0){const r=ee(this.tool_call_chunks,e.tool_call_chunks);r!==void 0&&r.length>0&&(t.tool_call_chunks=r)}if(this.usage_metadata!==void 0||e.usage_metadata!==void 0){const r={...(this.usage_metadata?.input_token_details?.audio!==void 0||e.usage_metadata?.input_token_details?.audio!==void 0)&&{audio:(this.usage_metadata?.input_token_details?.audio??0)+(e.usage_metadata?.input_token_details?.audio??0)},...(this.usage_metadata?.input_token_details?.cache_read!==void 0||e.usage_metadata?.input_token_details?.cache_read!==void 0)&&{cache_read:(this.usage_metadata?.input_token_details?.cache_read??0)+(e.usage_metadata?.input_token_details?.cache_read??0)},...(this.usage_metadata?.input_token_details?.cache_creation!==void 0||e.usage_metadata?.input_token_details?.cache_creation!==void 0)&&{cache_creation:(this.usage_metadata?.input_token_details?.cache_creation??0)+(e.usage_metadata?.input_token_details?.cache_creation??0)}},a={...(this.usage_metadata?.output_token_details?.audio!==void 0||e.usage_metadata?.output_token_details?.audio!==void 0)&&{audio:(this.usage_metadata?.output_token_details?.audio??0)+(e.usage_metadata?.output_token_details?.audio??0)},...(this.usage_metadata?.output_token_details?.reasoning!==void 0||e.usage_metadata?.output_token_details?.reasoning!==void 0)&&{reasoning:(this.usage_metadata?.output_token_details?.reasoning??0)+(e.usage_metadata?.output_token_details?.reasoning??0)}},i=this.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},s=e.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},o={input_tokens:i.input_tokens+s.input_tokens,output_tokens:i.output_tokens+s.output_tokens,total_tokens:i.total_tokens+s.total_tokens,...Object.keys(r).length>0&&{input_token_details:r},...Object.keys(a).length>0&&{output_token_details:a}};t.usage_metadata=o}return new De(t)}}class Be extends G{static lc_name(){return"ChatMessage"}static _chatMessageClass(){return Be}constructor(e,t){typeof e=="string"&&(e={content:e,role:t}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}_getType(){return"generic"}static isInstance(e){return e._getType()==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}}class Ge extends z{static lc_name(){return"ChatMessageChunk"}constructor(e,t){typeof e=="string"&&(e={content:e,role:t}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}_getType(){return"generic"}concat(e){return new Ge({content:H(this.content,e.content),additional_kwargs:I(this.additional_kwargs,e.additional_kwargs),response_metadata:I(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}get _printableFields(){return{...super._printableFields,role:this.role}}}class la extends G{static lc_name(){return"FunctionMessage"}constructor(e,t){typeof e=="string"&&(e={content:e,name:t}),super(e)}_getType(){return"function"}}class Fe extends z{static lc_name(){return"FunctionMessageChunk"}_getType(){return"function"}concat(e){return new Fe({content:H(this.content,e.content),additional_kwargs:I(this.additional_kwargs,e.additional_kwargs),response_metadata:I(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}}class ca extends G{static lc_name(){return"HumanMessage"}_getType(){return"human"}constructor(e,t){super(e,t)}}class He extends z{static lc_name(){return"HumanMessageChunk"}_getType(){return"human"}constructor(e,t){super(e,t)}concat(e){return new He({content:H(this.content,e.content),additional_kwargs:I(this.additional_kwargs,e.additional_kwargs),response_metadata:I(this.response_metadata,e.response_metadata),id:this.id??e.id})}}class ua extends G{static lc_name(){return"SystemMessage"}_getType(){return"system"}constructor(e,t){super(e,t)}}class ze extends z{static lc_name(){return"SystemMessageChunk"}_getType(){return"system"}constructor(e,t){super(e,t)}concat(e){return new ze({content:H(this.content,e.content),additional_kwargs:I(this.additional_kwargs,e.additional_kwargs),response_metadata:I(this.response_metadata,e.response_metadata),id:this.id??e.id})}}const mt="gen_ai.operation.name",ft="gen_ai.system",ye="gen_ai.request.model",_t="gen_ai.response.model",be="gen_ai.usage.input_tokens",we="gen_ai.usage.output_tokens",ve="gen_ai.usage.total_tokens",gt="gen_ai.request.max_tokens",yt="gen_ai.request.temperature",bt="gen_ai.request.top_p",wt="gen_ai.request.frequency_penalty",vt="gen_ai.request.presence_penalty",St="gen_ai.response.finish_reasons",Et="gen_ai.prompt",Ot="gen_ai.completion",Tt="gen_ai.request.extra_query",At="gen_ai.request.extra_body",It="gen_ai.serialized.name",Pt="gen_ai.serialized.signature",$t="gen_ai.serialized.doc",Rt="gen_ai.response.id",jt="gen_ai.response.service_tier",xt="gen_ai.response.system_fingerprint",Nt="gen_ai.usage.input_token_details",Ct="gen_ai.usage.output_token_details",kt="langsmith.trace.session_id",Lt="langsmith.trace.session_name",Ut="langsmith.span.kind",Mt="langsmith.trace.name",Dt="langsmith.metadata",Se="langsmith.span.tags",Bt="langsmith.request.streaming",Gt="langsmith.request.headers",Ft=(...n)=>fetch(...n),Je=Symbol.for("ls:fetch_implementation"),Ht=()=>{const n=globalThis[Je];return n?typeof n=="function"&&"Headers"in n&&"Request"in n&&"Response"in n:!1},zt=n=>async(...e)=>{if(n||R("DEBUG")==="true"){const[r,a]=e;console.log(`→ ${a?.method||"GET"} ${r}`)}const t=await(globalThis[Je]??Ft)(...e);return(n||R("DEBUG")==="true")&&console.log(`← ${t.status} ${t.statusText} ${t.url}`),t},Jt=()=>R("PROJECT")??k("LANGCHAIN_SESSION")??"default",qe="0.3.73";var ue={};let C;const qt=()=>typeof window<"u"&&typeof window.document<"u",Kt=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Wt=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),Ke=()=>typeof Deno<"u",Qt=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Ke(),We=()=>C||(typeof Bun<"u"?C="bun":qt()?C="browser":Qt()?C="node":Kt()?C="webworker":Wt()?C="jsdom":Ke()?C="deno":C="other",C);let re;function Qe(){if(re===void 0){const n=We(),e=Yt();re={library:"langsmith",runtime:n,sdk:"langsmith-js",sdk_version:qe,...e}}return re}function Ve(){const n=Vt(),e={},t=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(const[r,a]of Object.entries(n))typeof a=="string"&&!t.includes(r)&&!r.toLowerCase().includes("key")&&!r.toLowerCase().includes("secret")&&!r.toLowerCase().includes("token")&&(r==="LANGCHAIN_REVISION_ID"?e.revision_id=a:e[r]=a);return e}function Vt(){const n={};try{if(typeof process<"u"&&ue)for(const[e,t]of Object.entries(ue))(e.startsWith("LANGCHAIN_")||e.startsWith("LANGSMITH_"))&&t!=null&&((e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token"))&&typeof t=="string"?n[e]=t.slice(0,2)+"*".repeat(t.length-4)+t.slice(-2):n[e]=t)}catch{}return n}function k(n){try{return typeof process<"u"?ue?.[n]:void 0}catch{return}}function R(n){return k(`LANGSMITH_${n}`)||k(`LANGCHAIN_${n}`)}let ae;function Yt(){if(ae!==void 0)return ae;const n=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],e={};for(const t of n){const r=k(t);r!==void 0&&(e[t]=r)}return ae=e,e}function Ye(){return k("OTEL_ENABLED")==="true"||R("OTEL_ENABLED")==="true"}class Xt{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...t){!this.hasWarned&&Ye()&&(console.warn('You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let r;if(t.length===1&&typeof t[0]=="function"?r=t[0]:t.length===2&&typeof t[1]=="function"?r=t[1]:t.length===3&&typeof t[2]=="function"&&(r=t[2]),typeof r=="function")return r()}}class Zt{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new Xt})}getTracer(e,t){return this.mockTracer}getActiveSpan(){}setSpan(e,t){return e}getSpan(e){}setSpanContext(e,t){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}}class er{active(){return{}}with(e,t){return t()}}const ie=Symbol.for("ls:otel_trace"),se=Symbol.for("ls:otel_context"),Ee=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),tr=new Zt,rr=new er;class ar{getTraceInstance(){return globalThis[ie]??tr}getContextInstance(){return globalThis[se]??rr}initializeGlobalInstances(e){globalThis[ie]===void 0&&(globalThis[ie]=e.trace),globalThis[se]===void 0&&(globalThis[se]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[Ee]=e}getDefaultOTLPTracerComponents(){return globalThis[Ee]??void 0}}const pe=new ar;function Xe(){return pe.getTraceInstance()}function ir(){return pe.getContextInstance()}function sr(){return pe.getDefaultOTLPTracerComponents()}const nr={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function or(n){return nr[n]||n}class lr{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,t){for(const r of e)try{if(!r.run)continue;if(r.operation==="post"){const a=this.createSpanForRun(r,r.run,t.get(r.id));a&&!r.run.end_time&&this.spans.set(r.id,a)}else this.updateSpanForRun(r,r.run)}catch(a){console.error(`Error processing operation ${r.id}:`,a)}}createSpanForRun(e,t,r){const a=r&&Xe().getSpan(r);if(a)try{return this.finishSpanSetup(a,t,e)}catch(i){console.error(`Failed to create span for run ${e.id}:`,i);return}}finishSpanSetup(e,t,r){return this.setSpanAttributes(e,t,r),t.error?(e.setStatus({code:2}),e.recordException(new Error(t.error))):e.setStatus({code:1}),t.end_time&&e.end(new Date(t.end_time)),e}updateSpanForRun(e,t){try{const r=this.spans.get(e.id);if(!r){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(r,t,e),t.error?(r.setStatus({code:2}),r.recordException(new Error(t.error))):r.setStatus({code:1});const a=t.end_time;a&&(r.end(new Date(a)),this.spans.delete(e.id))}catch(r){console.error(`Failed to update span for run ${e.id}:`,r)}}extractModelName(e){if(e.extra?.metadata){const t=e.extra.metadata;if(t.ls_model_name)return t.ls_model_name;if(t.invocation_params){const r=t.invocation_params;if(r.model)return r.model;if(r.model_name)return r.model_name}}}setSpanAttributes(e,t,r){if("run_type"in t&&t.run_type){e.setAttribute(Ut,t.run_type);const o=or(t.run_type||"chain");e.setAttribute(mt,o)}"name"in t&&t.name&&e.setAttribute(Mt,t.name),"session_id"in t&&t.session_id&&e.setAttribute(kt,t.session_id),"session_name"in t&&t.session_name&&e.setAttribute(Lt,t.session_name),this.setGenAiSystem(e,t);const a=this.extractModelName(t);a&&e.setAttribute(ye,a),"prompt_tokens"in t&&typeof t.prompt_tokens=="number"&&e.setAttribute(be,t.prompt_tokens),"completion_tokens"in t&&typeof t.completion_tokens=="number"&&e.setAttribute(we,t.completion_tokens),"total_tokens"in t&&typeof t.total_tokens=="number"&&e.setAttribute(ve,t.total_tokens),this.setInvocationParameters(e,t);const i=t.extra?.metadata||{};for(const[o,l]of Object.entries(i))l!=null&&e.setAttribute(`${Dt}.${o}`,String(l));const s=t.tags;if(s&&Array.isArray(s)?e.setAttribute(Se,s.join(", ")):s&&e.setAttribute(Se,String(s)),"serialized"in t&&typeof t.serialized=="object"){const o=t.serialized;o.name&&e.setAttribute(It,String(o.name)),o.signature&&e.setAttribute(Pt,String(o.signature)),o.doc&&e.setAttribute($t,String(o.doc))}this.setIOAttributes(e,r)}setGenAiSystem(e,t){let r="langchain";const a=this.extractModelName(t);if(a){const i=a.toLowerCase();i.includes("anthropic")||i.startsWith("claude")?r="anthropic":i.includes("bedrock")?r="aws.bedrock":i.includes("azure")&&i.includes("openai")?r="az.ai.openai":i.includes("azure")&&i.includes("inference")?r="az.ai.inference":i.includes("cohere")?r="cohere":i.includes("deepseek")?r="deepseek":i.includes("gemini")?r="gemini":i.includes("groq")?r="groq":i.includes("watson")||i.includes("ibm")?r="ibm.watsonx.ai":i.includes("mistral")?r="mistral_ai":i.includes("gpt")||i.includes("openai")?r="openai":i.includes("perplexity")||i.includes("sonar")?r="perplexity":i.includes("vertex")?r="vertex_ai":(i.includes("xai")||i.includes("grok"))&&(r="xai")}e.setAttribute(ft,r)}setInvocationParameters(e,t){if(!t.extra?.metadata?.invocation_params)return;const r=t.extra.metadata.invocation_params;r.max_tokens!==void 0&&e.setAttribute(gt,r.max_tokens),r.temperature!==void 0&&e.setAttribute(yt,r.temperature),r.top_p!==void 0&&e.setAttribute(bt,r.top_p),r.frequency_penalty!==void 0&&e.setAttribute(wt,r.frequency_penalty),r.presence_penalty!==void 0&&e.setAttribute(vt,r.presence_penalty)}setIOAttributes(e,t){if(t.run.inputs)try{const r=t.run.inputs;typeof r=="object"&&r!==null&&(r.model&&Array.isArray(r.messages)&&e.setAttribute(ye,r.model),r.stream!==void 0&&e.setAttribute(Bt,r.stream),r.extra_headers&&e.setAttribute(Gt,JSON.stringify(r.extra_headers)),r.extra_query&&e.setAttribute(Tt,JSON.stringify(r.extra_query)),r.extra_body&&e.setAttribute(At,JSON.stringify(r.extra_body))),e.setAttribute(Et,JSON.stringify(r))}catch(r){console.debug(`Failed to process inputs for run ${t.id}`,r)}if(t.run.outputs)try{const r=t.run.outputs,a=this.getUnifiedRunTokens(r);if(a&&(e.setAttribute(be,a[0]),e.setAttribute(we,a[1]),e.setAttribute(ve,a[0]+a[1])),r&&typeof r=="object"){if(r.model&&e.setAttribute(_t,String(r.model)),r.id&&e.setAttribute(Rt,r.id),r.choices&&Array.isArray(r.choices)){const i=r.choices.map(s=>s.finish_reason).filter(s=>s).map(String);i.length>0&&e.setAttribute(St,i.join(", "))}if(r.service_tier&&e.setAttribute(jt,r.service_tier),r.system_fingerprint&&e.setAttribute(xt,r.system_fingerprint),r.usage_metadata&&typeof r.usage_metadata=="object"){const i=r.usage_metadata;i.input_token_details&&e.setAttribute(Nt,JSON.stringify(i.input_token_details)),i.output_token_details&&e.setAttribute(Ct,JSON.stringify(i.output_token_details))}}e.setAttribute(Ot,JSON.stringify(r))}catch(r){console.debug(`Failed to process outputs for run ${t.id}`,r)}}getUnifiedRunTokens(e){if(!e)return null;let t=this.extractUnifiedRunTokens(e.usage_metadata);if(t)return t;const r=Object.keys(e);for(const s of r){const o=e[s];if(!(!o||typeof o!="object")&&(t=this.extractUnifiedRunTokens(o.usage_metadata),t||o.lc===1&&o.kwargs&&typeof o.kwargs=="object"&&(t=this.extractUnifiedRunTokens(o.kwargs.usage_metadata),t)))return t}const a=e.generations||[];if(!Array.isArray(a))return null;const i=Array.isArray(a[0])?a.flat():a;for(const s of i)if(typeof s=="object"&&s.message&&typeof s.message=="object"&&s.message.kwargs&&typeof s.message.kwargs=="object"&&(t=this.extractUnifiedRunTokens(s.message.kwargs.usage_metadata),t))return t;return null}extractUnifiedRunTokens(e){return!e||typeof e!="object"||typeof e.input_tokens!="number"||typeof e.output_tokens!="number"?null:[e.input_tokens,e.output_tokens]}}const cr=[429,500,502,503,504];class Oe{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,"default"in te?this.queue=new te.default({concurrency:this.maxConcurrency}):this.queue=new te({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...t){const r=this.onFailedResponseHook;return this.queue.add(()=>st(()=>e(...t).catch(a=>{throw a instanceof Error?a:new Error(a)}),{async onFailedAttempt(a){if(a.message.startsWith("Cancel")||a.message.startsWith("TimeoutError")||a.name==="TimeoutError"||a.message.startsWith("AbortError")||a?.code==="ECONNABORTED")throw a;const i=a?.response;if(r&&await r(i))return;const s=i?.status??a?.status;if(s&&!cr.includes(+s))throw a},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...r){return e.signal?Promise.race([this.call(t,...r),new Promise((a,i)=>{e.signal?.addEventListener("abort",()=>{i(new Error("AbortError"))})})]):this.call(t,...r)}}function Te(n){return typeof n?._getType=="function"}function Ae(n){const e={type:n._getType(),data:{content:n.content}};return n?.additional_kwargs&&Object.keys(n.additional_kwargs).length>0&&(e.data.additional_kwargs={...n.additional_kwargs}),e}const ur=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function _(n,e){if(!ur.test(n)){const t=e!==void 0?`Invalid UUID for ${e}: ${n}`:`Invalid UUID: ${n}`;throw new Error(t)}return n}const Ie={};function Ze(n){Ie[n]||(console.warn(n),Ie[n]=!0)}function M(n){if(!n||n.split("/").length>2||n.startsWith("/")||n.endsWith("/")||n.split(":").length>2)throw new Error(`Invalid identifier format: ${n}`);const[e,t]=n.split(":"),r=t||"latest";if(e.includes("/")){const[a,i]=e.split("/",2);if(!a||!i)throw new Error(`Invalid identifier format: ${n}`);return[a,i,r]}else{if(!e)throw new Error(`Invalid identifier format: ${n}`);return["-",e,r]}}class dr extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}}async function p(n,e,t){let r;if(n.ok){t&&(r=await n.text());return}if(n.status===403)try{(await n.json())?.error==="org_scoped_key_requires_workspace"&&(r="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{const o=new Error(`${n.status} ${n.statusText}`);throw o.status=n?.status,o}if(r===void 0)try{r=await n.text()}catch{r=""}const a=`Failed to ${e}. Received status [${n.status}]: ${n.statusText}. Message: ${r}`;if(n.status===409)throw new dr(a);const i=new Error(a);throw i.status=n.status,i}const et="ERR_CONFLICTING_ENDPOINTS";class hr 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:et}),this.name="ConflictingEndpointsError"}}function pr(n){return typeof n=="object"&&n!==null&&n.code===et}var Pe="[...]",mr={result:"[Circular]"},Y=[],F=[];const fr=new TextEncoder;function _r(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function Q(n){return fr.encode(n)}function tt(n){if(n&&typeof n=="object"&&n!==null){if(n instanceof Map)return Object.fromEntries(n);if(n instanceof Set)return Array.from(n);if(n instanceof Date)return n.toISOString();if(n instanceof RegExp)return n.toString();if(n instanceof Error)return{name:n.name,message:n.message}}else if(typeof n=="bigint")return n.toString();return n}function gr(n){return function(e,t){return tt(t)}}function j(n,e,t,r,a){try{const i=JSON.stringify(n,gr(t),r);return Q(i)}catch(i){if(!i.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`
11
+ Context: ${e}`:""}`),Q("[Unserializable]");R("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
12
+ Context: ${e}`:""}`),typeof a>"u"&&(a=_r()),de(n,"",0,[],void 0,0,a);let s;try{F.length===0?s=JSON.stringify(n,t,r):s=JSON.stringify(n,yr(t),r)}catch{return Q("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Y.length!==0;){const o=Y.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return Q(s)}}function ne(n,e,t,r){var a=Object.getOwnPropertyDescriptor(r,t);a.get!==void 0?a.configurable?(Object.defineProperty(r,t,{value:n}),Y.push([r,t,e,a])):F.push([e,t,n]):(r[t]=n,Y.push([r,t,e]))}function de(n,e,t,r,a,i,s){i+=1;var o;if(typeof n=="object"&&n!==null){for(o=0;o<r.length;o++)if(r[o]===n){ne(mr,n,e,a);return}if(typeof s.depthLimit<"u"&&i>s.depthLimit){ne(Pe,n,e,a);return}if(typeof s.edgesLimit<"u"&&t+1>s.edgesLimit){ne(Pe,n,e,a);return}if(r.push(n),Array.isArray(n))for(o=0;o<n.length;o++)de(n[o],o,o,r,n,i,s);else{n=tt(n);var l=Object.keys(n);for(o=0;o<l.length;o++){var c=l[o];de(n[c],c,o,r,n,i,s)}}r.pop()}}function yr(n){return n=typeof n<"u"?n:function(e,t){return t},function(e,t){if(F.length>0)for(var r=0;r<F.length;r++){var a=F[r];if(a[1]===e&&a[0]===t){t=a[2],F.splice(r,1);break}}return n.call(this,e,t)}}function $e(n,e){const t=Qe(),r=e??Ve(),a=n.extra??{},i=a.metadata;return n.extra={...a,runtime:{...t,...a?.runtime},metadata:{...r,...r.revision_id||"revision_id"in n&&n.revision_id?{revision_id:("revision_id"in n?n.revision_id:void 0)??r.revision_id}:{},...i}},n}const br=n=>{const e=n?.toString()??R("TRACING_SAMPLING_RATE");if(e===void 0)return;const t=parseFloat(e);if(t<0||t>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${t}`);return t},wr=n=>{const t=n.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return t==="localhost"||t==="127.0.0.1"||t==="::1"};async function vr(n){const e=[];for await(const t of n)e.push(t);return e}function V(n){if(n!==void 0)return n.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}const Sr=async n=>{if(n?.status===429){const e=parseInt(n.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(t=>setTimeout(t,e)),!0}return!1};function Re(n){return typeof n=="number"?Number(n.toFixed(4)):n}class Er{constructor(){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0})}peek(){return this.items[0]}push(e){let t;const r=new Promise(i=>{t=i}),a=j(e.item,`Serializing run with id: ${e.item.id}`).length;return this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:t,itemPromise:r,size:a}),this.sizeBytes+=a,r}pop({upToSizeBytes:e,upToSize:t}){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");const r=[];let a=0;for(;a+(this.peek()?.size??0)<e&&this.items.length>0&&r.length<t;){const i=this.items.shift();i&&(r.push(i),a+=i.size,this.sizeBytes-=i.size)}if(r.length===0&&this.items.length>0){const i=this.items.shift();r.push(i),a+=i.size,this.sizeBytes-=i.size}return[r.map(i=>({action:i.action,item:i.payload,otelContext:i.otelContext,apiKey:i.apiKey,apiUrl:i.apiUrl})),()=>r.forEach(i=>i.itemPromiseResolve())]}}const Or=24*1024*1024,Tr=1e4,Ar=100,je="https://api.smith.langchain.com";class X{get _fetch(){return this.fetchImplementation||zt(this.debug)}constructor(e={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:new Er}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:k("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:k("LANGSMITH_DEBUG")==="true"});const t=X.getDefaultClientConfig();if(this.tracingSampleRate=br(e.tracingSamplingRate),this.apiUrl=V(e.apiUrl??t.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=V(e.apiKey??t.apiKey),this.webUrl=V(e.webUrl??t.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=V(e.workspaceId??R("WORKSPACE_ID")),this.timeout_ms=e.timeout_ms??9e4,this.caller=new Oe({...e.callerOptions??{},maxRetries:4,debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.fetchImplementation=e.fetchImplementation,this.batchIngestCaller=new Oe({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...e.callerOptions??{},onFailedResponseHook:Sr,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??t.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??t.hideOutputs,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,Ye()&&(this.langSmithToOTELTranslator=new lr),this.cachedLSEnvVarsForMetadata=Ve()}static getDefaultClientConfig(){const e=R("API_KEY"),t=R("ENDPOINT")??je,r=R("HIDE_INPUTS")==="true",a=R("HIDE_OUTPUTS")==="true";return{apiUrl:t,apiKey:e,webUrl:void 0,hideInputs:r,hideOutputs:a}}getHostUrl(){return this.webUrl?this.webUrl:wr(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.endsWith("/api/v1")?(this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get headers(){const e={"User-Agent":`langsmith-js/${qe}`};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}_getPlatformEndpointPath(e){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${e}`:`/platform/${e}`}async processInputs(e){return this.hideInputs===!1?e:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(e):e}async processOutputs(e){return this.hideOutputs===!1?e:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(e):e}async prepareRunCreateOrUpdateInputs(e){const t={...e};return t.inputs!==void 0&&(t.inputs=await this.processInputs(t.inputs)),t.outputs!==void 0&&(t.outputs=await this.processOutputs(t.outputs)),t}async _getResponse(e,t){const r=t?.toString()??"",a=`${this.apiUrl}${e}?${r}`;return await this.caller.call(async()=>{const s=await this._fetch(a,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await p(s,`fetch ${e}`),s})}async _get(e,t){return(await this._getResponse(e,t)).json()}async*_getPaginated(e,t=new URLSearchParams,r){let a=Number(t.get("offset"))||0;const i=Number(t.get("limit"))||100;for(;;){t.set("offset",String(a)),t.set("limit",String(i));const s=`${this.apiUrl}${e}?${t}`,o=await this.caller.call(async()=>{const c=await this._fetch(s,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await p(c,`fetch ${e}`),c}),l=r?r(await o.json()):await o.json();if(l.length===0||(yield l,l.length<i))break;a+=l.length}}async*_getCursorPaginatedList(e,t=null,r="POST",a="runs"){const i=t?{...t}:{};for(;;){const s=JSON.stringify(i),l=await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}${e}`,{method:r,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await p(u,`fetch ${e}`),u})).json();if(!l||!l[a])break;yield l[a];const c=l.cursors;if(!c||!c.next)break;i.cursor=c.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(e,t=!1){if(this.tracingSampleRate===void 0)return e;if(t){const r=[];for(const a of e)this.filteredPostUuids.has(a.trace_id)?a.id===a.trace_id&&this.filteredPostUuids.delete(a.trace_id):r.push(a);return r}else{const r=[];for(const a of e){const i=a.trace_id??a.id;this.filteredPostUuids.has(i)||(a.id===i?this._shouldSample()?r.push(a):this.filteredPostUuids.add(i):r.push(a))}return r}}async _getBatchSizeLimitBytes(){const e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e.batch_ingest_config?.size_limit_bytes??Or}async _getBatchSizeLimit(){const e=await this._ensureServerInfo();return this.batchSizeLimit??e.batch_ingest_config?.size_limit??Ar}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t}){const r=[];for(;this.autoBatchQueue.items.length>0;){const[a,i]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:t});if(!a.length){i();break}const s=a.reduce((c,u)=>{const d=u.apiUrl??this.apiUrl,h=u.apiKey??this.apiKey,f=u.apiKey===this.apiKey&&u.apiUrl===this.apiUrl?"default":`${d}|${h}`;return c[f]||(c[f]=[]),c[f].push(u),c},{}),o=[];for(const[c,u]of Object.entries(s)){const d=this._processBatch(u,{apiUrl:c==="default"?void 0:c.split("|")[0],apiKey:c==="default"?void 0:c.split("|")[1]});o.push(d)}const l=Promise.all(o).finally(i);r.push(l)}return Promise.all(r)}async _processBatch(e,t){if(e.length)try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{const r={runCreates:e.filter(i=>i.action==="create").map(i=>i.item),runUpdates:e.filter(i=>i.action==="update").map(i=>i.item)},a=await this._ensureServerInfo();if(a?.batch_ingest_config?.use_multipart_endpoint){const i=a?.instance_flags?.gzip_body_enabled;await this.multipartIngestRuns(r,{...t,useGzip:i})}else await this.batchIngestRuns(r,t)}}catch(r){console.error("Error exporting batch:",r)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){const t=new Map,r=[];for(const a of e)a.item.id&&a.otelContext&&(t.set(a.item.id,a.otelContext),a.action==="create"?r.push({operation:"post",id:a.item.id,trace_id:a.item.trace_id??a.item.id,run:a.item}):r.push({operation:"patch",id:a.item.id,trace_id:a.item.trace_id??a.item.id,run:a.item}));this.langSmithToOTELTranslator.exportBatch(r,t)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=$e(e.item,this.cachedLSEnvVarsForMetadata);const t=this.autoBatchQueue.push(e);if(this.manualFlushMode)return t;const r=await this._getBatchSizeLimitBytes(),a=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>r||this.autoBatchQueue.items.length>a)&&this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:a}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:a})},this.autoBatchAggregationDelayMs)),t}async _getServerInfo(){const t=await(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(Tr),...this.fetchOptions});return await p(r,"get server info"),r})).json();return this.debug&&console.log(`
13
+ === LangSmith Server Configuration ===
14
+ `+JSON.stringify(t,null,2)+`
15
+ `),t}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){const e=await this._getBatchSizeLimitBytes(),t=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t})}_cloneCurrentOTELContext(){const e=Xe(),t=ir();if(this.langSmithToOTELTranslator!==void 0){const r=e.getActiveSpan();if(r)return e.setSpan(t.active(),r)}}async createRun(e,t){if(!this._filterForSampling([e]).length)return;const r={...this.headers,"Content-Type":"application/json"},a=e.project_name;delete e.project_name;const i=await this.prepareRunCreateOrUpdateInputs({session_name:a,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&i.trace_id!==void 0&&i.dotted_order!==void 0){const l=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:i,otelContext:l,apiKey:t?.apiKey,apiUrl:t?.apiUrl}).catch(console.error);return}const s=$e(i,this.cachedLSEnvVarsForMetadata);t?.apiKey!==void 0&&(r["x-api-key"]=t.apiKey),t?.workspaceId!==void 0&&(r["x-tenant-id"]=t.workspaceId);const o=j(s,`Creating run with id: ${s.id}`);await this.caller.call(async()=>{const l=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await p(l,"create run",!0),l})}async batchIngestRuns({runCreates:e,runUpdates:t},r){if(e===void 0&&t===void 0)return;let a=await Promise.all(e?.map(l=>this.prepareRunCreateOrUpdateInputs(l))??[]),i=await Promise.all(t?.map(l=>this.prepareRunCreateOrUpdateInputs(l))??[]);if(a.length>0&&i.length>0){const l=a.reduce((u,d)=>(d.id&&(u[d.id]=d),u),{}),c=[];for(const u of i)u.id!==void 0&&l[u.id]?l[u.id]={...l[u.id],...u}:c.push(u);a=Object.values(l),i=c}const s={post:a,patch:i};if(!s.post.length&&!s.patch.length)return;const o={post:[],patch:[]};for(const l of["post","patch"]){const c=l,u=s[c].reverse();let d=u.pop();for(;d!==void 0;)o[c].push(d),d=u.pop()}if(o.post.length>0||o.patch.length>0){const l=o.post.map(c=>c.id).concat(o.patch.map(c=>c.id)).join(",");await this._postBatchIngestRuns(j(o,`Ingesting runs with ids: ${l}`),r)}}async _postBatchIngestRuns(e,t){const r={...this.headers,"Content-Type":"application/json",Accept:"application/json"};t?.apiKey!==void 0&&(r["x-api-key"]=t.apiKey),await this.batchIngestCaller.call(async()=>{const a=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await p(a,"batch create run",!0),a})}async multipartIngestRuns({runCreates:e,runUpdates:t},r){if(e===void 0&&t===void 0)return;const a={};let i=[];for(const d of e??[]){const h=await this.prepareRunCreateOrUpdateInputs(d);h.id!==void 0&&h.attachments!==void 0&&(a[h.id]=h.attachments),delete h.attachments,i.push(h)}let s=[];for(const d of t??[])s.push(await this.prepareRunCreateOrUpdateInputs(d));if(i.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(s.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(i.length>0&&s.length>0){const d=i.reduce((m,f)=>(f.id&&(m[f.id]=f),m),{}),h=[];for(const m of s)m.id!==void 0&&d[m.id]?d[m.id]={...d[m.id],...m}:h.push(m);i=Object.values(d),s=h}if(i.length===0&&s.length===0)return;const c=[],u=[];for(const[d,h]of[["post",i],["patch",s]])for(const m of h){const{inputs:f,outputs:E,events:T,extra:g,error:w,serialized:y,attachments:O,...b}=m,P={inputs:f,outputs:E,events:T,extra:g,error:w,serialized:y},v=j(b,`Serializing for multipart ingestion of run with id: ${b.id}`);u.push({name:`${d}.${b.id}`,payload:new Blob([v],{type:`application/json; length=${v.length}`})});for(const[S,L]of Object.entries(P)){if(L===void 0)continue;const U=j(L,`Serializing ${S} for multipart ingestion of run with id: ${b.id}`);u.push({name:`${d}.${b.id}.${S}`,payload:new Blob([U],{type:`application/json; length=${U.length}`})})}if(b.id!==void 0){const S=a[b.id];if(S){delete a[b.id];for(const[L,U]of Object.entries(S)){let J,W;if(Array.isArray(U)?[J,W]=U:(J=U.mimeType,W=U.data),L.includes(".")){console.warn(`Skipping attachment '${L}' for run ${b.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}u.push({name:`attachment.${b.id}.${L}`,payload:new Blob([W],{type:`${J}; length=${W.byteLength}`})})}}}c.push(`trace=${b.trace_id},id=${b.id}`)}await this._sendMultipartRequest(u,c.join("; "),r)}async _createNodeFetchBody(e,t){const r=[];for(const s of e)r.push(new Blob([`--${t}\r
16
+ `])),r.push(new Blob([`Content-Disposition: form-data; name="${s.name}"\r
17
+ `,`Content-Type: ${s.payload.type}\r
18
+ \r
19
+ `])),r.push(s.payload),r.push(new Blob([`\r
20
+ `]));return r.push(new Blob([`--${t}--\r
21
+ `])),await new Blob(r).arrayBuffer()}async _createMultipartStream(e,t){const r=new TextEncoder;return new ReadableStream({async start(i){const s=async o=>{typeof o=="string"?i.enqueue(r.encode(o)):i.enqueue(o)};for(const o of e){await s(`--${t}\r
22
+ `),await s(`Content-Disposition: form-data; name="${o.name}"\r
23
+ `),await s(`Content-Type: ${o.payload.type}\r
24
+ \r
25
+ `);const c=o.payload.stream().getReader();try{let u;for(;!(u=await c.read()).done;)i.enqueue(u.value)}finally{c.releaseLock()}await s(`\r
26
+ `)}await s(`--${t}--\r
27
+ `),i.close()}})}async _sendMultipartRequest(e,t,r){const a="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),i=Ht(),s=()=>this._createNodeFetchBody(e,a),o=()=>this._createMultipartStream(e,a),l=async c=>this.batchIngestCaller.call(async()=>{const u=await c(),d={...this.headers,"Content-Type":`multipart/form-data; boundary=${a}`};r?.apiKey!==void 0&&(d["x-api-key"]=r.apiKey);let h=u;r?.useGzip&&typeof u=="object"&&"pipeThrough"in u&&(h=u.pipeThrough(new CompressionStream("gzip")),d["Content-Encoding"]="gzip");const m=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:d,body:h,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await p(m,"Failed to send multipart request",!0),m});try{let c,u=!1;!i&&!this.multipartStreamingDisabled&&We()!=="bun"?(u=!0,c=await l(o)):c=await l(s),(!this.multipartStreamingDisabled||u)&&c.status===422&&(r?.apiUrl??this.apiUrl)!==je&&(console.warn(`Streaming multipart upload to ${r?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${t}".`),this.multipartStreamingDisabled=!0,c=await l(s))}catch(c){console.warn(`${c.message.trim()}
28
+
29
+ Context: ${t}`)}}async updateRun(e,t,r){_(e),t.inputs&&(t.inputs=await this.processInputs(t.inputs)),t.outputs&&(t.outputs=await this.processOutputs(t.outputs));const a={...t,id:e};if(!this._filterForSampling([a],!0).length)return;if(this.autoBatchTracing&&a.trace_id!==void 0&&a.dotted_order!==void 0){const o=this._cloneCurrentOTELContext();if(t.end_time!==void 0&&a.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:a,otelContext:o,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:a,otelContext:o,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}const i={...this.headers,"Content-Type":"application/json"};r?.apiKey!==void 0&&(i["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(i["x-tenant-id"]=r.workspaceId);const s=j(t,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{const o=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:i,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await p(o,"update run",!0),o})}async readRun(e,{loadChildRuns:t}={loadChildRuns:!1}){_(e);let r=await this._get(`/runs/${e}`);return t&&(r=await this._loadChildRuns(r)),r}async getRunUrl({runId:e,run:t,projectOpts:r}){if(t!==void 0){let a;t.session_id?a=t.session_id:r?.projectName?a=(await this.readProject({projectName:r?.projectName})).id:r?.projectId?a=r?.projectId:a=(await this.readProject({projectName:R("PROJECT")||"default"})).id;const i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${a}/r/${t.id}?poll=true`}else if(e!==void 0){const a=await this.readRun(e);if(!a.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${a.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){const t=await vr(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),r={},a={};t.sort((i,s)=>(i?.dotted_order??"").localeCompare(s?.dotted_order??""));for(const i of t){if(i.parent_run_id===null||i.parent_run_id===void 0)throw new Error(`Child run ${i.id} has no parent`);i.dotted_order?.startsWith(e.dotted_order??"")&&i.id!==e.id&&(i.parent_run_id in r||(r[i.parent_run_id]=[]),r[i.parent_run_id].push(i),a[i.id]=i)}e.child_runs=r[e.id]||[];for(const i in r)i!==e.id&&(a[i].child_runs=r[i]);return e}async*listRuns(e){const{projectId:t,projectName:r,parentRunId:a,traceId:i,referenceExampleId:s,startTime:o,executionOrder:l,isRoot:c,runType:u,error:d,id:h,query:m,filter:f,traceFilter:E,treeFilter:T,limit:g,select:w,order:y}=e;let O=[];if(t&&(O=Array.isArray(t)?t:[t]),r){const S=Array.isArray(r)?r:[r],L=await Promise.all(S.map(U=>this.readProject({projectName:U}).then(J=>J.id)));O.push(...L)}const b=["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"],P={session:O.length?O:null,run_type:u,reference_example:s,query:m,filter:f,trace_filter:E,tree_filter:T,execution_order:l,parent_run:a,start_time:o?o.toISOString():null,error:d,id:h,limit:g,trace:i,select:w||b,is_root:c,order:y};let v=0;for await(const S of this._getCursorPaginatedList("/runs/query",P))if(g){if(v>=g)break;if(S.length+v>g){yield*S.slice(0,g-v);break}v+=S.length,yield*S}else yield*S}async*listGroupRuns(e){const{projectId:t,projectName:r,groupBy:a,filter:i,startTime:s,endTime:o,limit:l,offset:c}=e,d={session_id:t||(await this.readProject({projectName:r})).id,group_by:a,filter:i,start_time:s?s.toISOString():null,end_time:o?o.toISOString():null,limit:Number(l)||100};let h=Number(c)||0;const m="/runs/group",f=`${this.apiUrl}${m}`;for(;;){const E={...d,offset:h},T=Object.fromEntries(Object.entries(E).filter(([P,v])=>v!==void 0)),g=JSON.stringify(T),y=await(await this.caller.call(async()=>{const P=await this._fetch(f,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:g});return await p(P,`Failed to fetch ${m}`),P})).json(),{groups:O,total:b}=y;if(O.length===0)break;for(const P of O)yield P;if(h+=O.length,h>=b)break}}async getRunStats({id:e,trace:t,parentRun:r,runType:a,projectNames:i,projectIds:s,referenceExampleIds:o,startTime:l,endTime:c,error:u,query:d,filter:h,traceFilter:m,treeFilter:f,isRoot:E,dataSourceType:T}){let g=s||[];i&&(g=[...s||[],...await Promise.all(i.map(v=>this.readProject({projectName:v}).then(S=>S.id)))]);const y=Object.fromEntries(Object.entries({id:e,trace:t,parent_run:r,run_type:a,session:g,reference_example:o,start_time:l,end_time:c,error:u,query:d,filter:h,trace_filter:m,tree_filter:f,is_root:E,data_source_type:T}).filter(([v,S])=>S!==void 0)),O=JSON.stringify(y);return await(await this.caller.call(async()=>{const v=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:O});return await p(v,"get run stats"),v})).json()}async shareRun(e,{shareId:t}={}){const r={run_id:e,share_token:t||B()};_(e);const a=JSON.stringify(r),s=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await p(o,"share run"),o})).json();if(s===null||!("share_token"in s))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${s.share_token}/r`}async unshareRun(e){_(e),await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await p(t,"unshare run",!0),t})}async readRunSharedLink(e){_(e);const r=await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await p(a,"read run shared link"),a})).json();if(!(r===null||!("share_token"in r)))return`${this.getHostUrl()}/public/${r.share_token}/r`}async listSharedRuns(e,{runIds:t}={}){const r=new URLSearchParams({share_token:e});if(t!==void 0)for(const s of t)r.append("id",s);return _(e),await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/public/${e}/runs${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await p(s,"list shared runs"),s})).json()}async readDatasetSharedSchema(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id),_(e);const a=await(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await p(i,"read dataset shared schema"),i})).json();return a.url=`${this.getHostUrl()}/public/${a.share_token}/d`,a}async shareDataset(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id);const r={dataset_id:e};_(e);const a=JSON.stringify(r),s=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await p(o,"share dataset"),o})).json();return s.url=`${this.getHostUrl()}/public/${s.share_token}/d`,s}async unshareDataset(e){_(e),await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await p(t,"unshare dataset",!0),t})}async readSharedDataset(e){return _(e),await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await p(a,"read shared dataset"),a})).json()}async listSharedExamples(e,t){const r={};t?.exampleIds&&(r.id=t.exampleIds);const a=new URLSearchParams;Object.entries(r).forEach(([o,l])=>{Array.isArray(l)?l.forEach(c=>a.append(o,c)):a.append(o,l)});const i=await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/public/${e}/examples?${a.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await p(o,"list shared examples"),o}),s=await i.json();if(!i.ok)throw"detail"in s?new Error(`Failed to list shared examples.
30
+ Status: ${i.status}
31
+ Message: ${Array.isArray(s.detail)?s.detail.join(`
32
+ `):"Unspecified error"}`):new Error(`Failed to list shared examples: ${i.status} ${i.statusText}`);return s.map(o=>({...o,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:t=null,metadata:r=null,upsert:a=!1,projectExtra:i=null,referenceDatasetId:s=null}){const o=a?"?upsert=true":"",l=`${this.apiUrl}/sessions${o}`,c=i||{};r&&(c.metadata=r);const u={name:e,extra:c,description:t};s!==null&&(u.reference_dataset_id=s);const d=JSON.stringify(u);return await(await this.caller.call(async()=>{const f=await this._fetch(l,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:d});return await p(f,"create project"),f})).json()}async updateProject(e,{name:t=null,description:r=null,metadata:a=null,projectExtra:i=null,endTime:s=null}){const o=`${this.apiUrl}/sessions/${e}`;let l=i;a&&(l={...l||{},metadata:a});const c=JSON.stringify({name:t,extra:l,description:r,end_time:s?new Date(s).toISOString():null});return await(await this.caller.call(async()=>{const h=await this._fetch(o,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await p(h,"update project"),h})).json()}async hasProject({projectId:e,projectName:t}){let r="/sessions";const a=new URLSearchParams;if(e!==void 0&&t!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)_(e),r+=`/${e}`;else if(t!==void 0)a.append("name",t);else throw new Error("Must provide projectName or projectId");const i=await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}${r}?${a}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await p(s,"has project"),s});try{const s=await i.json();return i.ok?Array.isArray(s)?s.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:t,includeStats:r}){let a="/sessions";const i=new URLSearchParams;if(e!==void 0&&t!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)_(e),a+=`/${e}`;else if(t!==void 0)i.append("name",t);else throw new Error("Must provide projectName or projectId");r!==void 0&&i.append("include_stats",r.toString());const s=await this._get(a,i);let o;if(Array.isArray(s)){if(s.length===0)throw new Error(`Project[id=${e}, name=${t}] not found`);o=s[0]}else o=s;return o}async getProjectUrl({projectId:e,projectName:t}){if(e===void 0&&t===void 0)throw new Error("Must provide either projectName or projectId");const r=await this.readProject({projectId:e,projectName:t}),a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${r.id}`}async getDatasetUrl({datasetId:e,datasetName:t}){if(e===void 0&&t===void 0)throw new Error("Must provide either datasetName or datasetId");const r=await this.readDataset({datasetId:e,datasetName:t}),a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/datasets/${r.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;const e=new URLSearchParams({limit:"1"});for await(const t of this._getPaginated("/sessions",e))return this._tenantId=t[0].tenant_id,t[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:t,nameContains:r,referenceDatasetId:a,referenceDatasetName:i,includeStats:s,datasetVersion:o,referenceFree:l,metadata:c}={}){const u=new URLSearchParams;if(e!==void 0)for(const d of e)u.append("id",d);if(t!==void 0&&u.append("name",t),r!==void 0&&u.append("name_contains",r),a!==void 0)u.append("reference_dataset",a);else if(i!==void 0){const d=await this.readDataset({datasetName:i});u.append("reference_dataset",d.id)}s!==void 0&&u.append("include_stats",s.toString()),o!==void 0&&u.append("dataset_version",o),l!==void 0&&u.append("reference_free",l.toString()),c!==void 0&&u.append("metadata",JSON.stringify(c));for await(const d of this._getPaginated("/sessions",u))yield*d}async deleteProject({projectId:e,projectName:t}){let r;if(e===void 0&&t===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&t!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?r=(await this.readProject({projectName:t})).id:r=e,_(r),await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/sessions/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await p(a,`delete session ${r} (${t})`,!0),a})}async uploadCsv({csvFile:e,fileName:t,inputKeys:r,outputKeys:a,description:i,dataType:s,name:o}){const l=`${this.apiUrl}/datasets/upload`,c=new FormData;return c.append("file",e,t),r.forEach(h=>{c.append("input_keys",h)}),a.forEach(h=>{c.append("output_keys",h)}),i&&c.append("description",i),s&&c.append("data_type",s),o&&c.append("name",o),await(await this.caller.call(async()=>{const h=await this._fetch(l,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await p(h,"upload CSV"),h})).json()}async createDataset(e,{description:t,dataType:r,inputsSchema:a,outputsSchema:i,metadata:s}={}){const o={name:e,description:t,extra:s?{metadata:s}:void 0};r&&(o.data_type=r),a&&(o.inputs_schema_definition=a),i&&(o.outputs_schema_definition=i);const l=JSON.stringify(o);return await(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await p(d,"create dataset"),d})).json()}async readDataset({datasetId:e,datasetName:t}){let r="/datasets";const a=new URLSearchParams({limit:"1"});if(e&&t)throw new Error("Must provide either datasetName or datasetId, not both");if(e)_(e),r+=`/${e}`;else if(t)a.append("name",t);else throw new Error("Must provide datasetName or datasetId");const i=await this._get(r,a);let s;if(Array.isArray(i)){if(i.length===0)throw new Error(`Dataset[id=${e}, name=${t}] not found`);s=i[0]}else s=i;return s}async hasDataset({datasetId:e,datasetName:t}){try{return await this.readDataset({datasetId:e,datasetName:t}),!0}catch(r){if(r instanceof Error&&r.message.toLocaleLowerCase().includes("not found"))return!1;throw r}}async diffDatasetVersions({datasetId:e,datasetName:t,fromVersion:r,toVersion:a}){let i=e;if(i===void 0&&t===void 0)throw new Error("Must provide either datasetName or datasetId");if(i!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");i===void 0&&(i=(await this.readDataset({datasetName:t})).id);const s=new URLSearchParams({from_version:typeof r=="string"?r:r.toISOString(),to_version:typeof a=="string"?a:a.toISOString()});return await this._get(`/datasets/${i}/versions/diff`,s)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:t}){const r="/datasets";if(e===void 0)if(t!==void 0)e=(await this.readDataset({datasetName:t})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${r}/${e}/openai_ft`)).text()).trim().split(`
33
+ `).map(o=>JSON.parse(o))}async*listDatasets({limit:e=100,offset:t=0,datasetIds:r,datasetName:a,datasetNameContains:i,metadata:s}={}){const o="/datasets",l=new URLSearchParams({limit:e.toString(),offset:t.toString()});if(r!==void 0)for(const c of r)l.append("id",c);a!==void 0&&l.append("name",a),i!==void 0&&l.append("name_contains",i),s!==void 0&&l.append("metadata",JSON.stringify(s));for await(const c of this._getPaginated(o,l))yield*c}async updateDataset(e){const{datasetId:t,datasetName:r,...a}=e;if(!t&&!r)throw new Error("Must provide either datasetName or datasetId");const i=t??(await this.readDataset({datasetName:r})).id;_(i);const s=JSON.stringify(a);return await(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}/datasets/${i}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await p(l,"update dataset"),l})).json()}async updateDatasetTag(e){const{datasetId:t,datasetName:r,asOf:a,tag:i}=e;if(!t&&!r)throw new Error("Must provide either datasetName or datasetId");const s=t??(await this.readDataset({datasetName:r})).id;_(s);const o=JSON.stringify({as_of:typeof a=="string"?a:a.toISOString(),tag:i});await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}/datasets/${s}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await p(l,"update dataset tags",!0),l})}async deleteDataset({datasetId:e,datasetName:t}){let r="/datasets",a=e;if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(t!==void 0&&(a=(await this.readDataset({datasetName:t})).id),a!==void 0)_(a),r+=`/${a}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{const i=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await p(i,`delete ${r}`,!0),i})}async indexDataset({datasetId:e,datasetName:t,tag:r}){let a=e;if(!a&&!t)throw new Error("Must provide either datasetName or datasetId");if(a&&t)throw new Error("Must provide either datasetName or datasetId, not both");a||(a=(await this.readDataset({datasetName:t})).id),_(a);const s=JSON.stringify({tag:r});await(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}/datasets/${a}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await p(l,"index dataset"),l})).json()}async similarExamples(e,t,r,{filter:a}={}){const i={limit:r,inputs:e};a!==void 0&&(i.filter=a),_(t);const s=JSON.stringify(i);return(await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${t}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:s});return await p(c,"fetch similar examples"),c})).json()).examples}async createExample(e,t,r){if(xe(e)&&(t!==void 0||r!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let a=t?r?.datasetId:e.dataset_id;const i=t?r?.datasetName:e.dataset_name;if(a===void 0&&i===void 0)throw new Error("Must provide either datasetName or datasetId");if(a!==void 0&&i!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");a===void 0&&(a=(await this.readDataset({datasetName:i})).id);const s=(t?r?.createdAt:e.created_at)||new Date;let o;xe(e)?o=e:o={inputs:e,outputs:t,created_at:s?.toISOString(),id:r?.exampleId,metadata:r?.metadata,split:r?.split,source_run_id:r?.sourceRunId,use_source_run_io:r?.useSourceRunIO,use_source_run_attachments:r?.useSourceRunAttachments,attachments:r?.attachments};const l=await this._uploadExamplesMultipart(a,[o]);return await this.readExample(l.example_ids?.[0]??B())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];const w=e;let y=w[0].dataset_id;const O=w[0].dataset_name;if(y===void 0&&O===void 0)throw new Error("Must provide either datasetName or datasetId");if(y!==void 0&&O!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");y===void 0&&(y=(await this.readDataset({datasetName:O})).id);const b=await this._uploadExamplesMultipart(y,w);return await Promise.all(b.example_ids.map(v=>this.readExample(v)))}const{inputs:t,outputs:r,metadata:a,splits:i,sourceRunIds:s,useSourceRunIOs:o,useSourceRunAttachments:l,attachments:c,exampleIds:u,datasetId:d,datasetName:h}=e;if(t===void 0)throw new Error("Must provide inputs when using legacy parameters");let m=d;const f=h;if(m===void 0&&f===void 0)throw new Error("Must provide either datasetName or datasetId");if(m!==void 0&&f!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");m===void 0&&(m=(await this.readDataset({datasetName:f})).id);const E=t.map((w,y)=>({dataset_id:m,inputs:w,outputs:r?.[y],metadata:a?.[y],split:i?.[y],id:u?.[y],attachments:c?.[y],source_run_id:s?.[y],use_source_run_io:o?.[y],use_source_run_attachments:l?.[y]})),T=await this._uploadExamplesMultipart(m,E);return await Promise.all(T.example_ids.map(w=>this.readExample(w)))}async createLLMExample(e,t,r){return this.createExample({input:e},{output:t},r)}async createChatExample(e,t,r){const a=e.map(s=>Te(s)?Ae(s):s),i=Te(t)?Ae(t):t;return this.createExample({input:a},{output:i},r)}async readExample(e){_(e);const t=`/examples/${e}`,r=await this._get(t),{attachment_urls:a,...i}=r,s=i;return a&&(s.attachments=Object.entries(a).reduce((o,[l,c])=>(o[l.slice(11)]={presigned_url:c.presigned_url,mime_type:c.mime_type},o),{})),s}async*listExamples({datasetId:e,datasetName:t,exampleIds:r,asOf:a,splits:i,inlineS3Urls:s,metadata:o,limit:l,offset:c,filter:u,includeAttachments:d}={}){let h;if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)h=e;else if(t!==void 0)h=(await this.readDataset({datasetName:t})).id;else throw new Error("Must provide a datasetName or datasetId");const m=new URLSearchParams({dataset:h}),f=a?typeof a=="string"?a:a?.toISOString():void 0;f&&m.append("as_of",f);const E=s??!0;if(m.append("inline_s3_urls",E.toString()),r!==void 0)for(const g of r)m.append("id",g);if(i!==void 0)for(const g of i)m.append("splits",g);if(o!==void 0){const g=JSON.stringify(o);m.append("metadata",g)}l!==void 0&&m.append("limit",l.toString()),c!==void 0&&m.append("offset",c.toString()),u!==void 0&&m.append("filter",u),d===!0&&["attachment_urls","outputs","metadata"].forEach(g=>m.append("select",g));let T=0;for await(const g of this._getPaginated("/examples",m)){for(const w of g){const{attachment_urls:y,...O}=w,b=O;y&&(b.attachments=Object.entries(y).reduce((P,[v,S])=>(P[v.slice(11)]={presigned_url:S.presigned_url,mime_type:S.mime_type||void 0},P),{})),yield b,T++}if(l!==void 0&&T>=l)break}}async deleteExample(e){_(e);const t=`/examples/${e}`;await this.caller.call(async()=>{const r=await this._fetch(this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await p(r,`delete ${t}`,!0),r})}async updateExample(e,t){let r;t?r=e:r=e.id,_(r);let a;t?a={id:r,...t}:a=e;let i;return a.dataset_id!==void 0?i=a.dataset_id:i=(await this.readExample(r)).dataset_id,this._updateExamplesMultipart(i,[a])}async updateExamples(e){let t;return e[0].dataset_id===void 0?t=(await this.readExample(e[0].id)).dataset_id:t=e[0].dataset_id,this._updateExamplesMultipart(t,e)}async readDatasetVersion({datasetId:e,datasetName:t,asOf:r,tag:a}){let i;if(e?i=e:i=(await this.readDataset({datasetName:t})).id,_(i),r&&a||!r&&!a)throw new Error("Exactly one of asOf and tag must be specified.");const s=new URLSearchParams;return r!==void 0&&s.append("as_of",typeof r=="string"?r:r.toISOString()),a!==void 0&&s.append("tag",a),await(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}/datasets/${i}/version?${s.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await p(l,"read dataset version"),l})).json()}async listDatasetSplits({datasetId:e,datasetName:t,asOf:r}){let a;if(e===void 0&&t===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?a=(await this.readDataset({datasetName:t})).id:a=e,_(a);const i=new URLSearchParams,s=r?typeof r=="string"?r:r?.toISOString():void 0;return s&&i.append("as_of",s),await this._get(`/datasets/${a}/splits`,i)}async updateDatasetSplits({datasetId:e,datasetName:t,splitName:r,exampleIds:a,remove:i=!1}){let s;if(e===void 0&&t===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?s=(await this.readDataset({datasetName:t})).id:s=e,_(s);const o={split_name:r,examples:a.map(c=>(_(c),c)),remove:i},l=JSON.stringify(o);await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${s}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await p(c,"update dataset splits",!0),c})}async evaluateRun(e,t,{sourceInfo:r,loadChildRuns:a,referenceExample:i}={loadChildRuns:!1}){Ze("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.");let s;if(typeof e=="string")s=await this.readRun(e,{loadChildRuns:a});else if(typeof e=="object"&&"id"in e)s=e;else throw new Error(`Invalid run type: ${typeof e}`);s.reference_example_id!==null&&s.reference_example_id!==void 0&&(i=await this.readExample(s.reference_example_id));const o=await t.evaluateRun(s,i),[l,c]=await this._logEvaluationFeedback(o,s,r);return c[0]}async createFeedback(e,t,{score:r,value:a,correction:i,comment:s,sourceInfo:o,feedbackSourceType:l="api",sourceRunId:c,feedbackId:u,feedbackConfig:d,projectId:h,comparativeExperimentId:m}){if(!e&&!h)throw new Error("One of runId or projectId must be provided");if(e&&h)throw new Error("Only one of runId or projectId can be provided");const f={type:l??"api",metadata:o??{}};c!==void 0&&f?.metadata!==void 0&&!f.metadata.__run&&(f.metadata.__run={run_id:c}),f?.metadata!==void 0&&f.metadata.__run?.run_id!==void 0&&_(f.metadata.__run.run_id);const E={id:u??B(),run_id:e,key:t,score:Re(r),value:a,correction:i,comment:s,feedback_source:f,comparative_experiment_id:m,feedbackConfig:d,session_id:h},T=JSON.stringify(E),g=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{const w=await this._fetch(g,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:T});return await p(w,"create feedback",!0),w}),E}async updateFeedback(e,{score:t,value:r,correction:a,comment:i}){const s={};t!=null&&(s.score=Re(t)),r!=null&&(s.value=r),a!=null&&(s.correction=a),i!=null&&(s.comment=i),_(e);const o=JSON.stringify(s);await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await p(l,"update feedback",!0),l})}async readFeedback(e){_(e);const t=`/feedback/${e}`;return await this._get(t)}async deleteFeedback(e){_(e);const t=`/feedback/${e}`;await this.caller.call(async()=>{const r=await this._fetch(this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await p(r,`delete ${t}`,!0),r})}async*listFeedback({runIds:e,feedbackKeys:t,feedbackSourceTypes:r}={}){const a=new URLSearchParams;if(e)for(const i of e)_(i),a.append("run",i);if(t)for(const i of t)a.append("key",i);if(r)for(const i of r)a.append("source",i);for await(const i of this._getPaginated("/feedback",a))yield*i}async createPresignedFeedbackToken(e,t,{expiration:r,feedbackConfig:a}={}){const i={run_id:e,feedback_key:t,feedback_config:a};r?typeof r=="string"?i.expires_at=r:(r?.hours||r?.minutes||r?.days)&&(i.expires_in=r):i.expires_in={hours:3};const s=JSON.stringify(i);return await(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await p(l,"create presigned feedback token"),l})).json()}async createComparativeExperiment({name:e,experimentIds:t,referenceDatasetId:r,createdAt:a,description:i,metadata:s,id:o}){if(t.length===0)throw new Error("At least one experiment is required");if(r||(r=(await this.readProject({projectId:t[0]})).reference_dataset_id),!r==null)throw new Error("A reference dataset is required");const l={id:o,name:e,experiment_ids:t,reference_dataset_id:r,description:i,created_at:(a??new Date)?.toISOString(),extra:{}};s&&(l.extra.metadata=s);const c=JSON.stringify(l);return(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await p(d,"create comparative experiment"),d})).json()}async*listPresignedFeedbackTokens(e){_(e);const t=new URLSearchParams({run_id:e});for await(const r of this._getPaginated("/feedback/tokens",t))yield*r}_selectEvalResults(e){let t;return"results"in e?t=e.results:Array.isArray(e)?t=e:t=[e],t}async _logEvaluationFeedback(e,t,r){const a=this._selectEvalResults(e),i=[];for(const s of a){let o=r||{};s.evaluatorInfo&&(o={...s.evaluatorInfo,...o});let l=null;s.targetRunId?l=s.targetRunId:t&&(l=t.id),i.push(await this.createFeedback(l,s.key,{score:s.score,value:s.value,comment:s.comment,correction:s.correction,sourceInfo:o,sourceRunId:s.sourceRunId,feedbackConfig:s.feedbackConfig,feedbackSourceType:"model"}))}return[a,i]}async logEvaluationFeedback(e,t,r){const[a]=await this._logEvaluationFeedback(e,t,r);return a}async*listAnnotationQueues(e={}){const{queueIds:t,name:r,nameContains:a,limit:i}=e,s=new URLSearchParams;t&&t.forEach((l,c)=>{_(l,`queueIds[${c}]`),s.append("ids",l)}),r&&s.append("name",r),a&&s.append("name_contains",a),s.append("limit",(i!==void 0?Math.min(i,100):100).toString());let o=0;for await(const l of this._getPaginated("/annotation-queues",s))if(yield*l,o++,i!==void 0&&o>=i)break}async createAnnotationQueue(e){const{name:t,description:r,queueId:a,rubricInstructions:i}=e,s={name:t,description:r,id:a||B(),rubric_instructions:i},o=JSON.stringify(Object.fromEntries(Object.entries(s).filter(([c,u])=>u!==void 0)));return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await p(c,"create annotation queue"),c})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${_(e,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await p(r,"read annotation queue"),r})).json()}async updateAnnotationQueue(e,t){const{name:r,description:a,rubricInstructions:i}=t,s=JSON.stringify({name:r,description:a,rubric_instructions:i});await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/annotation-queues/${_(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await p(o,"update annotation queue",!0),o})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/annotation-queues/${_(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await p(t,"delete annotation queue",!0),t})}async addRunsToAnnotationQueue(e,t){const r=JSON.stringify(t.map((a,i)=>_(a,`runIds[${i}]`).toString()));await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/annotation-queues/${_(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await p(a,"add runs to annotation queue",!0),a})}async getRunFromAnnotationQueue(e,t){const r=`/annotation-queues/${_(e,"queueId")}/run`;return(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${r}/${t}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await p(i,"get run from annotation queue"),i})).json()}async deleteRunFromAnnotationQueue(e,t){await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${_(e,"queueId")}/runs/${_(t,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await p(r,"delete run from annotation queue",!0),r})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${_(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await p(r,"get size from annotation queue"),r})).json()}async _currentTenantIsOwner(e){const t=await this._getSettings();return e=="-"||t.tenant_handle===e}async _ownerConflictError(e,t){const r=await this._getSettings();return new Error(`Cannot ${e} for another tenant.
34
+
35
+ Current tenant: ${r.tenant_handle}
36
+
37
+ Requested tenant: ${t}`)}async _getLatestCommitHash(e){const r=await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await p(a,"get latest commit hash"),a})).json();if(r.commits.length!==0)return r.commits[0].commit_hash}async _likeOrUnlikePrompt(e,t){const[r,a,i]=M(e),s=JSON.stringify({like:t});return(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}/likes/${r}/${a}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await p(l,`${t?"like":"unlike"} prompt`),l})).json()}async _getPromptUrl(e){const[t,r,a]=M(e);if(await this._currentTenantIsOwner(t)){const i=await this._getSettings();return a!=="latest"?`${this.getHostUrl()}/prompts/${r}/${a.substring(0,8)}?organizationId=${i.id}`:`${this.getHostUrl()}/prompts/${r}?organizationId=${i.id}`}else return a!=="latest"?`${this.getHostUrl()}/hub/${t}/${r}/${a.substring(0,8)}`:`${this.getHostUrl()}/hub/${t}/${r}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){for await(const t of this._getPaginated(`/commits/${e}/`,new URLSearchParams,r=>r.commits))yield*t}async*listPrompts(e){const t=new URLSearchParams;t.append("sort_field",e?.sortField??"updated_at"),t.append("sort_direction","desc"),t.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&t.append("is_public",e.isPublic.toString()),e?.query&&t.append("query",e.query);for await(const r of this._getPaginated("/repos",t,a=>a.repos))yield*r}async getPrompt(e){const[t,r,a]=M(e),s=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/repos/${t}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return o?.status===404?null:(await p(o,"get prompt"),o)}))?.json();return s?.repo?s.repo:null}async createPrompt(e,t){const r=await this._getSettings();if(t?.isPublic&&!r.tenant_handle)throw new Error(`Cannot create a public prompt without first
38
+
39
+ creating a LangChain Hub handle.
40
+ You can add a handle by creating a public prompt at:
41
+
42
+ https://smith.langchain.com/prompts`);const[a,i,s]=M(e);if(!await this._currentTenantIsOwner(a))throw await this._ownerConflictError("create a prompt",a);const o={repo_handle:i,...t?.description&&{description:t.description},...t?.readme&&{readme:t.readme},...t?.tags&&{tags:t.tags},is_public:!!t?.isPublic},l=JSON.stringify(o),c=await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await p(d,"create prompt"),d}),{repo:u}=await c.json();return u}async createCommit(e,t,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[a,i,s]=M(e),o=r?.parentCommitHash==="latest"||!r?.parentCommitHash?await this._getLatestCommitHash(`${a}/${i}`):r?.parentCommitHash,l={manifest:JSON.parse(JSON.stringify(t)),parent_commit:o},c=JSON.stringify(l),d=await(await this.caller.call(async()=>{const h=await this._fetch(`${this.apiUrl}/commits/${a}/${i}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await p(h,"create commit"),h})).json();return this._getPromptUrl(`${a}/${i}${d.commit_hash?`:${d.commit_hash}`:""}`)}async updateExamplesMultipart(e,t=[]){return this._updateExamplesMultipart(e,t)}async _updateExamplesMultipart(e,t=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const r=new FormData;for(const s of t){const o=s.id,l={...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split}},c=j(l,`Serializing body for example with id: ${o}`),u=new Blob([c],{type:"application/json"});if(r.append(o,u),s.inputs){const d=j(s.inputs,`Serializing inputs for example with id: ${o}`),h=new Blob([d],{type:"application/json"});r.append(`${o}.inputs`,h)}if(s.outputs){const d=j(s.outputs,`Serializing outputs whle updating example with id: ${o}`),h=new Blob([d],{type:"application/json"});r.append(`${o}.outputs`,h)}if(s.attachments)for(const[d,h]of Object.entries(s.attachments)){let m,f;Array.isArray(h)?[m,f]=h:(m=h.mimeType,f=h.data);const E=new Blob([f],{type:`${m}; length=${f.byteLength}`});r.append(`${o}.attachment.${d}`,E)}if(s.attachments_operations){const d=j(s.attachments_operations,`Serializing attachments while updating example with id: ${o}`),h=new Blob([d],{type:"application/json"});r.append(`${o}.attachments_operations`,h)}}const a=e??t[0]?.dataset_id;return(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${a}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await p(s,"update examples"),s})).json()}async uploadExamplesMultipart(e,t=[]){return this._uploadExamplesMultipart(e,t)}async _uploadExamplesMultipart(e,t=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const r=new FormData;for(const i of t){const s=(i.id??B()).toString(),o={created_at:i.created_at,...i.metadata&&{metadata:i.metadata},...i.split&&{split:i.split},...i.source_run_id&&{source_run_id:i.source_run_id},...i.use_source_run_io&&{use_source_run_io:i.use_source_run_io},...i.use_source_run_attachments&&{use_source_run_attachments:i.use_source_run_attachments}},l=j(o,`Serializing body for uploaded example with id: ${s}`),c=new Blob([l],{type:"application/json"});if(r.append(s,c),i.inputs){const u=j(i.inputs,`Serializing inputs for uploaded example with id: ${s}`),d=new Blob([u],{type:"application/json"});r.append(`${s}.inputs`,d)}if(i.outputs){const u=j(i.outputs,`Serializing outputs for uploaded example with id: ${s}`),d=new Blob([u],{type:"application/json"});r.append(`${s}.outputs`,d)}if(i.attachments)for(const[u,d]of Object.entries(i.attachments)){let h,m;Array.isArray(d)?[h,m]=d:(h=d.mimeType,m=d.data);const f=new Blob([m],{type:`${h}; length=${m.byteLength}`});r.append(`${s}.attachment.${u}`,f)}}return(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await p(i,"upload examples"),i})).json()}async updatePrompt(e,t){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[r,a]=M(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("update a prompt",r);const i={};if(t?.description!==void 0&&(i.description=t.description),t?.readme!==void 0&&(i.readme=t.readme),t?.tags!==void 0&&(i.tags=t.tags),t?.isPublic!==void 0&&(i.is_public=t.isPublic),t?.isArchived!==void 0&&(i.is_archived=t.isArchived),Object.keys(i).length===0)throw new Error("No valid update options provided");const s=JSON.stringify(i);return(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}/repos/${r}/${a}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await p(l,"update prompt"),l})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[t,r,a]=M(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("delete a prompt",t);return(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/repos/${t}/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await p(s,"delete prompt"),s})).json()}async pullPromptCommit(e,t){const[r,a,i]=M(e),o=await(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}/commits/${r}/${a}/${i}${t?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await p(l,"pull prompt commit"),l})).json();return{owner:r,repo:a,commit_hash:o.commit_hash,manifest:o.manifest,examples:o.examples}}async _pullPrompt(e,t){const r=await this.pullPromptCommit(e,{includeModel:t?.includeModel});return JSON.stringify(r.manifest)}async pushPrompt(e,t){return await this.promptExists(e)?t&&Object.keys(t).some(a=>a!=="object")&&await this.updatePrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}):await this.createPrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}),t?.object?await this.createCommit(e,t?.object,{parentCommitHash:t?.parentCommitHash}):await this._getPromptUrl(e)}async clonePublicDataset(e,t={}){const{sourceApiUrl:r=this.apiUrl,datasetName:a}=t,[i,s]=this.parseTokenOrUrl(e,r),o=new X({apiUrl:i,apiKey:"placeholder"}),l=await o.readSharedDataset(s),c=a||l.name;try{if(await this.hasDataset({datasetId:c})){console.log(`Dataset ${c} already exists in your tenant. Skipping.`);return}}catch{}const u=await o.listSharedExamples(s),d=await this.createDataset(c,{description:l.description,dataType:l.data_type||"kv",inputsSchema:l.inputs_schema_definition??void 0,outputsSchema:l.outputs_schema_definition??void 0});try{await this.createExamples({inputs:u.map(h=>h.inputs),outputs:u.flatMap(h=>h.outputs?[h.outputs]:[]),datasetId:d.id})}catch(h){throw console.error(`An error occurred while creating dataset ${c}. You should delete it manually.`),h}}parseTokenOrUrl(e,t,r=2,a="dataset"){try{return _(e),[t,e]}catch{}try{const s=new URL(e).pathname.split("/").filter(o=>o!=="");if(s.length>=r){const o=s[s.length-r];return[t,o]}else throw new Error(`Invalid public ${a} URL: ${e}`)}catch{throw new Error(`Invalid public ${a} URL or token: ${e}`)}}async awaitPendingTraceBatches(){if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await sr()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}}function xe(n){return"dataset_id"in n||"dataset_name"in n}const Ir=n=>!!["TRACING_V2","TRACING"].find(t=>R(t)==="true"),oe=Symbol.for("lc:context_variables");function Pr(n){return n.replace(/[-:.]/g,"")}function rt(n,e,t=1){const r=t.toFixed(0).slice(0,3).padStart(3,"0"),a=`${new Date(n).toISOString().slice(0,-1)}${r}Z`;return{dottedOrder:Pr(a)+e,microsecondPrecisionDatestring:a}}class Z{constructor(e,t,r,a){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=t,this.project_name=r,this.replicas=a}static fromHeader(e){const t=e.split(",");let r={},a=[],i,s;for(const o of t){const[l,c]=o.split("="),u=decodeURIComponent(c);l==="langsmith-metadata"?r=JSON.parse(u):l==="langsmith-tags"?a=u.split(","):l==="langsmith-project"?i=u:l==="langsmith-replicas"&&(s=JSON.parse(u))}return new Z(r,a,i,s)}toHeader(){const e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&e.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),e.join(",")}}class N{constructor(e){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),$r(e)){Object.assign(this,{...e});return}const t=N.getDefaultConfig(),{metadata:r,...a}=e,i=a.client??N.getSharedClient(),s={...r,...a?.extra?.metadata};if(a.extra={...a.extra,metadata:s},Object.assign(this,{...t,...a,client:i}),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=Cr(this.replicas),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order){const{dottedOrder:o,microsecondPrecisionDatestring:l}=rt(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+o:this.dotted_order=o,this._serialized_start_time=l}}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){return{id:B(),run_type:"chain",project_name:Jt(),child_runs:[],api_url:k("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:k("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return N.sharedClient||(N.sharedClient=new X),N.sharedClient}createChild(e){const t=this.child_execution_order+1,r=new N({...e,parent_run:this,project_name:this.project_name,replicas:this.replicas,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:t,child_execution_order:t});oe in this&&(r[oe]=this[oe]);const a=Symbol.for("lc:child_config"),i=e.extra?.[a]??this.extra[a];if(jr(i)){const l={...i},c=Rr(l.callbacks)?l.callbacks.copy?.():void 0;c&&(Object.assign(c,{_parentRunId:r.id}),c.handlers?.find(at)?.updateFromRunTree?.(r),l.callbacks=c),r.extra[a]=l}const s=new Set;let o=this;for(;o!=null&&!s.has(o.id);)s.add(o.id),o.child_execution_order=Math.max(o.child_execution_order,t),o=o.parent_run;return this.child_runs.push(r),r}async end(e,t,r=Date.now(),a){this.outputs=this.outputs??e,this.error=this.error??t,this.end_time=this.end_time??r,a&&Object.keys(a).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...a}}:{metadata:a})}_convertToCreate(e,t,r=!0){const a=e.extra??{};if(a?.runtime?.library===void 0&&(a.runtime||(a.runtime={}),t))for(const[o,l]of Object.entries(t))a.runtime[o]||(a.runtime[o]=l);let i,s;return r?(s=e.parent_run?.id??e.parent_run_id,i=[]):(i=e.child_runs.map(o=>this._convertToCreate(o,t,r)),s=void 0),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:a,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:i,parent_run_id:s,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_remapForProject(e,t,r=!0){const a=this._convertToCreate(this,t,r);if(e===this.project_name)return a;const i=d=>_e(`${d}:${e}`,_e.DNS),s=i(a.id),o=a.trace_id?i(a.trace_id):void 0,l=a.parent_run_id?i(a.parent_run_id):void 0;let c;if(a.dotted_order){const d=xr(a.dotted_order),h=[];for(let f=0;f<d.length-1;f++){const[E,T]=d[f],g=i(T);h.push(E.toISOString().replace(/[-:]/g,"").replace(".","")+g)}const[m]=d[d.length-1];h.push(m.toISOString().replace(/[-:]/g,"").replace(".","")+s),c=h.join(".")}else c=void 0;return{...a,id:s,trace_id:o,parent_run_id:l,dotted_order:c,session_name:e}}async postRun(e=!0){try{const t=Qe();if(this.replicas&&this.replicas.length>0)for(const{projectName:r,apiKey:a,apiUrl:i,workspaceId:s}of this.replicas){const o=this._remapForProject(r??this.project_name,t,!0);await this.client.createRun(o,{apiKey:a,apiUrl:i,workspaceId:s})}else{const r=this._convertToCreate(this,t,e);await this.client.createRun(r)}if(!e){Ze("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(const r of this.child_runs)await r.postRun(!1)}}catch(t){console.error(`Error in postRun for run ${this.id}:`,t)}}async patchRun(e){if(this.replicas&&this.replicas.length>0)for(const{projectName:t,apiKey:r,apiUrl:a,workspaceId:i,updates:s}of this.replicas){const o=this._remapForProject(t??this.project_name),l={id:o.id,outputs:o.outputs,error:o.error,parent_run_id:o.parent_run_id,session_name:o.session_name,reference_example_id:o.reference_example_id,end_time:o.end_time,dotted_order:o.dotted_order,trace_id:o.trace_id,events:o.events,tags:o.tags,extra:o.extra,attachments:this.attachments,...s};e?.excludeInputs||(l.inputs=o.inputs),await this.client.updateRun(o.id,l,{apiKey:r,apiUrl:a,workspaceId:i})}else try{const t={end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:this.parent_run?.id??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};e?.excludeInputs||(t.inputs=this.inputs),await this.client.updateRun(this.id,t)}catch(t){console.error(`Error in patchRun for run ${this.id}`,t)}}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),typeof e=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(e,t){const r=e?.callbacks;let a,i,s,o=Ir();if(r){const c=r?.getParentRunId?.()??"",u=r?.handlers?.find(d=>d?.name=="langchain_tracer");a=u?.getRun?.(c),i=u?.projectName,s=u?.client,o=o||!!u}return a?new N({name:a.name,id:a.id,trace_id:a.trace_id,dotted_order:a.dotted_order,client:s,tracingEnabled:o,project_name:i,tags:[...new Set((a?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...a?.extra?.metadata,...e?.metadata}}}).createChild(t):new N({...t,client:s,tracingEnabled:o,project_name:i})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,t){const r="get"in e&&typeof e.get=="function"?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,a=r["langsmith-trace"];if(!a||typeof a!="string")return;const i=a.trim(),s=i.split(".").map(c=>{const[u,d]=c.split("Z");return{strTime:u,time:Date.parse(u+"Z"),uuid:d}}),o=s[0].uuid,l={...t,name:t?.name??"parent",run_type:t?.run_type??"chain",start_time:t?.start_time??Date.now(),id:s.at(-1)?.uuid,trace_id:o,dotted_order:i};if(r.baggage&&typeof r.baggage=="string"){const c=Z.fromHeader(r.baggage);l.metadata=c.metadata,l.tags=c.tags,l.project_name=c.project_name,l.replicas=c.replicas}return new N(l)}toHeaders(e){const t={"langsmith-trace":this.dotted_order,baggage:new Z(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(const[r,a]of Object.entries(t))e.set(r,a);return t}}Object.defineProperty(N,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function $r(n){return n!=null&&typeof n.createChild=="function"&&typeof n.postRun=="function"}function at(n){return typeof n=="object"&&n!=null&&typeof n.name=="string"&&n.name==="langchain_tracer"}function Ne(n){return Array.isArray(n)&&n.some(e=>at(e))}function Rr(n){return typeof n=="object"&&n!=null&&Array.isArray(n.handlers)}function jr(n){return n!=null&&typeof n.callbacks=="object"&&(Ne(n.callbacks?.handlers)||Ne(n.callbacks))}function xr(n){return n.split(".").map(t=>{const r=t.slice(0,-36),a=t.slice(-36),i=parseInt(r.slice(0,4)),s=parseInt(r.slice(4,6))-1,o=parseInt(r.slice(6,8)),l=parseInt(r.slice(9,11)),c=parseInt(r.slice(11,13)),u=parseInt(r.slice(13,15)),d=parseInt(r.slice(15,21));return[new Date(i,s,o,l,c,u,d/1e3),a]})}function Nr(){const n=k("LANGSMITH_RUNS_ENDPOINTS");if(!n)return[];try{const e=JSON.parse(n);if(Array.isArray(e)){const t=[];for(const r of e){if(typeof r!="object"||r===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof r}`);continue}if(typeof r.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof r.api_url}`);continue}if(typeof r.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof r.api_key}`);continue}t.push({apiUrl:r.api_url.replace(/\/$/,""),apiKey:r.api_key})}return t}else if(typeof e=="object"&&e!==null){kr(e);const t=[];for(const[r,a]of Object.entries(e)){const i=r.replace(/\/$/,"");if(typeof a=="string")t.push({apiUrl:i,apiKey:a});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${r}: expected string, got ${typeof a}`);continue}}return t}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof e}`),[]}catch(e){if(pr(e))throw e;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}function Cr(n){return n?n.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):Nr()}function kr(n){if(Object.keys(n).length>0&&R("ENDPOINT"))throw new hr}var Lr={};const Ur=()=>typeof window<"u"&&typeof window.document<"u",Mr=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Dr=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),me=()=>typeof Deno<"u",Br=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!me(),Gr=()=>{let n;return Ur()?n="browser":Br()?n="node":Mr()?n="webworker":Dr()?n="jsdom":me()?n="deno":n="other",n};let le;function Fr(){return le===void 0&&(le={library:"langchain-js",runtime:Gr()}),le}function Hr(n){try{return typeof process<"u"?Lr?.[n]:me()?Deno?.env.get(n):void 0}catch{return}}class zr{}function da(n){return"lc_prefer_streaming"in n&&n.lc_prefer_streaming}class fe extends zr{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,Ue(this.constructor)]}constructor(e){super(),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ignoreLLM",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreChain",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreAgent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreRetriever",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreCustomEvent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"raiseError",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"awaitHandlers",{enumerable:!0,configurable:!0,writable:!0,value:Hr("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"}),this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return q.prototype.toJSON.call(this)}toJSONNotImplemented(){return q.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends fe{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:B()}),Object.assign(this,e)}}return new t}}const ha=n=>{const e=n;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"},Jr=n=>{if(n)return n.events=n.events??[],n.child_runs=n.child_runs??[],n};function he(n,e){if(n)return new N({...n,start_time:n._serialized_start_time??n.start_time,parent_run:he(e),child_runs:n.child_runs.map(t=>he(t)).filter(t=>t!==void 0),extra:{...n.extra,runtime:Fr()},tracingEnabled:!1})}function ce(n,e){return n&&!Array.isArray(n)&&typeof n=="object"?n:{[e]:n}}function pa(n){return typeof n._addRunToRunMap=="function"}class qr extends fe{constructor(e){super(...arguments),Object.defineProperty(this,"runMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"runTreeMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"usesRunTreeMap",{enumerable:!0,configurable:!0,writable:!0,value:!1})}copy(){return this}getRunById(e){if(e!==void 0)return this.usesRunTreeMap?Jr(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`
43
+
44
+ ${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){const{dottedOrder:t,microsecondPrecisionDatestring:r}=rt(new Date(e.start_time).getTime(),e.id,e.execution_order),a={...e},i=this.getRunById(a.parent_run_id);if(a.parent_run_id!==void 0?i&&(this._addChildRun(i,a),i.child_execution_order=Math.max(i.child_execution_order,a.child_execution_order),a.trace_id=i.trace_id,i.dotted_order!==void 0&&(a.dotted_order=[i.dotted_order,t].join("."),a._serialized_start_time=r)):(a.trace_id=a.id,a.dotted_order=t,a._serialized_start_time=r),this.usesRunTreeMap){const s=he(a,i);s!==void 0&&this.runTreeMap.set(a.id,s)}else this.runMap.set(a.id,a);return a}async _endTrace(e){const t=e.parent_run_id!==void 0&&this.getRunById(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),await this.onRunUpdate?.(e),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){const t=e!==void 0&&this.getRunById(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,r,a,i,s,o,l){const c=this._getExecutionOrder(a),u=Date.now(),d=o?{...i,metadata:o}:i,h={id:r,name:l??e.id[e.id.length-1],parent_run_id:a,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:d??{},tags:s||[]};return this._addRunToRunMap(h)}async handleLLMStart(e,t,r,a,i,s,o,l){const c=this.getRunById(r)??this._createRunForLLMStart(e,t,r,a,i,s,o,l);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(e,t,r,a,i,s,o,l){const c=this._getExecutionOrder(a),u=Date.now(),d=o?{...i,metadata:o}:i,h={id:r,name:l??e.id[e.id.length-1],parent_run_id:a,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:d??{},tags:s||[]};return this._addRunToRunMap(h)}async handleChatModelStart(e,t,r,a,i,s,o,l){const c=this.getRunById(r)??this._createRunForChatModelStart(e,t,r,a,i,s,o,l);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(e,t,r,a,i){const s=this.getRunById(t);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.outputs=e,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(e,t,r,a,i){const s=this.getRunById(t);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(e),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(e,t,r,a,i,s,o,l){const c=this._getExecutionOrder(a),u=Date.now(),d={id:r,name:l??e.id[e.id.length-1],parent_run_id:a,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:t,execution_order:c,child_execution_order:c,run_type:o??"chain",child_runs:[],extra:s?{metadata:s}:{},tags:i||[]};return this._addRunToRunMap(d)}async handleChainStart(e,t,r,a,i,s,o,l){const c=this.getRunById(r)??this._createRunForChainStart(e,t,r,a,i,s,o,l);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(e,t,r,a,i){const s=this.getRunById(t);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.outputs=ce(e,"output"),s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),i?.inputs!==void 0&&(s.inputs=ce(i.inputs,"input")),await this.onChainEnd?.(s),await this._endTrace(s),s}async handleChainError(e,t,r,a,i){const s=this.getRunById(t);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(e),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),i?.inputs!==void 0&&(s.inputs=ce(i.inputs,"input")),await this.onChainError?.(s),await this._endTrace(s),s}_createRunForToolStart(e,t,r,a,i,s,o){const l=this._getExecutionOrder(a),c=Date.now(),u={id:r,name:o??e.id[e.id.length-1],parent_run_id:a,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:t},execution_order:l,child_execution_order:l,run_type:"tool",child_runs:[],extra:s?{metadata:s}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleToolStart(e,t,r,a,i,s,o){const l=this.getRunById(r)??this._createRunForToolStart(e,t,r,a,i,s,o);return await this.onRunCreate?.(l),await this.onToolStart?.(l),l}async handleToolEnd(e,t){const r=this.getRunById(t);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onToolEnd?.(r),await this._endTrace(r),r}async handleToolError(e,t){const r=this.getRunById(t);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onToolError?.(r),await this._endTrace(r),r}async handleAgentAction(e,t){const r=this.getRunById(t);if(!r||r?.run_type!=="chain")return;const a=r;a.actions=a.actions||[],a.actions.push(e),a.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentAction?.(r)}async handleAgentEnd(e,t){const r=this.getRunById(t);!r||r?.run_type!=="chain"||(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentEnd?.(r))}_createRunForRetrieverStart(e,t,r,a,i,s,o){const l=this._getExecutionOrder(a),c=Date.now(),u={id:r,name:o??e.id[e.id.length-1],parent_run_id:a,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:t},execution_order:l,child_execution_order:l,run_type:"retriever",child_runs:[],extra:s?{metadata:s}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleRetrieverStart(e,t,r,a,i,s,o){const l=this.getRunById(r)??this._createRunForRetrieverStart(e,t,r,a,i,s,o);return await this.onRunCreate?.(l),await this.onRetrieverStart?.(l),l}async handleRetrieverEnd(e,t){const r=this.getRunById(t);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onRetrieverEnd?.(r),await this._endTrace(r),r}async handleRetrieverError(e,t){const r=this.getRunById(t);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onRetrieverError?.(r),await this._endTrace(r),r}async handleText(e,t){const r=this.getRunById(t);!r||r?.run_type!=="chain"||(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:e}}),await this.onText?.(r))}async handleLLMNewToken(e,t,r,a,i,s){const o=this.getRunById(r);if(!o||o?.run_type!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return o.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:e,idx:t,chunk:s?.chunk}}),await this.onLLMNewToken?.(o,e,{chunk:s?.chunk}),o}}function A(n,e){return`${n.open}${e}${n.close}`}function x(n,e){try{return JSON.stringify(n,null,2)}catch{return e}}function Ce(n){return typeof n=="string"?n.trim():n==null?n:x(n,n.toString())}function D(n){if(!n.end_time)return"";const e=n.end_time-n.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}const{color:$}=ke;class ma extends qr{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"console_callback_handler"})}persistRun(e){return Promise.resolve()}getParents(e){const t=[];let r=e;for(;r.parent_run_id;){const a=this.runMap.get(r.parent_run_id);if(a)t.push(a),r=a;else break}return t}getBreadcrumbs(e){const r=[...this.getParents(e).reverse(),e].map((a,i,s)=>{const o=`${a.execution_order}:${a.run_type}:${a.name}`;return i===s.length-1?A(ke.bold,o):o}).join(" > ");return A($.grey,r)}onChainStart(e){const t=this.getBreadcrumbs(e);console.log(`${A($.green,"[chain/start]")} [${t}] Entering Chain run with input: ${x(e.inputs,"[inputs]")}`)}onChainEnd(e){const t=this.getBreadcrumbs(e);console.log(`${A($.cyan,"[chain/end]")} [${t}] [${D(e)}] Exiting Chain run with output: ${x(e.outputs,"[outputs]")}`)}onChainError(e){const t=this.getBreadcrumbs(e);console.log(`${A($.red,"[chain/error]")} [${t}] [${D(e)}] Chain run errored with error: ${x(e.error,"[error]")}`)}onLLMStart(e){const t=this.getBreadcrumbs(e),r="prompts"in e.inputs?{prompts:e.inputs.prompts.map(a=>a.trim())}:e.inputs;console.log(`${A($.green,"[llm/start]")} [${t}] Entering LLM run with input: ${x(r,"[inputs]")}`)}onLLMEnd(e){const t=this.getBreadcrumbs(e);console.log(`${A($.cyan,"[llm/end]")} [${t}] [${D(e)}] Exiting LLM run with output: ${x(e.outputs,"[response]")}`)}onLLMError(e){const t=this.getBreadcrumbs(e);console.log(`${A($.red,"[llm/error]")} [${t}] [${D(e)}] LLM run errored with error: ${x(e.error,"[error]")}`)}onToolStart(e){const t=this.getBreadcrumbs(e);console.log(`${A($.green,"[tool/start]")} [${t}] Entering Tool run with input: "${Ce(e.inputs.input)}"`)}onToolEnd(e){const t=this.getBreadcrumbs(e);console.log(`${A($.cyan,"[tool/end]")} [${t}] [${D(e)}] Exiting Tool run with output: "${Ce(e.outputs?.output)}"`)}onToolError(e){const t=this.getBreadcrumbs(e);console.log(`${A($.red,"[tool/error]")} [${t}] [${D(e)}] Tool run errored with error: ${x(e.error,"[error]")}`)}onRetrieverStart(e){const t=this.getBreadcrumbs(e);console.log(`${A($.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${x(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){const t=this.getBreadcrumbs(e);console.log(`${A($.cyan,"[retriever/end]")} [${t}] [${D(e)}] Exiting Retriever run with output: ${x(e.outputs,"[outputs]")}`)}onRetrieverError(e){const t=this.getBreadcrumbs(e);console.log(`${A($.red,"[retriever/error]")} [${t}] [${D(e)}] Retriever run errored with error: ${x(e.error,"[error]")}`)}onAgentAction(e){const t=e,r=this.getBreadcrumbs(e);console.log(`${A($.blue,"[agent/action]")} [${r}] Agent selected action: ${x(t.actions[t.actions.length-1],"[action]")}`)}}export{sa as A,fe as B,Be as C,Yr as D,Le as E,la as F,Me as G,ca as H,Xr as I,N as R,ua as S,aa as T,ta as _,G as a,De as b,ht as c,ia as d,na as e,K as f,ea as g,Zr as h,ra as i,Hr as j,He as k,ze as l,Fe as m,Ge as n,X as o,Wr as p,qr as q,Jt as r,pa as s,ma as t,ha as u,q as v,oa as w,da as x,Qr as y,Vr as z};
@@ -1,3 +1,3 @@
1
- import{B as p,c as n,r as o,P as u}from"./langfuse-YA2S23SM-DhR-jd9m.js";import"./zodToJsonSchema-B4lr8sxI.js";import"./index-DkAopXco.js";import"./deep-compare-strict-DtUHXpbW.js";import"./v4-BKrj-4V8.js";class l extends p{constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"examples",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleSelector",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"examplePrompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"suffix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"exampleSeparator",{enumerable:!0,configurable:!0,writable:!0,value:`
1
+ import{B as p,c as n,r as o,P as u}from"./langfuse-YA2S23SM-BaAcgQMN.js";import"./zodToJsonSchema-t7UzpXtO.js";import"./index-C5GpJHbP.js";import"./deep-compare-strict-DtUHXpbW.js";import"./v4-BKrj-4V8.js";class l extends p{constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"examples",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleSelector",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"examplePrompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"suffix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"exampleSeparator",{enumerable:!0,configurable:!0,writable:!0,value:`
2
2
 
3
3
  `}),Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.assign(this,e),this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let t=this.inputVariables;this.partialVariables&&(t=t.concat(Object.keys(this.partialVariables))),n(this.prefix+this.suffix,this.templateFormat,t)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw new Error("One of 'examples' and 'example_selector' should be provided")}async partial(e){const t=this.inputVariables.filter(i=>!(i in e)),a={...this.partialVariables??{},...e},r={...this,inputVariables:t,partialVariables:a};return new l(r)}async format(e){const t=await this.mergePartialAndUserVariables(e),a=await this.getExamples(t),r=await Promise.all(a.map(s=>this.examplePrompt.format(s))),i=[this.prefix,...r,this.suffix].join(this.exampleSeparator);return o(i,this.templateFormat,t)}serialize(){if(this.exampleSelector||!this.examples)throw new Error("Serializing an example selector is not currently supported");if(this.outputParser!==void 0)throw new Error("Serializing an output parser is not currently supported");return{_type:this._getPromptType(),input_variables:this.inputVariables,example_prompt:this.examplePrompt.serialize(),example_separator:this.exampleSeparator,suffix:this.suffix,prefix:this.prefix,template_format:this.templateFormat,examples:this.examples}}static async deserialize(e){const{example_prompt:t}=e;if(!t)throw new Error("Missing example prompt");const a=await u.deserialize(t);let r;if(Array.isArray(e.examples))r=e.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new l({inputVariables:e.input_variables,examplePrompt:a,examples:r,exampleSeparator:e.example_separator,prefix:e.prefix,suffix:e.suffix,templateFormat:e.template_format})}}export{l as FewShotPromptTemplate};