@mcp-use/inspector 0.5.3-canary.8 → 0.5.3

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.
@@ -1,4 +1,4 @@
1
- import{s as Oi,v as se,P as Pe,p as Ht,a as Ga,b as Nr,g as he,c as kr,d as Ke,_ as Ci,$ as xi,e as Ni,f as ki,h as Rr,i as ca,j as Ri,k as Pi,t as Va,l as Pr,V as Mi,m as Li,n as Ut,o as $i,T as ji}from"./chunk-VL2OQCWN-BFKzE0YG.js";import{Z as P,a as Za,o as la,s as ua}from"./index-CKNaXAjV.js";var Di=Object.defineProperty,F=(e,t)=>{for(var n in t)Di(e,n,{get:t[n],enumerable:!0})};function Ue(e){return typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string"&&"source_type"in e&&(e.source_type==="url"||e.source_type==="base64"||e.source_type==="text"||e.source_type==="id")}function da(e){return Ue(e)&&e.source_type==="url"&&"url"in e&&typeof e.url=="string"}function ha(e){return Ue(e)&&e.source_type==="base64"&&"data"in e&&typeof e.data=="string"}function Fi(e){return Ue(e)&&e.source_type==="text"&&"text"in e&&typeof e.text=="string"}function Mr(e){return Ue(e)&&e.source_type==="id"&&"id"in e&&typeof e.id=="string"}function Lr(e){if(Ue(e)){if(e.source_type==="url")return{type:"image_url",image_url:{url:e.url}};if(e.source_type==="base64"){if(!e.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${e.mime_type};base64,${e.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function Ui(e){const t=e.split(";")[0].split("/");if(t.length!==2)throw new Error(`Invalid mime type: "${e}" - does not match type/subtype format.`);const n=t[0].trim(),a=t[1].trim();if(n===""||a==="")throw new Error(`Invalid mime type: "${e}" - type or subtype is empty.`);const r={};for(const s of e.split(";").slice(1)){const i=s.split("=");if(i.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);const o=i[0].trim(),c=i[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${e}".`);r[o]=c}return{type:n,subtype:a,parameters:r}}function $n({dataUrl:e,asTypedArray:t=!1}){const n=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let a;if(n){a=n[1].toLowerCase();const r=t?Uint8Array.from(atob(n[2]),s=>s.charCodeAt(0)):n[2];return{mime_type:a,data:r}}}function Bi(e,t){if(e.type==="text"){if(!t.fromStandardTextBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardTextBlock\` method.`);return t.fromStandardTextBlock(e)}if(e.type==="image"){if(!t.fromStandardImageBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardImageBlock\` method.`);return t.fromStandardImageBlock(e)}if(e.type==="audio"){if(!t.fromStandardAudioBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardAudioBlock\` method.`);return t.fromStandardAudioBlock(e)}if(e.type==="file"){if(!t.fromStandardFileBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardFileBlock\` method.`);return t.fromStandardFileBlock(e)}throw new Error(`Unable to convert content block type '${e.type}' to provider-specific format: not recognized.`)}function $r(e){return typeof e=="object"&&e!==null&&"type"in e&&"content"in e&&(typeof e.content=="string"||Array.isArray(e.content))}function zi(e,t){return t?.[e]||Oi(e)}function Hi(e,t,n){const a={};for(const r in e)Object.hasOwn(e,r)&&(a[t(r,n)]=e[r]);return a}var Gi={};F(Gi,{Serializable:()=>lt,get_lc_unique_name:()=>pa});function qa(e){return Array.isArray(e)?[...e]:{...e}}function Vi(e,t){const n=qa(e);for(const[a,r]of Object.entries(t)){const[s,...i]=a.split(".").reverse();let o=n;for(const c of i.reverse()){if(o[c]===void 0)break;o[c]=qa(o[c]),o=o[c]}o[s]!==void 0&&(o[s]={lc:1,type:"secret",id:[r]})}return n}function pa(e){const t=Object.getPrototypeOf(e);return typeof e.lc_name=="function"&&(typeof t.lc_name!="function"||e.lc_name()!==t.lc_name())?e.lc_name():e.name}var lt=class jr{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,pa(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(t,...n){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(t||{}).filter(([a])=>this.lc_serializable_keys?.includes(a))):this.lc_kwargs=t??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof jr||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const t={},n={},a=Object.keys(this.lc_kwargs).reduce((r,s)=>(r[s]=s in this?this[s]:this.lc_kwargs[s],r),{});for(let r=Object.getPrototypeOf(this);r;r=Object.getPrototypeOf(r))Object.assign(t,Reflect.get(r,"lc_aliases",this)),Object.assign(n,Reflect.get(r,"lc_secrets",this)),Object.assign(a,Reflect.get(r,"lc_attributes",this));return Object.keys(n).forEach(r=>{let s=this,i=a;const[o,...c]=r.split(".").reverse();for(const l of c.reverse()){if(!(l in s)||s[l]===void 0)return;(!(l in i)||i[l]===void 0)&&(typeof s[l]=="object"&&s[l]!=null?i[l]={}:Array.isArray(s[l])&&(i[l]=[])),s=s[l],i=i[l]}o in s&&s[o]!==void 0&&(i[o]=i[o]||s[o])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:Hi(Object.keys(n).length?Vi(a,n):a,zi,t)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function C(e,t){return k(e)&&e.type===t}function k(e){return typeof e=="object"&&e!==null}function Ie(e){return Array.isArray(e)}function S(e){return typeof e=="string"}function we(e){return typeof e=="number"}function fa(e){return e instanceof Uint8Array}function Ja(e){try{return JSON.parse(e)}catch{return}}const vt=e=>e();function Zi(e){if(e.type==="char_location"&&S(e.document_title)&&we(e.start_char_index)&&we(e.end_char_index)&&S(e.cited_text)){const{document_title:t,start_char_index:n,end_char_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"char",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="page_location"&&S(e.document_title)&&we(e.start_page_number)&&we(e.end_page_number)&&S(e.cited_text)){const{document_title:t,start_page_number:n,end_page_number:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"page",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="content_block_location"&&S(e.document_title)&&we(e.start_block_index)&&we(e.end_block_index)&&S(e.cited_text)){const{document_title:t,start_block_index:n,end_block_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"block",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="web_search_result_location"&&S(e.url)&&S(e.title)&&S(e.encrypted_index)&&S(e.cited_text)){const{url:t,title:n,encrypted_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"url",url:t,title:n,startIndex:Number(a),endIndex:Number(a),citedText:r}}if(e.type==="search_result_location"&&S(e.source)&&S(e.title)&&we(e.start_block_index)&&we(e.end_block_index)&&S(e.cited_text)){const{source:t,title:n,start_block_index:a,end_block_index:r,cited_text:s,...i}=e;return{...i,type:"citation",source:"search",url:t,title:n??void 0,startIndex:a,endIndex:r,citedText:s}}}function Dr(e){if(C(e,"document")&&k(e.source)&&"type"in e.source){if(e.source.type==="base64"&&S(e.source.media_type)&&S(e.source.data))return{type:"file",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&S(e.source.url))return{type:"file",url:e.source.url};if(e.source.type==="file"&&S(e.source.file_id))return{type:"file",fileId:e.source.file_id};if(e.source.type==="text"&&S(e.source.data))return{type:"file",mimeType:String(e.source.media_type??"text/plain"),data:e.source.data}}else if(C(e,"image")&&k(e.source)&&"type"in e.source){if(e.source.type==="base64"&&S(e.source.media_type)&&S(e.source.data))return{type:"image",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&S(e.source.url))return{type:"image",url:e.source.url};if(e.source.type==="file"&&S(e.source.file_id))return{type:"image",fileId:e.source.file_id}}}function qi(e){function*t(){for(const n of e){const a=Dr(n);a?yield a:yield n}}return Array.from(t())}function Wa(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const a of n){if(C(a,"text")&&S(a.text)){const{text:r,citations:s,...i}=a;if(Ie(s)&&s.length){const o=s.reduce((c,l)=>{const d=Zi(l);return d?[...c,d]:c},[]);yield{...i,type:"text",text:r,annotations:o};continue}else{yield{...i,type:"text",text:r};continue}}else if(C(a,"thinking")&&S(a.thinking)){const{thinking:r,signature:s,...i}=a;yield{...i,type:"reasoning",reasoning:r,signature:s};continue}else if(C(a,"redacted_thinking")){yield{type:"non_standard",value:a};continue}else if(C(a,"tool_use")&&S(a.name)&&S(a.id)){yield{type:"tool_call",id:a.id,name:a.name,args:a.input};continue}else if(C(a,"input_json_delta")){if(Wi(e)&&e.tool_call_chunks?.length){const r=e.tool_call_chunks[0];yield{type:"tool_call_chunk",id:r.id,name:r.name,args:r.args,index:r.index};continue}}else if(C(a,"server_tool_use")&&S(a.name)&&S(a.id)){const{name:r,id:s}=a;if(r==="web_search"){const i=vt(()=>{if(typeof a.input=="string")return a.input;if(k(a.input)&&S(a.input.query))return a.input.query;if(S(a.partial_json)){const o=Ja(a.partial_json);if(o?.query)return o.query}return""});yield{id:s,type:"server_tool_call",name:"web_search",args:{query:i}};continue}else if(a.name==="code_execution"){const i=vt(()=>{if(typeof a.input=="string")return a.input;if(k(a.input)&&S(a.input.code))return a.input.code;if(S(a.partial_json)){const o=Ja(a.partial_json);if(o?.code)return o.code}return""});yield{id:s,type:"server_tool_call",name:"code_execution",args:{code:i}};continue}}else if(C(a,"web_search_tool_result")&&S(a.tool_use_id)&&Ie(a.content)){const{content:r,tool_use_id:s}=a,i=r.reduce((o,c)=>C(c,"web_search_result")?[...o,c.url]:o,[]);yield{type:"server_tool_call_result",name:"web_search",toolCallId:s,status:"success",output:{urls:i}};continue}else if(C(a,"code_execution_tool_result")&&S(a.tool_use_id)&&k(a.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:a.tool_use_id,status:"success",output:a.content};continue}else if(C(a,"mcp_tool_use")){yield{id:a.id,type:"server_tool_call",name:"mcp_tool_use",args:a.input};continue}else if(C(a,"mcp_tool_result")&&S(a.tool_use_id)&&k(a.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:a.tool_use_id,status:"success",output:a.content};continue}else if(C(a,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:a.input};continue}else if(C(a,"search_result")){yield{id:a.id,type:"non_standard",value:a};continue}else if(C(a,"tool_result")){yield{id:a.id,type:"non_standard",value:a};continue}else{const r=Dr(a);if(r){yield r;continue}}yield{type:"non_standard",value:a}}}return Array.from(t())}const Ji={translateContent:Wa,translateContentChunk:Wa};function Wi(e){return typeof e?._getType=="function"&&typeof e.concat=="function"&&e._getType()==="ai"}function Ki(e){return da(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:ha(e)?{type:e.type,mimeType:e.mime_type??"application/octet-stream",data:e.data,metadata:e.metadata}:Mr(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function Yi(e){return e.map(Ki)}function Qi(e){return!!(C(e,"image_url")&&k(e.image_url)||C(e,"input_audio")&&k(e.input_audio)||C(e,"file")&&k(e.file))}function Xi(e){if(C(e,"image_url")&&k(e.image_url)&&S(e.image_url.url)){const t=$n({dataUrl:e.image_url.url});return t?{type:"image",mimeType:t.mime_type,data:t.data}:{type:"image",url:e.image_url.url}}else{if(C(e,"input_audio")&&k(e.input_audio)&&S(e.input_audio.data)&&S(e.input_audio.format))return{type:"audio",data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};if(C(e,"file")&&k(e.file)&&S(e.file.data)){const t=$n({dataUrl:e.file.data});if(t)return{type:"file",data:t.data,mimeType:t.mime_type};if(S(e.file.file_id))return{type:"file",fileId:e.file.file_id}}}return e}function eo(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...ma(e.content));for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}function to(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...ma(e.content));for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}function ma(e){const t=[];for(const n of e)Qi(n)?t.push(Xi(n)):t.push(n);return t}function no(e){if(e.type==="url_citation"){const{url:t,title:n,start_index:a,end_index:r}=e;return{type:"citation",url:t,title:n,startIndex:a,endIndex:r}}if(e.type==="file_citation"){const{file_id:t,filename:n,index:a}=e;return{type:"citation",title:n,startIndex:a,endIndex:a,fileId:t}}return e}function Fr(e){function*t(){k(e.additional_kwargs?.reasoning)&&Ie(e.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:e.additional_kwargs.reasoning.summary.reduce((r,s)=>k(s)&&S(s.text)?`${r}${s.text}`:r,"")});const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const a of n)if(C(a,"text")){const{text:r,annotations:s,...i}=a;Array.isArray(s)?yield{...i,type:"text",text:String(r),annotations:s.map(no)}:yield{...i,type:"text",text:String(r)}}for(const a of e.tool_calls??[])yield{type:"tool_call",id:a.id,name:a.name,args:a.args};if(k(e.additional_kwargs)&&Ie(e.additional_kwargs.tool_outputs))for(const a of e.additional_kwargs.tool_outputs){if(C(a,"web_search_call")){yield{id:a.id,type:"server_tool_call",name:"web_search",args:{query:a.query}};continue}else if(C(a,"file_search_call")){yield{id:a.id,type:"server_tool_call",name:"file_search",args:{query:a.query}};continue}else if(C(a,"computer_call")){yield{type:"non_standard",value:a};continue}else if(C(a,"code_interpreter_call")){if(S(a.code)&&(yield{id:a.id,type:"server_tool_call",name:"code_interpreter",args:{code:a.code}}),Ie(a.outputs)){const r=vt(()=>{if(a.status!=="in_progress"){if(a.status==="completed")return 0;if(a.status==="incomplete")return 127;if(a.status!=="interpreting"&&a.status==="failed")return 1}});for(const s of a.outputs)if(C(s,"logs")){yield{type:"server_tool_call_result",toolCallId:a.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:r??0,stderr:[0,void 0].includes(r)?void 0:String(s.logs),stdout:[0,void 0].includes(r)?String(s.logs):void 0}};continue}}continue}else if(C(a,"mcp_call")){yield{id:a.id,type:"server_tool_call",name:"mcp_call",args:a.input};continue}else if(C(a,"mcp_list_tools")){yield{id:a.id,type:"server_tool_call",name:"mcp_list_tools",args:a.input};continue}else if(C(a,"mcp_approval_request")){yield{type:"non_standard",value:a};continue}else if(C(a,"image_generation_call")){yield{type:"non_standard",value:a};continue}k(a)&&(yield{type:"non_standard",value:a})}}return Array.from(t())}function ao(e){function*t(){yield*Fr(e);for(const n of e.tool_call_chunks??[])yield{type:"tool_call_chunk",id:n.id,name:n.name,args:n.args}}return Array.from(t())}const ro={translateContent:e=>typeof e.content=="string"?eo(e):Fr(e),translateContentChunk:e=>typeof e.content=="string"?to(e):ao(e)};function so(e,t="pretty"){return t==="pretty"?io(e):JSON.stringify(e)}function io(e){const t=[],n=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,a=Math.floor((80-n.length)/2),r="=".repeat(a),s=n.length%2===0?r:`${r}=`;if(t.push(`${r}${n}${s}`),e.type==="ai"){const i=e;if(i.tool_calls&&i.tool_calls.length>0){t.push("Tool Calls:");for(const o of i.tool_calls){t.push(` ${o.name} (${o.id})`),t.push(` Call ID: ${o.id}`),t.push(" Args:");for(const[c,l]of Object.entries(o.args))t.push(` ${c}: ${l}`)}}}if(e.type==="tool"){const i=e;i.name&&t.push(`Name: ${i.name}`)}return typeof e.content=="string"&&e.content.trim()&&(t.length>1&&t.push(""),t.push(e.content)),t.join(`
1
+ import{s as Oi,v as se,P as Pe,p as Ht,a as Ga,b as Nr,g as he,c as kr,d as Ke,_ as Ci,$ as xi,e as Ni,f as ki,h as Rr,i as ca,j as Ri,k as Pi,t as Va,l as Pr,V as Mi,m as Li,n as Ut,o as $i,T as ji}from"./chunk-VL2OQCWN-lvFdpsKs.js";import{Z as P,a as Za,o as la,s as ua}from"./index-CFpQGWTL.js";var Di=Object.defineProperty,F=(e,t)=>{for(var n in t)Di(e,n,{get:t[n],enumerable:!0})};function Ue(e){return typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string"&&"source_type"in e&&(e.source_type==="url"||e.source_type==="base64"||e.source_type==="text"||e.source_type==="id")}function da(e){return Ue(e)&&e.source_type==="url"&&"url"in e&&typeof e.url=="string"}function ha(e){return Ue(e)&&e.source_type==="base64"&&"data"in e&&typeof e.data=="string"}function Fi(e){return Ue(e)&&e.source_type==="text"&&"text"in e&&typeof e.text=="string"}function Mr(e){return Ue(e)&&e.source_type==="id"&&"id"in e&&typeof e.id=="string"}function Lr(e){if(Ue(e)){if(e.source_type==="url")return{type:"image_url",image_url:{url:e.url}};if(e.source_type==="base64"){if(!e.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${e.mime_type};base64,${e.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function Ui(e){const t=e.split(";")[0].split("/");if(t.length!==2)throw new Error(`Invalid mime type: "${e}" - does not match type/subtype format.`);const n=t[0].trim(),a=t[1].trim();if(n===""||a==="")throw new Error(`Invalid mime type: "${e}" - type or subtype is empty.`);const r={};for(const s of e.split(";").slice(1)){const i=s.split("=");if(i.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);const o=i[0].trim(),c=i[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${e}".`);r[o]=c}return{type:n,subtype:a,parameters:r}}function $n({dataUrl:e,asTypedArray:t=!1}){const n=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let a;if(n){a=n[1].toLowerCase();const r=t?Uint8Array.from(atob(n[2]),s=>s.charCodeAt(0)):n[2];return{mime_type:a,data:r}}}function Bi(e,t){if(e.type==="text"){if(!t.fromStandardTextBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardTextBlock\` method.`);return t.fromStandardTextBlock(e)}if(e.type==="image"){if(!t.fromStandardImageBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardImageBlock\` method.`);return t.fromStandardImageBlock(e)}if(e.type==="audio"){if(!t.fromStandardAudioBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardAudioBlock\` method.`);return t.fromStandardAudioBlock(e)}if(e.type==="file"){if(!t.fromStandardFileBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardFileBlock\` method.`);return t.fromStandardFileBlock(e)}throw new Error(`Unable to convert content block type '${e.type}' to provider-specific format: not recognized.`)}function $r(e){return typeof e=="object"&&e!==null&&"type"in e&&"content"in e&&(typeof e.content=="string"||Array.isArray(e.content))}function zi(e,t){return t?.[e]||Oi(e)}function Hi(e,t,n){const a={};for(const r in e)Object.hasOwn(e,r)&&(a[t(r,n)]=e[r]);return a}var Gi={};F(Gi,{Serializable:()=>lt,get_lc_unique_name:()=>pa});function qa(e){return Array.isArray(e)?[...e]:{...e}}function Vi(e,t){const n=qa(e);for(const[a,r]of Object.entries(t)){const[s,...i]=a.split(".").reverse();let o=n;for(const c of i.reverse()){if(o[c]===void 0)break;o[c]=qa(o[c]),o=o[c]}o[s]!==void 0&&(o[s]={lc:1,type:"secret",id:[r]})}return n}function pa(e){const t=Object.getPrototypeOf(e);return typeof e.lc_name=="function"&&(typeof t.lc_name!="function"||e.lc_name()!==t.lc_name())?e.lc_name():e.name}var lt=class jr{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,pa(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(t,...n){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(t||{}).filter(([a])=>this.lc_serializable_keys?.includes(a))):this.lc_kwargs=t??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof jr||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const t={},n={},a=Object.keys(this.lc_kwargs).reduce((r,s)=>(r[s]=s in this?this[s]:this.lc_kwargs[s],r),{});for(let r=Object.getPrototypeOf(this);r;r=Object.getPrototypeOf(r))Object.assign(t,Reflect.get(r,"lc_aliases",this)),Object.assign(n,Reflect.get(r,"lc_secrets",this)),Object.assign(a,Reflect.get(r,"lc_attributes",this));return Object.keys(n).forEach(r=>{let s=this,i=a;const[o,...c]=r.split(".").reverse();for(const l of c.reverse()){if(!(l in s)||s[l]===void 0)return;(!(l in i)||i[l]===void 0)&&(typeof s[l]=="object"&&s[l]!=null?i[l]={}:Array.isArray(s[l])&&(i[l]=[])),s=s[l],i=i[l]}o in s&&s[o]!==void 0&&(i[o]=i[o]||s[o])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:Hi(Object.keys(n).length?Vi(a,n):a,zi,t)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function C(e,t){return k(e)&&e.type===t}function k(e){return typeof e=="object"&&e!==null}function Ie(e){return Array.isArray(e)}function S(e){return typeof e=="string"}function we(e){return typeof e=="number"}function fa(e){return e instanceof Uint8Array}function Ja(e){try{return JSON.parse(e)}catch{return}}const vt=e=>e();function Zi(e){if(e.type==="char_location"&&S(e.document_title)&&we(e.start_char_index)&&we(e.end_char_index)&&S(e.cited_text)){const{document_title:t,start_char_index:n,end_char_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"char",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="page_location"&&S(e.document_title)&&we(e.start_page_number)&&we(e.end_page_number)&&S(e.cited_text)){const{document_title:t,start_page_number:n,end_page_number:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"page",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="content_block_location"&&S(e.document_title)&&we(e.start_block_index)&&we(e.end_block_index)&&S(e.cited_text)){const{document_title:t,start_block_index:n,end_block_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"block",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="web_search_result_location"&&S(e.url)&&S(e.title)&&S(e.encrypted_index)&&S(e.cited_text)){const{url:t,title:n,encrypted_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"url",url:t,title:n,startIndex:Number(a),endIndex:Number(a),citedText:r}}if(e.type==="search_result_location"&&S(e.source)&&S(e.title)&&we(e.start_block_index)&&we(e.end_block_index)&&S(e.cited_text)){const{source:t,title:n,start_block_index:a,end_block_index:r,cited_text:s,...i}=e;return{...i,type:"citation",source:"search",url:t,title:n??void 0,startIndex:a,endIndex:r,citedText:s}}}function Dr(e){if(C(e,"document")&&k(e.source)&&"type"in e.source){if(e.source.type==="base64"&&S(e.source.media_type)&&S(e.source.data))return{type:"file",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&S(e.source.url))return{type:"file",url:e.source.url};if(e.source.type==="file"&&S(e.source.file_id))return{type:"file",fileId:e.source.file_id};if(e.source.type==="text"&&S(e.source.data))return{type:"file",mimeType:String(e.source.media_type??"text/plain"),data:e.source.data}}else if(C(e,"image")&&k(e.source)&&"type"in e.source){if(e.source.type==="base64"&&S(e.source.media_type)&&S(e.source.data))return{type:"image",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&S(e.source.url))return{type:"image",url:e.source.url};if(e.source.type==="file"&&S(e.source.file_id))return{type:"image",fileId:e.source.file_id}}}function qi(e){function*t(){for(const n of e){const a=Dr(n);a?yield a:yield n}}return Array.from(t())}function Wa(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const a of n){if(C(a,"text")&&S(a.text)){const{text:r,citations:s,...i}=a;if(Ie(s)&&s.length){const o=s.reduce((c,l)=>{const d=Zi(l);return d?[...c,d]:c},[]);yield{...i,type:"text",text:r,annotations:o};continue}else{yield{...i,type:"text",text:r};continue}}else if(C(a,"thinking")&&S(a.thinking)){const{thinking:r,signature:s,...i}=a;yield{...i,type:"reasoning",reasoning:r,signature:s};continue}else if(C(a,"redacted_thinking")){yield{type:"non_standard",value:a};continue}else if(C(a,"tool_use")&&S(a.name)&&S(a.id)){yield{type:"tool_call",id:a.id,name:a.name,args:a.input};continue}else if(C(a,"input_json_delta")){if(Wi(e)&&e.tool_call_chunks?.length){const r=e.tool_call_chunks[0];yield{type:"tool_call_chunk",id:r.id,name:r.name,args:r.args,index:r.index};continue}}else if(C(a,"server_tool_use")&&S(a.name)&&S(a.id)){const{name:r,id:s}=a;if(r==="web_search"){const i=vt(()=>{if(typeof a.input=="string")return a.input;if(k(a.input)&&S(a.input.query))return a.input.query;if(S(a.partial_json)){const o=Ja(a.partial_json);if(o?.query)return o.query}return""});yield{id:s,type:"server_tool_call",name:"web_search",args:{query:i}};continue}else if(a.name==="code_execution"){const i=vt(()=>{if(typeof a.input=="string")return a.input;if(k(a.input)&&S(a.input.code))return a.input.code;if(S(a.partial_json)){const o=Ja(a.partial_json);if(o?.code)return o.code}return""});yield{id:s,type:"server_tool_call",name:"code_execution",args:{code:i}};continue}}else if(C(a,"web_search_tool_result")&&S(a.tool_use_id)&&Ie(a.content)){const{content:r,tool_use_id:s}=a,i=r.reduce((o,c)=>C(c,"web_search_result")?[...o,c.url]:o,[]);yield{type:"server_tool_call_result",name:"web_search",toolCallId:s,status:"success",output:{urls:i}};continue}else if(C(a,"code_execution_tool_result")&&S(a.tool_use_id)&&k(a.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:a.tool_use_id,status:"success",output:a.content};continue}else if(C(a,"mcp_tool_use")){yield{id:a.id,type:"server_tool_call",name:"mcp_tool_use",args:a.input};continue}else if(C(a,"mcp_tool_result")&&S(a.tool_use_id)&&k(a.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:a.tool_use_id,status:"success",output:a.content};continue}else if(C(a,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:a.input};continue}else if(C(a,"search_result")){yield{id:a.id,type:"non_standard",value:a};continue}else if(C(a,"tool_result")){yield{id:a.id,type:"non_standard",value:a};continue}else{const r=Dr(a);if(r){yield r;continue}}yield{type:"non_standard",value:a}}}return Array.from(t())}const Ji={translateContent:Wa,translateContentChunk:Wa};function Wi(e){return typeof e?._getType=="function"&&typeof e.concat=="function"&&e._getType()==="ai"}function Ki(e){return da(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:ha(e)?{type:e.type,mimeType:e.mime_type??"application/octet-stream",data:e.data,metadata:e.metadata}:Mr(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function Yi(e){return e.map(Ki)}function Qi(e){return!!(C(e,"image_url")&&k(e.image_url)||C(e,"input_audio")&&k(e.input_audio)||C(e,"file")&&k(e.file))}function Xi(e){if(C(e,"image_url")&&k(e.image_url)&&S(e.image_url.url)){const t=$n({dataUrl:e.image_url.url});return t?{type:"image",mimeType:t.mime_type,data:t.data}:{type:"image",url:e.image_url.url}}else{if(C(e,"input_audio")&&k(e.input_audio)&&S(e.input_audio.data)&&S(e.input_audio.format))return{type:"audio",data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};if(C(e,"file")&&k(e.file)&&S(e.file.data)){const t=$n({dataUrl:e.file.data});if(t)return{type:"file",data:t.data,mimeType:t.mime_type};if(S(e.file.file_id))return{type:"file",fileId:e.file.file_id}}}return e}function eo(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...ma(e.content));for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}function to(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...ma(e.content));for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}function ma(e){const t=[];for(const n of e)Qi(n)?t.push(Xi(n)):t.push(n);return t}function no(e){if(e.type==="url_citation"){const{url:t,title:n,start_index:a,end_index:r}=e;return{type:"citation",url:t,title:n,startIndex:a,endIndex:r}}if(e.type==="file_citation"){const{file_id:t,filename:n,index:a}=e;return{type:"citation",title:n,startIndex:a,endIndex:a,fileId:t}}return e}function Fr(e){function*t(){k(e.additional_kwargs?.reasoning)&&Ie(e.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:e.additional_kwargs.reasoning.summary.reduce((r,s)=>k(s)&&S(s.text)?`${r}${s.text}`:r,"")});const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const a of n)if(C(a,"text")){const{text:r,annotations:s,...i}=a;Array.isArray(s)?yield{...i,type:"text",text:String(r),annotations:s.map(no)}:yield{...i,type:"text",text:String(r)}}for(const a of e.tool_calls??[])yield{type:"tool_call",id:a.id,name:a.name,args:a.args};if(k(e.additional_kwargs)&&Ie(e.additional_kwargs.tool_outputs))for(const a of e.additional_kwargs.tool_outputs){if(C(a,"web_search_call")){yield{id:a.id,type:"server_tool_call",name:"web_search",args:{query:a.query}};continue}else if(C(a,"file_search_call")){yield{id:a.id,type:"server_tool_call",name:"file_search",args:{query:a.query}};continue}else if(C(a,"computer_call")){yield{type:"non_standard",value:a};continue}else if(C(a,"code_interpreter_call")){if(S(a.code)&&(yield{id:a.id,type:"server_tool_call",name:"code_interpreter",args:{code:a.code}}),Ie(a.outputs)){const r=vt(()=>{if(a.status!=="in_progress"){if(a.status==="completed")return 0;if(a.status==="incomplete")return 127;if(a.status!=="interpreting"&&a.status==="failed")return 1}});for(const s of a.outputs)if(C(s,"logs")){yield{type:"server_tool_call_result",toolCallId:a.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:r??0,stderr:[0,void 0].includes(r)?void 0:String(s.logs),stdout:[0,void 0].includes(r)?String(s.logs):void 0}};continue}}continue}else if(C(a,"mcp_call")){yield{id:a.id,type:"server_tool_call",name:"mcp_call",args:a.input};continue}else if(C(a,"mcp_list_tools")){yield{id:a.id,type:"server_tool_call",name:"mcp_list_tools",args:a.input};continue}else if(C(a,"mcp_approval_request")){yield{type:"non_standard",value:a};continue}else if(C(a,"image_generation_call")){yield{type:"non_standard",value:a};continue}k(a)&&(yield{type:"non_standard",value:a})}}return Array.from(t())}function ao(e){function*t(){yield*Fr(e);for(const n of e.tool_call_chunks??[])yield{type:"tool_call_chunk",id:n.id,name:n.name,args:n.args}}return Array.from(t())}const ro={translateContent:e=>typeof e.content=="string"?eo(e):Fr(e),translateContentChunk:e=>typeof e.content=="string"?to(e):ao(e)};function so(e,t="pretty"){return t==="pretty"?io(e):JSON.stringify(e)}function io(e){const t=[],n=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,a=Math.floor((80-n.length)/2),r="=".repeat(a),s=n.length%2===0?r:`${r}=`;if(t.push(`${r}${n}${s}`),e.type==="ai"){const i=e;if(i.tool_calls&&i.tool_calls.length>0){t.push("Tool Calls:");for(const o of i.tool_calls){t.push(` ${o.name} (${o.id})`),t.push(` Call ID: ${o.id}`),t.push(" Args:");for(const[c,l]of Object.entries(o.args))t.push(` ${c}: ${l}`)}}}if(e.type==="tool"){const i=e;i.name&&t.push(`Name: ${i.name}`)}return typeof e.content=="string"&&e.content.trim()&&(t.length>1&&t.push(""),t.push(e.content)),t.join(`
2
2
  `)}const yn=Symbol.for("langchain.message");function Xe(e,t){return typeof e=="string"?e===""?t:typeof t=="string"?e+t:Array.isArray(t)&&t.some(n=>Ue(n))?[{type:"text",source_type:"text",text:e},...t]:[{type:"text",text:e},...t]:Array.isArray(t)?Ot(e,t)??[...e,...t]:t===""?e:Array.isArray(e)&&e.some(n=>Ue(n))?[...e,{type:"file",source_type:"text",text:t}]:[...e,{type:"text",text:t}]}function Ur(e,t){return e==="error"||t==="error"?"error":"success"}function oo(e,t){function n(a,r){if(typeof a!="object"||a===null||a===void 0)return a;if(r>=t)return Array.isArray(a)?"[Array]":"[Object]";if(Array.isArray(a))return a.map(i=>n(i,r+1));const s={};for(const i of Object.keys(a))s[i]=n(a[i],r+1);return s}return JSON.stringify(n(e,0),null,2)}var Le=class extends lt{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[yn]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(e){const t=typeof e=="string"||Array.isArray(e)?{content:e}:e;t.additional_kwargs||(t.additional_kwargs={}),t.response_metadata||(t.response_metadata={}),super(t),this.name=t.name,t.content===void 0&&t.contentBlocks!==void 0?(this.content=t.contentBlocks,this.response_metadata={output_version:"v1",...t.response_metadata}):t.content!==void 0?(this.content=t.content??[],this.response_metadata=t.response_metadata):(this.content=[],this.response_metadata=t.response_metadata),this.additional_kwargs=t.additional_kwargs,this.id=t.id}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(""):""}get contentBlocks(){const e=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[Yi,ma,qi].reduce((a,r)=>r(a),e)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(e){return typeof e=="object"&&e!==null&&yn in e&&e[yn]===!0&&$r(e)}_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=oo(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}toFormattedString(e="pretty"){return so(this,e)}};function co(e){return Array.isArray(e)&&e.every(t=>typeof t.index=="number")}function ee(e={},t={}){const n={...e};for(const[a,r]of Object.entries(t))if(n[a]==null)n[a]=r;else{if(r==null)continue;if(typeof n[a]!=typeof r||Array.isArray(n[a])!==Array.isArray(r))throw new Error(`field[${a}] already exists in the message chunk, but with a different type.`);if(typeof n[a]=="string"){if(a==="type")continue;["id","name","output_version","model_provider"].includes(a)?n[a]=r:n[a]+=r}else if(typeof n[a]=="object"&&!Array.isArray(n[a]))n[a]=ee(n[a],r);else if(Array.isArray(n[a]))n[a]=Ot(n[a],r);else{if(n[a]===r)continue;console.warn(`field[${a}] already exists in this message chunk and value has unsupported type.`)}}return n}function Ot(e,t){if(!(e===void 0&&t===void 0)){if(e===void 0||t===void 0)return e||t;{const n=[...e];for(const a of t)if(typeof a=="object"&&a!==null&&"index"in a&&typeof a.index=="number"){const r=n.findIndex(s=>{const i=typeof s=="object",o="index"in s&&s.index===a.index,c="id"in s&&"id"in a&&s?.id===a?.id,l=!("id"in s)||!s?.id||!("id"in a)||!a?.id;return i&&o&&(c||l)});r!==-1&&typeof n[r]=="object"&&n[r]!==null?n[r]=ee(n[r],a):n.push(a)}else{if(typeof a=="object"&&a!==null&&"text"in a&&a.text==="")continue;n.push(a)}return n}}}function Br(e,t){if(!e&&!t)throw new Error("Cannot merge two undefined objects.");if(!e||!t)return e||t;if(typeof e!=typeof t)throw new Error(`Cannot merge objects of different types.
3
3
  Left ${typeof e}
4
4
  Right ${typeof t}`);if(typeof e=="string"&&typeof t=="string")return e+t;if(Array.isArray(e)&&Array.isArray(t))return Ot(e,t);if(typeof e=="object"&&typeof t=="object")return ee(e,t);if(e===t)return e;throw new Error(`Can not merge objects of different types.
@@ -1 +1 @@
1
- import{m as B}from"./langfuse-C4HKZ3NL-1laIPiUg.js";import"./index-CKNaXAjV.js";import"./chunk-VL2OQCWN-BFKzE0YG.js";import"./index-DRz5BQNA.js";import"./__vite-browser-external-DFygW7-s.js";import"./path-C9FudP8b.js";var J={};class ge{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(s=>s!==t)}}emit(e,t){for(const s of this.events[e]||[])s(t);for(const s of this.events["*"]||[])s(e,t)}}const ye=60;class be{constructor(e,t){this.value=e,this._expiry=Date.now()+t*1e3}get isExpired(){return Date.now()>this._expiry}}class _e{constructor(){this._cache=new Map,this._defaultTtlSeconds=ye,this._refreshingKeys=new Map}getIncludingExpired(e){return this._cache.get(e)??null}set(e,t,s){const n=s??this._defaultTtlSeconds;this._cache.set(e,new be(t,n))}addRefreshingPromise(e,t){this._refreshingKeys.set(e,t),t.then(()=>{this._refreshingKeys.delete(e)}).catch(()=>{this._refreshingKeys.delete(e)})}isRefreshing(e){return this._refreshingKeys.has(e)}invalidate(e){console.log("invalidating",e,this._cache.keys());for(const t of this._cache.keys())t.startsWith(e)&&this._cache.delete(t)}}var I;(function(r){r.Props="props",r.Queue="queue",r.OptedOut="opted_out"})(I||(I={}));var b;(function(r){r.ChatMessage="chatmessage",r.Placeholder="placeholder"})(b||(b={}));B.escape=function(r){return r};class ee{constructor(e,t=!1,s){this.name=e.name,this.version=e.version,this.config=e.config,this.labels=e.labels,this.tags=e.tags,this.isFallback=t,this.type=s,this.commitMessage=e.commitMessage}_transformToLangchainVariables(e){return this.escapeJsonForLangchain(e).replace(/\{\{(\w+)\}\}/g,"{$1}")}escapeJsonForLangchain(e){const t=[],s=[];let n=0;const o=e.length;for(;n<o;){const a=e[n];if(a==="{"){if(n+1<o&&e[n+1]==="{"){t.push("{{"),n+=2;continue}let c=n+1;for(;c<o&&/\s/.test(e[c]);)c++;const i=c<o&&(e[c]==="'"||e[c]==='"');t.push(i?"{{":"{"),s.push(i),n+=1;continue}if(a==="}"){if(n+1<o&&e[n+1]==="}"){t.push("}}"),n+=2;continue}const c=s.pop()??!1;t.push(c?"}}":"}"),n+=1;continue}t.push(a),n+=1}return t.join("")}}class k extends ee{constructor(e,t=!1){super(e,t,"text"),this.promptResponse=e,this.prompt=e.prompt}compile(e,t){return B.render(this.promptResponse.prompt,e??{})}getLangchainPrompt(e){return this._transformToLangchainVariables(this.prompt)}toJSON(){return JSON.stringify({name:this.name,prompt:this.prompt,version:this.version,isFallback:this.isFallback,tags:this.tags,labels:this.labels,type:this.type,config:this.config})}}class O extends ee{constructor(e,t=!1){const s=O.normalizePrompt(e.prompt),n={...e,prompt:s};super(n,t,"chat"),this.promptResponse=n,this.prompt=s}static normalizePrompt(e){return e.map(t=>"type"in t?t:{type:b.ChatMessage,...t})}compile(e,t){const s=[],n=t??{};for(const o of this.prompt)if("type"in o&&o.type===b.Placeholder){const a=n[o.name];Array.isArray(a)&&a.length>0&&a.every(c=>typeof c=="object"&&"role"in c&&"content"in c)?s.push(...a):Array.isArray(a)&&a.length===0||(a!==void 0?s.push(JSON.stringify(a)):s.push(o))}else"role"in o&&"content"in o&&o.type===b.ChatMessage&&s.push({role:o.role,content:o.content});return s.map(o=>typeof o=="object"&&o!==null&&"role"in o&&"content"in o?{...o,content:B.render(o.content,e??{})}:o)}getLangchainPrompt(e){const t=[],s=e?.placeholders??{};for(const n of this.prompt)if("type"in n&&n.type===b.Placeholder){const o=s[n.name];Array.isArray(o)&&o.length>0&&o.every(a=>typeof a=="object"&&"role"in a&&"content"in a)?t.push(...o.map(a=>({role:a.role,content:this._transformToLangchainVariables(a.content)}))):Array.isArray(o)&&o.length===0||(o!==void 0?t.push(JSON.stringify(o)):t.push({variableName:n.name,optional:!1}))}else"role"in n&&"content"in n&&n.type===b.ChatMessage&&t.push({role:n.role,content:this._transformToLangchainVariables(n.content)});return t}toJSON(){return JSON.stringify({name:this.name,prompt:this.promptResponse.prompt.map(e=>{if("type"in e&&e.type===b.ChatMessage){const{type:t,...s}=e;return s}return e}),version:this.version,isFallback:this.isFallback,tags:this.tags,labels:this.labels,type:this.type,config:this.config})}}function Ee(r,e){if(!r)throw new Error(e)}function te(r){return r?.replace(/\/+$/,"")}async function F(r,e={},t){const{retryCount:s=3,retryDelay:n=5e3,retryCheck:o=()=>!0}=e;let a=null;for(let c=0;c<s+1;c++){c>0&&(await new Promise(i=>setTimeout(i,n)),t(`Retrying ${c+1} of ${s+1}`));try{return await r()}catch(i){if(a=i,!o(i))throw i;t(`Retriable error: ${JSON.stringify(i)}`)}}throw a}function w(r){let e=new Date().getTime(),t=r&&r.performance&&r.performance.now&&r.performance.now()*1e3||0;return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(s){let n=Math.random()*16;return e>0?(n=(e+n)%16|0,e=Math.floor(e/16)):(n=(t+n)%16|0,t=Math.floor(t/16)),(s==="x"?n:n&3|8).toString(16)})}function we(){return new Date().getTime()}function se(){return new Date().toISOString()}function re(r,e){const t=setTimeout(r,e);return t?.unref&&t?.unref(),t}function g(r){if(typeof process<"u"&&J[r])return J[r];if(typeof globalThis<"u")return globalThis[r]}function Se(r,e=!0){const{publicKey:t,secretKey:s,...n}=r??{},o=t??g("LANGFUSE_PUBLIC_KEY"),a=e?s??g("LANGFUSE_SECRET_KEY"):void 0,c=n.baseUrl??g("LANGFUSE_BASEURL"),i={...n,baseUrl:c};return{publicKey:o,...e?{secretKey:a}:void 0,...i}}const C=r=>{const e=new URLSearchParams;return Object.entries(r??{}).forEach(([t,s])=>{s!=null&&(s instanceof Date?e.append(t,s.toISOString()):e.append(t,s.toString()))}),e.toString()};var ne=Object.freeze({__proto__:null,assert:Ee,configLangfuseSDK:Se,currentISOTime:se,currentTimestamp:we,encodeQueryParams:C,generateUUID:w,getEnv:g,removeTrailingSlash:te,retriable:F,safeSetTimeout:re});const ve=["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","TRIGGER_DEPLOYMENT_ID"];function Te(){for(const r of ve){const e=g(r);if(e)return e}}let P=null,$=null;const j=r=>import(r);typeof globalThis.Deno<"u"?Promise.all([j("node:fs"),j("node:crypto")]).then(([r,e])=>{P=r,$=e}).catch():typeof process<"u"&&process.versions?.node?Promise.all([j("fs"),j("crypto")]).then(([r,e])=>{P=r,$=e}).catch():typeof crypto<"u"&&($=crypto);class v{constructor(e){const{obj:t,base64DataUri:s,contentType:n,contentBytes:o,filePath:a}=e;if(this.obj=t,this._mediaId=void 0,s){const[c,i]=this.parseBase64DataUri(s);this._contentBytes=c,this._contentType=i,this._source="base64_data_uri"}else if(o&&n)this._contentBytes=o,this._contentType=n,this._source="bytes";else if(a&&n){if(!P)throw new Error("File system support is not available in this environment");if(!P.existsSync(a))throw new Error(`File at path ${a} does not exist`);this._contentBytes=this.readFile(a),this._contentType=this._contentBytes?n:void 0,this._source=this._contentBytes?"file":void 0}else console.error("base64DataUri, or contentBytes and contentType, or filePath must be provided to LangfuseMedia")}readFile(e){try{if(!P)throw new Error("File system support is not available in this environment");return P.readFileSync(e)}catch(t){console.error(`Error reading file at path ${e}`,t);return}}parseBase64DataUri(e){try{if(!e||typeof e!="string")throw new Error("Data URI is not a string");if(!e.startsWith("data:"))throw new Error("Data URI does not start with 'data:'");const[t,s]=e.slice(5).split(",",2);if(!t||!s)throw new Error("Invalid URI");const n=t.split(";");if(!n.includes("base64"))throw new Error("Data is not base64 encoded");const o=n[0];if(!o)throw new Error("Content type is empty");return[Buffer.from(s,"base64"),o]}catch(t){return console.error("Error parsing base64 data URI",t),[void 0,void 0]}}get contentLength(){return this._contentBytes?.length}get contentSha256Hash(){if(!this._contentBytes)return;if(!$){console.error("Crypto support is not available in this environment");return}return $.createHash("sha256").update(this._contentBytes).digest("base64")}toJSON(){return!this._contentType||!this._source||!this._mediaId?`<Upload handling failed for LangfuseMedia of type ${this._contentType}>`:`@@@langfuseMedia:type=${this._contentType}|id=${this._mediaId}|source=${this._source}@@@`}static parseReferenceString(e){const t="@@@langfuseMedia:";if(!e.startsWith(t))throw new Error("Reference string does not start with '@@@langfuseMedia:type='");if(!e.endsWith("@@@"))throw new Error("Reference string does not end with '@@@'");const o=e.slice(t.length,-3).split("|"),a={};for(const c of o){const[i,u]=c.split("=",2);a[i]=u}if(!("type"in a&&"id"in a&&"source"in a))throw new Error("Missing required fields in reference string");return{mediaId:a.id,source:a.source,contentType:a.type}}static async resolveMediaReferences(e){const{obj:t,langfuseClient:s,maxDepth:n=10}=e;async function o(a,c){if(c>n)return a;if(typeof a=="string"){const i=/@@@langfuseMedia:.+?@@@/g,u=a.match(i);if(!u)return a;let h=a;const l=new Map;await Promise.all(u.map(async p=>{try{const m=v.parseReferenceString(p),y=await s.fetchMedia(m.mediaId),_=await s.fetch(y.url,{method:"GET",headers:{}});if(_.status!==200)throw new Error("Failed to fetch media content");const E=Buffer.from(await _.arrayBuffer()).toString("base64"),f=`data:${y.contentType};base64,${E}`;l.set(p,f)}catch(m){console.warn("Error fetching media content for reference string",p,m)}}));for(const[p,m]of l.entries())h=h.replaceAll(p,m);return h}return Array.isArray(a)?Promise.all(a.map(async i=>await o(i,c+1))):typeof a=="object"&&a!==null?Object.fromEntries(await Promise.all(Object.entries(a).map(async([i,u])=>[i,await o(u,c+1)]))):a}return o(t,0)}}function Ie(r,e){return e===void 0?!0:e===0?!1:e<0||e>1||isNaN(e)?(console.warn("Sample rate must be between 0 and 1. Ignoring setting."),!0):Pe(r)<e}function Pe(r){let e=0;const t=31;for(let s=0;s<r.length;s++)e=e*t+r.charCodeAt(s)>>>0;return e=(e>>>16^e)*73244475,e=(e>>>16^e)*73244475,e=e>>>16^e,Math.abs(e)/2147483647}const z=g("LANGFUSE_MAX_EVENT_SIZE_BYTES")?Number(g("LANGFUSE_MAX_EVENT_SIZE_BYTES")):1e6,Le=g("LANGFUSE_MAX_BATCH_SIZE_BYTES")?Number(g("LANGFUSE_MAX_BATCH_SIZE_BYTES")):25e5,H=/^(?!langfuse)[a-z0-9_-]+$/,Ae=["langfuse-prompt-experiment"];class U extends Error{constructor(e,t){super("HTTP error while fetching Langfuse: "+e.status+" and body: "+t),this.response=e,this.name="LangfuseFetchHttpError"}}class M extends Error{constructor(e){super("Network error while fetching Langfuse",e instanceof Error?{cause:e}:{}),this.error=e,this.name="LangfuseFetchNetworkError"}}function oe(r){return typeof r=="object"&&r.name==="LangfuseFetchHttpError"}function ae(r){return typeof r=="object"&&r.name==="LangfuseFetchNetworkError"}function Ce(r){return oe(r)||ae(r)}const D="https://langfuse.com/support",Oe="https://api.reference.langfuse.com",$e="https://langfuse.com/docs/rbac",Re="https://langfuse.com/docs/sdk/typescript/guide",je="https://langfuse.com/faq/all/api-limits",Ue="https://www.npmjs.com/package/langfuse",Q=`Make sure to keep your SDK updated, refer to ${Ue} for details.`,x=`This is an unusual occurrence and we are monitoring it closely. For help, please contact support: ${D}.`,V=`Unexpected error occurred. Please check your request and contact support: ${D}.`,xe=new Map([[500,`Internal server error occurred. For help, please contact support: ${D}`],[501,`Not implemented. Please check your request and contact support for help: ${D}.`],[502,`Bad gateway. ${x}`],[503,`Service unavailable. ${x}`],[504,`Gateway timeout. ${x}`],[404,`Internal error occurred. ${x}`],[400,`Bad request. Please check your request for any missing or incorrect parameters. Refer to our API docs: ${Oe} for details.`],[401,`Unauthorized. Please check your public/private host settings. Refer to our installation and setup guide: ${Re} for details on SDK configuration.`],[403,`Forbidden. Please check your access control settings. Refer to our RBAC docs: ${$e} for details.`],[429,`Rate limit exceeded. For more information on rate limits please see: ${je}`]]);function De(r){if(!r)return`${V} ${Q}`;const e=xe.get(r)||V;return`${r}: ${e} ${Q}`}function G(r){if(oe(r)){const e=r.response.status,t=De(e);console.error("[Langfuse SDK]",t,`Error details: ${r}`)}else ae(r)?console.error("[Langfuse SDK] Network error: ",r):console.error("[Langfuse SDK] Unknown error:",r)}class ie{constructor(e){this.additionalHeaders={},this.debugMode=!1,this.pendingEventProcessingPromises={},this.pendingIngestionPromises={},this.localEventExportMap=new Map,this._events=new ge;const{publicKey:t,secretKey:s,enabled:n,_projectId:o,_isLocalEventExportEnabled:a,...c}=e;if(this._events.on("error",i=>{console.error(`[Langfuse SDK] ${typeof i=="string"?i:JSON.stringify(i)}`)}),this.enabled=n!==!1,this.publicKey=t??"",this.secretKey=s,this.baseUrl=te(c?.baseUrl||"https://cloud.langfuse.com"),this.additionalHeaders=c?.additionalHeaders||{},this.flushAt=c?.flushAt?Math.max(c?.flushAt,1):15,this.flushInterval=c?.flushInterval??1e4,this.release=c?.release??g("LANGFUSE_RELEASE")??Te()??void 0,this.mask=c?.mask,this.sampleRate=c?.sampleRate??(g("LANGFUSE_SAMPLE_RATE")?Number(g("LANGFUSE_SAMPLE_RATE")):void 0),this.sampleRate&&this._events.emit("debug",`Langfuse trace sampling enabled with sampleRate ${this.sampleRate}.`),this.environment=c?.environment??g("LANGFUSE_TRACING_ENVIRONMENT"),this.environment&&!(H.test(this.environment)||Ae.includes(this.environment))&&!a&&this._events.emit("error",`Invalid tracing environment set: ${this.environment} . Environment must match regex ${H}. Events will be rejected by Langfuse server.`),this._retryOptions={retryCount:c?.fetchRetryCount??3,retryDelay:c?.fetchRetryDelay??3e3,retryCheck:Ce},this.requestTimeout=c?.requestTimeout??5e3,this.sdkIntegration=c?.sdkIntegration??"DEFAULT",this.isLocalEventExportEnabled=a??!1,this.isLocalEventExportEnabled&&!o){this._events.emit("error","Local event export is enabled, but no project ID was provided. Disabling local export."),this.isLocalEventExportEnabled=!1;return}else if(!this.isLocalEventExportEnabled&&o){this._events.emit("error","Local event export is disabled, but a project ID was provided. Disabling local export."),this.isLocalEventExportEnabled=!1;return}else this.projectId=o}getSdkIntegration(){return this.sdkIntegration}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}on(e,t){return this._events.on(e,t)}debug(e=!0){this.removeDebugCallback?.(),this.debugMode=e,e&&(this.removeDebugCallback=this.on("*",(t,s)=>{t!=="error"&&console.log("[Langfuse Debug]",t,JSON.stringify(s))}))}traceStateless(e){const{id:t,timestamp:s,release:n,...o}=e,a=t??w(),c=n??this.release,i={id:a,release:c,timestamp:s??new Date,environment:this.environment,...o};return this.enqueue("trace-create",i),a}eventStateless(e){const{id:t,startTime:s,...n}=e,o=t??w(),a={id:o,startTime:s??new Date,environment:this.environment,...n};return this.enqueue("event-create",a),o}spanStateless(e){const{id:t,startTime:s,...n}=e,o=t||w(),a={id:o,startTime:s??new Date,environment:this.environment,...n};return this.enqueue("span-create",a),o}generationStateless(e){const{id:t,startTime:s,prompt:n,...o}=e,a=n&&!n.isFallback?{promptName:n.name,promptVersion:n.version}:{},c=t||w(),i={id:c,startTime:s??new Date,environment:this.environment,...a,...o};return this.enqueue("generation-create",i),c}scoreStateless(e){const{id:t,...s}=e,n=t||w(),o={id:n,environment:this.environment,...s};return this.enqueue("score-create",o),n}updateSpanStateless(e){return this.enqueue("span-update",e),e.id}updateGenerationStateless(e){const{prompt:t,...s}=e,o={...t&&!t.isFallback?{promptName:t.name,promptVersion:t.version}:{},...s};return this.enqueue("generation-update",o),e.id}async _getDataset(e){const t=encodeURIComponent(e);return this.fetchAndLogErrors(`${this.baseUrl}/api/public/v2/datasets/${t}`,this._getFetchOptions({method:"GET"}))}async _getDatasetItems(e){const t=new URLSearchParams;return Object.entries(e??{}).forEach(([s,n])=>{n!=null&&t.append(s,n.toString())}),this.fetchAndLogErrors(`${this.baseUrl}/api/public/dataset-items?${t}`,this._getFetchOptions({method:"GET"}))}async _fetchMedia(e){return this.fetchAndLogErrors(`${this.baseUrl}/api/public/media/${e}`,this._getFetchOptions({method:"GET"}))}async fetchTraces(e){const{data:t,meta:s}=await this.fetchAndLogErrors(`${this.baseUrl}/api/public/traces?${C(e)}`,this._getFetchOptions({method:"GET"}));return{data:t,meta:s}}async fetchTrace(e){return{data:await this.fetchAndLogErrors(`${this.baseUrl}/api/public/traces/${e}`,this._getFetchOptions({method:"GET"}))}}async fetchObservations(e){const{data:t,meta:s}=await this.fetchAndLogErrors(`${this.baseUrl}/api/public/observations?${C(e)}`,this._getFetchOptions({method:"GET"}));return{data:t,meta:s}}async fetchObservation(e){return{data:await this.fetchAndLogErrors(`${this.baseUrl}/api/public/observations/${e}`,this._getFetchOptions({method:"GET"}))}}async fetchSessions(e){const{data:t,meta:s}=await this.fetchAndLogErrors(`${this.baseUrl}/api/public/sessions?${C(e)}`,this._getFetchOptions({method:"GET"}));return{data:t,meta:s}}async getDatasetRun(e){const t=encodeURIComponent(e.datasetName),s=encodeURIComponent(e.runName);return this.fetchAndLogErrors(`${this.baseUrl}/api/public/datasets/${t}/runs/${s}`,this._getFetchOptions({method:"GET"}))}async getDatasetRuns(e,t){return this.fetchAndLogErrors(`${this.baseUrl}/api/public/datasets/${encodeURIComponent(e)}/runs?${C(t)}`,this._getFetchOptions({method:"GET"}))}async createDatasetRunItem(e){return this.fetchAndLogErrors(`${this.baseUrl}/api/public/dataset-run-items`,this._getFetchOptions({method:"POST",body:JSON.stringify(e)}))}async createDataset(e){const t=typeof e=="string"?{name:e}:e;return this.fetchAndLogErrors(`${this.baseUrl}/api/public/datasets`,this._getFetchOptions({method:"POST",body:JSON.stringify(t)}))}async createDatasetItem(e){return this.fetchAndLogErrors(`${this.baseUrl}/api/public/dataset-items`,this._getFetchOptions({method:"POST",body:JSON.stringify(e)}))}async getDatasetItem(e){return this.fetchAndLogErrors(`${this.baseUrl}/api/public/dataset-items/${e}`,this._getFetchOptions({method:"GET"}))}_parsePayload(e){try{return JSON.parse(e)}catch{return e}}async createPromptStateless(e){return this.fetchAndLogErrors(`${this.baseUrl}/api/public/v2/prompts`,this._getFetchOptions({method:"POST",body:JSON.stringify(e)}))}async updatePromptStateless(e){return this.fetchAndLogErrors(`${this.baseUrl}/api/public/v2/prompts/${encodeURIComponent(e.name)}/versions/${encodeURIComponent(e.version)}`,this._getFetchOptions({method:"PATCH",body:JSON.stringify(e)}))}async getPromptStateless(e,t,s,n,o){const a=encodeURIComponent(e),c=new URLSearchParams;if(t&&s)throw new Error("Provide either version or label, not both.");t&&c.append("version",t.toString()),s&&c.append("label",s);const i=`${this.baseUrl}/api/public/v2/prompts/${a}${c.size?"?"+c:""}`,u=this._getBoundedMaxRetries({maxRetries:n,defaultMaxRetries:2,maxRetriesUpperBound:4}),h={...this._retryOptions,retryCount:u,retryDelay:500};return F(async()=>{const p=await this.fetch(i,this._getFetchOptions({method:"GET",fetchTimeout:o??this.requestTimeout})).catch(y=>{throw y.name==="AbortError"?new M("Fetch request timed out"):new M(y)});if(p.status>=500)throw new U(p,await p.text());const m=await p.json();return{fetchResult:p.status===200?"success":"failure",data:m}},h,p=>this._events.emit("retry",p+", "+i+", "+JSON.stringify(h)))}_getBoundedMaxRetries(e){const t=Math.max(e.defaultMaxRetries??2,0),s=Math.max(e.maxRetriesUpperBound??4,0);return e.maxRetries===void 0?t:Math.min(Math.max(e.maxRetries,0),s)}enqueue(e,t){if(!this.enabled)return;const s=this.parseTraceId(e,t);if(!s)this._events.emit("warning","Failed to parse traceID for sampling. Please open a Github issue in https://github.com/langfuse/langfuse/issues/new/choose");else if(!Ie(s,this.sampleRate)){this._events.emit("debug",`Event with trace ID ${s} is out of sample. Skipping.`);return}const n=this.processEnqueueEvent(e,t),o=w();this.pendingEventProcessingPromises[o]=n,n.catch(a=>{this._events.emit("error",a)}).finally(()=>{delete this.pendingEventProcessingPromises[o]})}async processEnqueueEvent(e,t){this.maskEventBodyInPlace(t),await this.processMediaInEvent(e,t);const s=this.truncateEventBody(t,z);try{JSON.stringify(s)}catch(o){this._events.emit("error",`Event Body for ${e} is not JSON-serializable: ${o}`);return}const n=this.getPersistedProperty(I.Queue)||[];n.push({id:w(),type:e,timestamp:se(),body:s,metadata:void 0}),this.setPersistedProperty(I.Queue,n),this._events.emit(e,s),n.length>=this.flushAt&&this.flush(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=re(()=>this.flush(),this.flushInterval))}maskEventBodyInPlace(e){if(!this.mask)return;const t=["input","output"];for(const s of t)if(s in e)try{e[s]=this.mask({data:e[s]})}catch(n){this._events.emit("error",`Error masking ${s}: ${n}`),e[s]="<fully masked due to failed mask function>"}}truncateEventBody(e,t){const s=this.getByteSize(e);if(s<=t)return e;this._events.emit("warning",`Event Body is too large (${s} bytes) and will be truncated`);const o=["input","output","metadata"].map(i=>({key:i,size:i in e?this.getByteSize(e[i]):0})).sort((i,u)=>u.size-i.size);let a={...e},c=s;for(const{key:i,size:u}of o)c>t&&Object.prototype.hasOwnProperty.call(a,i)&&(a={...a,[i]:"<truncated due to size exceeding limit>"},this._events.emit("warning",`Truncated ${i} due to total size exceeding limit`),c-=u);return a}getByteSize(e){const t=JSON.stringify(e);return typeof TextEncoder<"u"?new TextEncoder().encode(t).length:encodeURIComponent(t).replace(/%[A-F\d]{2}/g,"U").length}async processMediaInEvent(e,t){if(!t)return;const s=this.parseTraceId(e,t);if(!s){this._events.emit("warning","traceId is required for media upload");return}const n=(e.includes("generation")||e.includes("span"))&&t.id?t.id:void 0;await Promise.all(["input","output","metadata"].map(async o=>{t[o]&&(t[o]=await this.findAndProcessMedia({data:t[o],traceId:s,observationId:n,field:o}).catch(a=>{this._events.emit("error",`Error processing multimodal event: ${a}`)})??t[o])}))}parseTraceId(e,t){return"traceId"in t?t.traceId:e.includes("trace")?t.id:void 0}async findAndProcessMedia({data:e,traceId:t,observationId:s,field:n}){const o=new WeakMap,a=10,c=async(i,u)=>{if(typeof i=="string"&&i.startsWith("data:")){const h=new v({base64DataUri:i});return await this.processMediaItem({media:h,traceId:t,observationId:s,field:n}),h}if(typeof i!="object"||i===null||o.has(i)||u>a)return i;if(o.set(i,!0),i instanceof v||Object.prototype.toString.call(i)==="[object LangfuseMedia]")return await this.processMediaItem({media:i,traceId:t,observationId:s,field:n}),i;if(Array.isArray(i))return await Promise.all(i.map(h=>c(h,u+1)));if(typeof i=="object"&&i!==null){if("input_audio"in i&&typeof i.input_audio=="object"&&"data"in i.input_audio){const h=new v({base64DataUri:`data:audio/${i.input_audio.format||"wav"};base64,${i.input_audio.data}`});return await this.processMediaItem({media:h,traceId:t,observationId:s,field:n}),{...i,input_audio:{...i.input_audio,data:h}}}if("audio"in i&&typeof i.audio=="object"&&"data"in i.audio){const h=new v({base64DataUri:`data:audio/${i.audio.format||"wav"};base64,${i.audio.data}`});return await this.processMediaItem({media:h,traceId:t,observationId:s,field:n}),{...i,audio:{...i.audio,data:h}}}return Object.fromEntries(await Promise.all(Object.entries(i).map(async([h,l])=>[h,await c(l,u+1)])))}return i};return await c(e,1)}async processMediaItem({media:e,traceId:t,observationId:s,field:n}){try{if(!e.contentLength||!e._contentType||!e.contentSha256Hash||!e._contentBytes)return;const o={contentLength:e.contentLength,traceId:t,observationId:s,field:n,contentType:e._contentType,sha256Hash:e.contentSha256Hash},c=await(await this.fetch(`${this.baseUrl}/api/public/media`,this._getFetchOptions({method:"POST",body:JSON.stringify(o)}))).json(),{uploadUrl:i,mediaId:u}=c;if(e._mediaId=u,i){this._events.emit("debug",`Uploading media ${u}`);const h=Date.now(),l=await this.uploadMediaWithBackoff({uploadUrl:i,contentBytes:e._contentBytes,contentType:e._contentType,contentSha256Hash:e.contentSha256Hash,maxRetries:3,baseDelay:1e3});if(!l)throw Error("Media upload process failed");const p={uploadedAt:new Date().toISOString(),uploadHttpStatus:l.status,uploadHttpError:await l.text(),uploadTimeMs:Date.now()-h};await this.fetch(`${this.baseUrl}/api/public/media/${u}`,this._getFetchOptions({method:"PATCH",body:JSON.stringify(p)})),this._events.emit("debug",`Media upload status reported for ${u}`)}else this._events.emit("debug",`Media ${u} already uploaded`)}catch(o){this._events.emit("error",`Error processing media item: ${o}`)}}async uploadMediaWithBackoff(e){const{uploadUrl:t,contentType:s,contentSha256Hash:n,contentBytes:o,maxRetries:a,baseDelay:c}=e;for(let i=0;i<=a;i++)try{const u=await this.fetch(t,{method:"PUT",body:o,headers:{"Content-Type":s,"x-amz-checksum-sha256":n,"x-ms-blob-type":"BlockBlob"}});if(i<a&&u.status!==200&&u.status!==201)throw new Error(`Upload failed with status ${u.status}`);return u}catch(u){if(i===a)throw u;const h=c*Math.pow(2,i),l=Math.random()*1e3;await new Promise(p=>setTimeout(p,h+l))}}async flushAsync(){return await Promise.all(Object.values(this.pendingEventProcessingPromises)).catch(e=>{G(e)}),new Promise((e,t)=>{try{this.flush((s,n)=>{s?(G(s),e()):e(n)})}catch(s){console.error("[Langfuse SDK] Error while flushing Langfuse",s)}})}flush(e){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=null);const t=this.getPersistedProperty(I.Queue)||[];if(!t.length)return e?.();const s=t.splice(0,this.flushAt),{processedItems:n,remainingItems:o}=this.processQueueItems(s,z,Le);this.setPersistedProperty(I.Queue,[...o,...t]);const a=w(),c=p=>{p&&this._events.emit("warning",p),e?.(p,s),this._events.emit("flush",s)};if(this.isLocalEventExportEnabled&&this.projectId){this.localEventExportMap.has(this.projectId)?this.localEventExportMap.get(this.projectId)?.push(...s):this.localEventExportMap.set(this.projectId,[...s]),c();return}const i=JSON.stringify({batch:n,metadata:{batch_size:n.length,sdk_integration:this.sdkIntegration,sdk_version:this.getLibraryVersion(),sdk_variant:this.getLibraryId(),public_key:this.publicKey,sdk_name:"langfuse-js"}}),u=`${this.baseUrl}/api/public/ingestion`,h=this._getFetchOptions({method:"POST",body:i}),l=this.fetchWithRetry(u,h).then(()=>c()).catch(p=>{c(p)});this.pendingIngestionPromises[a]=l,l.finally(()=>{delete this.pendingIngestionPromises[a]})}processQueueItems(e,t,s){let n=0;const o=[],a=[];for(let c=0;c<e.length;c++)try{const i=new Blob([JSON.stringify(e[c])]).size;if(i>t){console.warn(`Item exceeds size limit (size: ${i}), dropping item.`);continue}if(n+i>=s){console.debug(`hit batch size limit (size: ${n+i})`),a.push(...e.slice(c)),console.log(`Remaining items: ${a.length}`),console.log(`processes items: ${o.length}`);break}n+=i,o.push(e[c])}catch(i){this._events.emit("error",i),a.push(...e.slice(c));break}return{processedItems:o,remainingItems:a}}_getFetchOptions(e){return{method:e.method,headers:{"Content-Type":"application/json","X-Langfuse-Sdk-Name":"langfuse-js","X-Langfuse-Sdk-Version":this.getLibraryVersion(),"X-Langfuse-Sdk-Variant":this.getLibraryId(),"X-Langfuse-Sdk-Integration":this.sdkIntegration,"X-Langfuse-Public-Key":this.publicKey,...this.additionalHeaders,...this.constructAuthorizationHeader(this.publicKey,this.secretKey)},body:e.body,...e.fetchTimeout!==void 0?{signal:AbortSignal.timeout(e.fetchTimeout)}:{}}}constructAuthorizationHeader(e,t){return t===void 0?{Authorization:"Bearer "+e}:{Authorization:"Basic "+(typeof btoa=="function"?btoa(e+":"+t):Buffer.from(e+":"+t).toString("base64"))}}async fetchWithRetry(e,t,s){return AbortSignal.timeout??=function(o){const a=new AbortController;return setTimeout(()=>a.abort(),o),a.signal},await F(async()=>{let n=null;try{n=await this.fetch(e,{signal:AbortSignal.timeout(this.requestTimeout),...t})}catch(a){throw new M(a)}if(n.status<200||n.status>=400){const a=await n.json();throw new U(n,JSON.stringify(a))}const o=await n.json();if(n.status===207&&o.errors.length>0)throw new U(n,JSON.stringify(o.errors));return n},{...this._retryOptions,...s},n=>this._events.emit("retry",n+", "+e+", "+JSON.stringify(t)))}async fetchAndLogErrors(e,t){const s=await this.fetch(e,t),n=s.status===429?await s.text():await s.json();return(s.status<200||s.status>=400)&&G(new U(s,JSON.stringify(n))),n}async shutdownAsync(){clearTimeout(this._flushTimer);try{await this.flushAsync(),await Promise.all(Object.values(this.pendingIngestionPromises).map(e=>e.catch(()=>{}))),await this.flushAsync()}catch(e){console.error("[Langfuse SDK] Error while shutting down Langfuse",e)}}async _exportLocalEvents(e){if(this.isLocalEventExportEnabled){clearTimeout(this._flushTimer),await this.flushAsync();const t=this.localEventExportMap.get(e)??[];return this.localEventExportMap.delete(e),t}else return this._events.emit("error","Local event exports are disabled, but _exportLocalEvents() was called."),[]}shutdown(){console.warn("shutdown() is deprecated. It does not wait for all events to be processed. Please use shutdownAsync() instead."),this.shutdownAsync()}async awaitAllQueuedAndPendingRequests(){clearTimeout(this._flushTimer),await this.flushAsync(),await Promise.all(Object.values(this.pendingIngestionPromises))}}class qe extends ie{constructor(e){const{flushAt:t,flushInterval:s,publicKey:n,enabled:o,...a}=e;let c=o!==!1;c&&!n&&(c=!1,console.warn("Langfuse public key not passed to constructor and not set as 'LANGFUSE_PUBLIC_KEY' environment variable. No observability data will be sent to Langfuse.")),super({...a,publicKey:n,flushAt:t??1,flushInterval:s??0,enabled:c})}async score(e){return this.scoreStateless(e),await this.awaitAllQueuedAndPendingRequests(),this}}class ke extends ie{constructor(e){const{publicKey:t,secretKey:s,enabled:n,_isLocalEventExportEnabled:o}=e;let a=n!==!1;o?a=!0:s?t||(a=!1,n!==!1&&console.warn("Langfuse public key was not passed to constructor or not set as 'LANGFUSE_PUBLIC_KEY' environment variable. No observability data will be sent to Langfuse.")):(a=!1,n!==!1&&console.warn("Langfuse secret key was not passed to constructor or not set as 'LANGFUSE_SECRET_KEY' environment variable. No observability data will be sent to Langfuse.")),super({...e,enabled:a}),this._promptCache=new _e}trace(e){const t=this.traceStateless(e??{}),s=new Me(this,t);if(g("DEFER")&&e)try{const n=g("__deferRuntime");n&&n.langfuseTraces([{id:t,name:e.name||"",url:s.getTraceUrl()}])}catch{}return s}span(e){const t=e.traceId||this.traceStateless({name:e.name}),s=this.spanStateless({...e,traceId:t});return new Ge(this,s,t)}generation(e){const t=e.traceId||this.traceStateless({name:e.name}),s=this.generationStateless({...e,traceId:t});return new Ne(this,s,t)}event(e){const t=e.traceId||this.traceStateless({name:e.name}),s=this.eventStateless({...e,traceId:t});return new Fe(this,s,t)}score(e){return this.scoreStateless(e),this}async getDataset(e,t){const s=await this._getDataset(e),n=[];let o=1;for(;;){const c=await this._getDatasetItems({datasetName:e,limit:t?.fetchItemsPageSize??50,page:o});if(n.push(...c.data),c.meta.totalPages<=o)break;o++}return{...s,description:s.description??void 0,metadata:s.metadata??void 0,items:n.map(c=>({...c,link:async(i,u,h)=>(await this.awaitAllQueuedAndPendingRequests(),await this.createDatasetRunItem({runName:u,datasetItemId:c.id,observationId:i.observationId,traceId:i.traceId,runDescription:h?.description,metadata:h?.metadata}))}))}}async createPrompt(e){const t=e.labels??[],s=e.type==="chat"?await this.createPromptStateless({...e,prompt:e.prompt.map(n=>"type"in n&&n.type===b.Placeholder?{type:b.Placeholder,name:n.name}:{type:b.ChatMessage,...n}),labels:e.isActive?[...new Set([...t,"production"])]:t}):await this.createPromptStateless({...e,type:e.type??"text",labels:e.isActive?[...new Set([...t,"production"])]:t});return s.type==="chat"?new O(s):new k(s)}async updatePrompt(e){const t=await this.updatePromptStateless(e);return this._promptCache.invalidate(e.name),t}async getPrompt(e,t,s){const n=this._getPromptCacheKey({name:e,version:t,label:s?.label}),o=this._promptCache.getIncludingExpired(n);if(!o||s?.cacheTtlSeconds===0)try{return await this._fetchPromptAndUpdateCache({name:e,version:t,label:s?.label,cacheTtlSeconds:s?.cacheTtlSeconds,maxRetries:s?.maxRetries,fetchTimeout:s?.fetchTimeoutMs})}catch(a){if(s?.fallback){const c={name:e,version:t??0,labels:s.label?[s.label]:[],cacheTtlSeconds:s?.cacheTtlSeconds,config:{},tags:[]};return s.type==="chat"?new O({...c,type:"chat",prompt:s.fallback.map(i=>({type:b.ChatMessage,...i}))},!0):new k({...c,type:"text",prompt:s.fallback},!0)}throw a}if(o.isExpired){if(!this._promptCache.isRefreshing(n)){const a=this._fetchPromptAndUpdateCache({name:e,version:t,label:s?.label,cacheTtlSeconds:s?.cacheTtlSeconds,maxRetries:s?.maxRetries,fetchTimeout:s?.fetchTimeoutMs}).catch(()=>{console.warn(`Failed to refresh prompt cache '${n}', stale cache will be used until next refresh succeeds.`)});this._promptCache.addRefreshingPromise(n,a)}return o.value}return o.value}_getPromptCacheKey(e){const{name:t,version:s,label:n}=e,o=[t];return s!==void 0?o.push("version:"+s.toString()):n!==void 0?o.push("label:"+n):o.push("label:production"),o.join("-")}async _fetchPromptAndUpdateCache(e){const t=this._getPromptCacheKey(e);try{const{name:s,version:n,cacheTtlSeconds:o,label:a,maxRetries:c,fetchTimeout:i}=e,{data:u,fetchResult:h}=await this.getPromptStateless(s,n,a,c,i);if(h==="failure")throw Error(u.message??"Internal error while fetching prompt");let l;return u.type==="chat"?l=new O(u):l=new k(u),this._promptCache.set(t,l,o),l}catch(s){throw console.error(`[Langfuse SDK] Error while fetching prompt '${t}':`,s),s}}async fetchMedia(e){return await this._fetchMedia(e)}async resolveMediaReferences(e){const{obj:t,...s}=e;return v.resolveMediaReferences({...s,langfuseClient:this,obj:t})}_updateSpan(e){return this.updateSpanStateless(e),this}_updateGeneration(e){return this.updateGenerationStateless(e),this}}class ce{constructor({client:e,id:t,traceId:s,observationId:n}){this.client=e,this.id=t,this.traceId=s,this.observationId=n}event(e){return this.client.event({...e,traceId:this.traceId,parentObservationId:this.observationId})}span(e){return this.client.span({...e,traceId:this.traceId,parentObservationId:this.observationId})}generation(e){return this.client.generation({...e,traceId:this.traceId,parentObservationId:this.observationId})}score(e){return this.client.score({...e,traceId:this.traceId,observationId:this.observationId}),this}getTraceUrl(){return`${this.client.baseUrl}/trace/${this.traceId}`}}class Me extends ce{constructor(e,t){super({client:e,id:t,traceId:t,observationId:null})}update(e){return this.client.trace({...e,id:this.id}),this}}class K extends ce{constructor(e,t,s){super({client:e,id:t,traceId:s,observationId:t})}}class Ge extends K{constructor(e,t,s){super(e,t,s)}update(e){return this.client._updateSpan({...e,id:this.id,traceId:this.traceId}),this}end(e){return this.client._updateSpan({...e,id:this.id,traceId:this.traceId,endTime:new Date}),this}}class Ne extends K{constructor(e,t,s){super(e,t,s)}update(e){return this.client._updateGeneration({...e,id:this.id,traceId:this.traceId}),this}end(e){return this.client._updateGeneration({...e,id:this.id,traceId:this.traceId,endTime:new Date}),this}}class Fe extends K{constructor(e,t,s){super(e,t,s)}}const ue={getItem(r){try{const e=r+"=",t=document.cookie.split(";");for(let s=0;s<t.length;s++){let n=t[s];for(;n.charAt(0)==" ";)n=n.substring(1,n.length);if(n.indexOf(e)===0)return decodeURIComponent(n.substring(e.length,n.length))}}catch{}return null},setItem(r,e){try{const o=r+"="+encodeURIComponent(e)+"; path=/";document.cookie=o}catch{return}},removeItem(r){try{ue.setItem(r,"")}catch{return}},clear(){document.cookie=""},getAllKeys(){const r=document.cookie.split(";"),e=[];for(let t=0;t<r.length;t++){let s=r[t];for(;s.charAt(0)==" ";)s=s.substring(1,s.length);e.push(s.split("=")[0])}return e}},W=r=>({getItem(e){return r.getItem(e)},setItem(e,t){r.setItem(e,t)},removeItem(e){r.removeItem(e)},clear(){r.clear()},getAllKeys(){const e=[];for(const t in localStorage)e.push(t);return e}}),X=(r,e="__mplssupport__")=>{if(!window)return!1;try{return r.setItem(e,"xyz"),r.getItem(e)!=="xyz"?!1:(r.removeItem(e),!0)}catch{return!1}};let N,L;const A=()=>{const r={};return{getItem(t){return r[t]},setItem(t,s){r[t]=s!==null?s:void 0},removeItem(t){delete r[t]},clear(){for(const t in r)delete r[t]},getAllKeys(){const t=[];for(const s in r)t.push(s);return t}}},q=(r,e)=>{if(typeof e!==void 0&&e){if(!localStorage){const t=W(e.localStorage);N=X(t)?t:void 0}if(!L){const t=W(e.sessionStorage);L=X(t)?t:void 0}}switch(r){case"cookie":return ue||N||L||A();case"localStorage":return N||L||A();case"sessionStorage":return L||A();case"memory":return A();default:return A()}};var d;(function(r){r.Json="application/json",r.FormData="multipart/form-data",r.UrlEncoded="application/x-www-form-urlencoded",r.Text="text/plain"})(d||(d={}));class Be{constructor(e={}){this.baseUrl="",this.securityData=null,this.abortControllers=new Map,this.customFetch=(...t)=>fetch(...t),this.baseApiParams={credentials:"same-origin",headers:{},redirect:"follow",referrerPolicy:"no-referrer"},this.setSecurityData=t=>{this.securityData=t},this.contentFormatters={[d.Json]:t=>t!==null&&(typeof t=="object"||typeof t=="string")?JSON.stringify(t):t,[d.Text]:t=>t!==null&&typeof t!="string"?JSON.stringify(t):t,[d.FormData]:t=>Object.keys(t||{}).reduce((s,n)=>{const o=t[n];return s.append(n,o instanceof Blob?o:typeof o=="object"&&o!==null?JSON.stringify(o):`${o}`),s},new FormData),[d.UrlEncoded]:t=>this.toQueryString(t)},this.createAbortSignal=t=>{if(this.abortControllers.has(t)){const n=this.abortControllers.get(t);return n?n.signal:void 0}const s=new AbortController;return this.abortControllers.set(t,s),s.signal},this.abortRequest=t=>{const s=this.abortControllers.get(t);s&&(s.abort(),this.abortControllers.delete(t))},this.request=async({body:t,secure:s,path:n,type:o,query:a,format:c,baseUrl:i,cancelToken:u,...h})=>{const l=(typeof s=="boolean"?s:this.baseApiParams.secure)&&this.securityWorker&&await this.securityWorker(this.securityData)||{},p=this.mergeRequestParams(h,l),m=a&&this.toQueryString(a),y=this.contentFormatters[o||d.Json],_=c||p.format;return this.customFetch(`${i||this.baseUrl||""}${n}${m?`?${m}`:""}`,{...p,headers:{...p.headers||{},...o&&o!==d.FormData?{"Content-Type":o}:{}},signal:(u?this.createAbortSignal(u):p.signal)||null,body:typeof t>"u"||t===null?null:y(t)}).then(async E=>{const f=E.clone();f.data=null,f.error=null;const R=_?await E[_]().then(T=>(f.ok?f.data=T:f.error=T,f)).catch(T=>(f.error=T,f)):f;if(u&&this.abortControllers.delete(u),!E.ok)throw R;return R.data})},Object.assign(this,e)}encodeQueryParam(e,t){return`${encodeURIComponent(e)}=${encodeURIComponent(typeof t=="number"?t:`${t}`)}`}addQueryParam(e,t){return this.encodeQueryParam(t,e[t])}addArrayQueryParam(e,t){return e[t].map(n=>this.encodeQueryParam(t,n)).join("&")}toQueryString(e){const t=e||{};return Object.keys(t).filter(n=>typeof t[n]<"u").map(n=>Array.isArray(t[n])?this.addArrayQueryParam(t,n):this.addQueryParam(t,n)).join("&")}addQueryParams(e){const t=this.toQueryString(e);return t?`?${t}`:""}mergeRequestParams(e,t){return{...this.baseApiParams,...e,...t||{},headers:{...this.baseApiParams.headers||{},...e.headers||{},...t&&t.headers||{}}}}}class Ke extends Be{constructor(){super(...arguments),this.api={annotationQueuesCreateQueueItem:(e,t,s={})=>this.request({path:`/api/public/annotation-queues/${e}/items`,method:"POST",body:t,secure:!0,type:d.Json,format:"json",...s}),annotationQueuesDeleteQueueItem:(e,t,s={})=>this.request({path:`/api/public/annotation-queues/${e}/items/${t}`,method:"DELETE",secure:!0,format:"json",...s}),annotationQueuesGetQueue:(e,t={})=>this.request({path:`/api/public/annotation-queues/${e}`,method:"GET",secure:!0,format:"json",...t}),annotationQueuesGetQueueItem:(e,t,s={})=>this.request({path:`/api/public/annotation-queues/${e}/items/${t}`,method:"GET",secure:!0,format:"json",...s}),annotationQueuesListQueueItems:({queueId:e,...t},s={})=>this.request({path:`/api/public/annotation-queues/${e}/items`,method:"GET",query:t,secure:!0,format:"json",...s}),annotationQueuesListQueues:(e,t={})=>this.request({path:"/api/public/annotation-queues",method:"GET",query:e,secure:!0,format:"json",...t}),annotationQueuesUpdateQueueItem:(e,t,s,n={})=>this.request({path:`/api/public/annotation-queues/${e}/items/${t}`,method:"PATCH",body:s,secure:!0,type:d.Json,format:"json",...n}),commentsCreate:(e,t={})=>this.request({path:"/api/public/comments",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),commentsGet:(e,t={})=>this.request({path:"/api/public/comments",method:"GET",query:e,secure:!0,format:"json",...t}),commentsGetById:(e,t={})=>this.request({path:`/api/public/comments/${e}`,method:"GET",secure:!0,format:"json",...t}),datasetItemsCreate:(e,t={})=>this.request({path:"/api/public/dataset-items",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),datasetItemsDelete:(e,t={})=>this.request({path:`/api/public/dataset-items/${e}`,method:"DELETE",secure:!0,format:"json",...t}),datasetItemsGet:(e,t={})=>this.request({path:`/api/public/dataset-items/${e}`,method:"GET",secure:!0,format:"json",...t}),datasetItemsList:(e,t={})=>this.request({path:"/api/public/dataset-items",method:"GET",query:e,secure:!0,format:"json",...t}),datasetRunItemsCreate:(e,t={})=>this.request({path:"/api/public/dataset-run-items",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),datasetRunItemsList:(e,t={})=>this.request({path:"/api/public/dataset-run-items",method:"GET",query:e,secure:!0,...t}),datasetsCreate:(e,t={})=>this.request({path:"/api/public/v2/datasets",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),datasetsDeleteRun:(e,t,s={})=>this.request({path:`/api/public/datasets/${e}/runs/${t}`,method:"DELETE",secure:!0,format:"json",...s}),datasetsGet:(e,t={})=>this.request({path:`/api/public/v2/datasets/${e}`,method:"GET",secure:!0,format:"json",...t}),datasetsGetRun:(e,t,s={})=>this.request({path:`/api/public/datasets/${e}/runs/${t}`,method:"GET",secure:!0,format:"json",...s}),datasetsGetRuns:({datasetName:e,...t},s={})=>this.request({path:`/api/public/datasets/${e}/runs`,method:"GET",query:t,secure:!0,format:"json",...s}),datasetsList:(e,t={})=>this.request({path:"/api/public/v2/datasets",method:"GET",query:e,secure:!0,format:"json",...t}),healthHealth:(e={})=>this.request({path:"/api/public/health",method:"GET",format:"json",...e}),ingestionBatch:(e,t={})=>this.request({path:"/api/public/ingestion",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),mediaGet:(e,t={})=>this.request({path:`/api/public/media/${e}`,method:"GET",secure:!0,format:"json",...t}),mediaGetUploadUrl:(e,t={})=>this.request({path:"/api/public/media",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),mediaPatch:(e,t,s={})=>this.request({path:`/api/public/media/${e}`,method:"PATCH",body:t,secure:!0,type:d.Json,...s}),metricsMetrics:(e,t={})=>this.request({path:"/api/public/metrics",method:"GET",query:e,secure:!0,format:"json",...t}),modelsCreate:(e,t={})=>this.request({path:"/api/public/models",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),modelsDelete:(e,t={})=>this.request({path:`/api/public/models/${e}`,method:"DELETE",secure:!0,...t}),modelsGet:(e,t={})=>this.request({path:`/api/public/models/${e}`,method:"GET",secure:!0,format:"json",...t}),modelsList:(e,t={})=>this.request({path:"/api/public/models",method:"GET",query:e,secure:!0,format:"json",...t}),observationsGet:(e,t={})=>this.request({path:`/api/public/observations/${e}`,method:"GET",secure:!0,format:"json",...t}),observationsGetMany:(e,t={})=>this.request({path:"/api/public/observations",method:"GET",query:e,secure:!0,format:"json",...t}),organizationsGetOrganizationMemberships:(e={})=>this.request({path:"/api/public/organizations/memberships",method:"GET",secure:!0,format:"json",...e}),organizationsGetOrganizationProjects:(e={})=>this.request({path:"/api/public/organizations/projects",method:"GET",secure:!0,format:"json",...e}),organizationsGetProjectMemberships:(e,t={})=>this.request({path:`/api/public/projects/${e}/memberships`,method:"GET",secure:!0,format:"json",...t}),organizationsUpdateOrganizationMembership:(e,t={})=>this.request({path:"/api/public/organizations/memberships",method:"PUT",body:e,secure:!0,type:d.Json,format:"json",...t}),organizationsUpdateProjectMembership:(e,t,s={})=>this.request({path:`/api/public/projects/${e}/memberships`,method:"PUT",body:t,secure:!0,type:d.Json,format:"json",...s}),projectsCreate:(e,t={})=>this.request({path:"/api/public/projects",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),projectsCreateApiKey:(e,t,s={})=>this.request({path:`/api/public/projects/${e}/apiKeys`,method:"POST",body:t,secure:!0,type:d.Json,format:"json",...s}),projectsDelete:(e,t={})=>this.request({path:`/api/public/projects/${e}`,method:"DELETE",secure:!0,format:"json",...t}),projectsDeleteApiKey:(e,t,s={})=>this.request({path:`/api/public/projects/${e}/apiKeys/${t}`,method:"DELETE",secure:!0,format:"json",...s}),projectsGet:(e={})=>this.request({path:"/api/public/projects",method:"GET",secure:!0,format:"json",...e}),projectsGetApiKeys:(e,t={})=>this.request({path:`/api/public/projects/${e}/apiKeys`,method:"GET",secure:!0,format:"json",...t}),projectsUpdate:(e,t,s={})=>this.request({path:`/api/public/projects/${e}`,method:"PUT",body:t,secure:!0,type:d.Json,format:"json",...s}),promptsCreate:(e,t={})=>this.request({path:"/api/public/v2/prompts",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),promptsGet:({promptName:e,...t},s={})=>this.request({path:`/api/public/v2/prompts/${e}`,method:"GET",query:t,secure:!0,format:"json",...s}),promptsList:(e,t={})=>this.request({path:"/api/public/v2/prompts",method:"GET",query:e,secure:!0,format:"json",...t}),promptVersionUpdate:(e,t,s,n={})=>this.request({path:`/api/public/v2/prompts/${e}/versions/${t}`,method:"PATCH",body:s,secure:!0,type:d.Json,format:"json",...n}),scimCreateUser:(e,t={})=>this.request({path:"/api/public/scim/Users",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),scimDeleteUser:(e,t={})=>this.request({path:`/api/public/scim/Users/${e}`,method:"DELETE",secure:!0,format:"json",...t}),scimGetResourceTypes:(e={})=>this.request({path:"/api/public/scim/ResourceTypes",method:"GET",secure:!0,format:"json",...e}),scimGetSchemas:(e={})=>this.request({path:"/api/public/scim/Schemas",method:"GET",secure:!0,format:"json",...e}),scimGetServiceProviderConfig:(e={})=>this.request({path:"/api/public/scim/ServiceProviderConfig",method:"GET",secure:!0,format:"json",...e}),scimGetUser:(e,t={})=>this.request({path:`/api/public/scim/Users/${e}`,method:"GET",secure:!0,format:"json",...t}),scimListUsers:(e,t={})=>this.request({path:"/api/public/scim/Users",method:"GET",query:e,secure:!0,format:"json",...t}),scoreConfigsCreate:(e,t={})=>this.request({path:"/api/public/score-configs",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),scoreConfigsGet:(e,t={})=>this.request({path:"/api/public/score-configs",method:"GET",query:e,secure:!0,format:"json",...t}),scoreConfigsGetById:(e,t={})=>this.request({path:`/api/public/score-configs/${e}`,method:"GET",secure:!0,format:"json",...t}),scoreCreate:(e,t={})=>this.request({path:"/api/public/scores",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),scoreDelete:(e,t={})=>this.request({path:`/api/public/scores/${e}`,method:"DELETE",secure:!0,...t}),scoreV2Get:(e,t={})=>this.request({path:"/api/public/v2/scores",method:"GET",query:e,secure:!0,format:"json",...t}),scoreV2GetById:(e,t={})=>this.request({path:`/api/public/v2/scores/${e}`,method:"GET",secure:!0,format:"json",...t}),sessionsGet:(e,t={})=>this.request({path:`/api/public/sessions/${e}`,method:"GET",secure:!0,format:"json",...t}),sessionsList:(e,t={})=>this.request({path:"/api/public/sessions",method:"GET",query:e,secure:!0,format:"json",...t}),traceDelete:(e,t={})=>this.request({path:`/api/public/traces/${e}`,method:"DELETE",secure:!0,format:"json",...t}),traceDeleteMultiple:(e,t={})=>this.request({path:"/api/public/traces",method:"DELETE",body:e,secure:!0,type:d.Json,format:"json",...t}),traceGet:(e,t={})=>this.request({path:`/api/public/traces/${e}`,method:"GET",secure:!0,format:"json",...t}),traceList:(e,t={})=>this.request({path:"/api/public/traces",method:"GET",query:e,secure:!0,format:"json",...t})}}}var le="3.38.6";class Je extends ke{constructor(e){const t=ne.configLangfuseSDK(e);super(t),typeof window<"u"&&!("Deno"in window)?(this._storageKey=e?.persistence_name?`lf_${e.persistence_name}`:`lf_${t.publicKey}_langfuse`,this._storage=q(e?.persistence||"localStorage",window)):(this._storageKey=`lf_${t.publicKey}_langfuse`,this._storage=q("memory",void 0)),this.api=new Ke({baseUrl:this.baseUrl,baseApiParams:{headers:{"X-Langfuse-Sdk-Name":"langfuse-js","X-Langfuse-Sdk-Version":this.getLibraryVersion(),"X-Langfuse-Sdk-Variant":this.getLibraryId(),"X-Langfuse-Sdk-Integration":this.sdkIntegration,"X-Langfuse-Public-Key":this.publicKey,...this.additionalHeaders,...this.constructAuthorizationHeader(this.publicKey,this.secretKey)}}}).api}getPersistedProperty(e){return this._storageCache||(this._storageCache=JSON.parse(this._storage.getItem(this._storageKey)||"{}")||{}),this._storageCache[e]}setPersistedProperty(e,t){this._storageCache||(this._storageCache=JSON.parse(this._storage.getItem(this._storageKey)||"{}")||{}),t===null?delete this._storageCache[e]:this._storageCache[e]=t,this._storage.setItem(this._storageKey,JSON.stringify(this._storageCache))}fetch(e,t){return fetch(e,t)}getLibraryId(){return"langfuse"}getLibraryVersion(){return le}getCustomUserAgent(){}}class ot extends qe{constructor(e){const t=ne.configLangfuseSDK(e,!1);super(t),typeof window<"u"?(this._storageKey=e?.persistence_name?`lf_${e.persistence_name}`:`lf_${t.publicKey}_langfuse`,this._storage=q(e?.persistence||"localStorage",window)):(this._storageKey=`lf_${t.publicKey}_langfuse`,this._storage=q("memory",void 0))}getPersistedProperty(e){return this._storageCache||(this._storageCache=JSON.parse(this._storage.getItem(this._storageKey)||"{}")||{}),this._storageCache[e]}setPersistedProperty(e,t){this._storageCache||(this._storageCache=JSON.parse(this._storage.getItem(this._storageKey)||"{}")||{}),t===null?delete this._storageCache[e]:this._storageCache[e]=t,this._storage.setItem(this._storageKey,JSON.stringify(this._storageCache))}fetch(e,t){return fetch(e,t)}getLibraryId(){return"langfuse-frontend"}getLibraryVersion(){return le}getCustomUserAgent(){}}class S{static getInstance(e){return S.instance||(S.instance=new Je(e)),S.instance}}S.instance=null;const ze=r=>{let e={};e={frequency_penalty:r.frequency_penalty,logit_bias:r.logit_bias,logprobs:r.logprobs,max_tokens:r.max_tokens,n:r.n,presence_penalty:r.presence_penalty,seed:r.seed,stop:r.stop,stream:r.stream,temperature:r.temperature,top_p:r.top_p,user:r.user,response_format:r.response_format,top_logprobs:r.top_logprobs};let t=r.input;return r&&typeof r=="object"&&!Array.isArray(r)&&"messages"in r?(t={},t.messages=r.messages,"function_call"in r&&(t.function_call=r.function_call),"functions"in r&&(t.functions=r.functions),"tools"in r&&(t.tools=r.tools),"tool_choice"in r&&(t.tool_choice=r.tool_choice)):t||(t=r.prompt),{model:r.model,input:t,modelParameters:e}},he=r=>{if(r instanceof Object&&"output_text"in r&&r.output_text!=="")return r.output_text;if(typeof r=="object"&&r&&"output"in r&&Array.isArray(r.output)){const e=r.output;return e.length>1?e:e.length===1?e[0]:null}return r instanceof Object&&"choices"in r&&Array.isArray(r.choices)?"message"in r.choices[0]?r.choices[0].message:r.choices[0].text??"":""},He=r=>{if(me(r)){const{prompt_tokens:e,completion_tokens:t,total_tokens:s}=r.usage;return{input:e,output:t,total:s}}},pe=r=>{if("prompt_tokens"in r){const{prompt_tokens:e,completion_tokens:t,total_tokens:s,completion_tokens_details:n,prompt_tokens_details:o}=r;return{input:e,output:t,total:s,...Object.fromEntries(Object.entries(o??{}).map(([a,c])=>[`input_${a}`,c])),...Object.fromEntries(Object.entries(n??{}).map(([a,c])=>[`output_${a}`,c]))}}else if("input_tokens"in r){const{input_tokens:e,output_tokens:t,total_tokens:s,input_tokens_details:n,output_tokens_details:o}=r;return{input:e,output:t,total:s,...Object.fromEntries(Object.entries(n??{}).map(([a,c])=>[`input_${a}`,c])),...Object.fromEntries(Object.entries(o??{}).map(([a,c])=>[`output_${a}`,c]))}}},de=r=>{if(me(r))return pe(r.usage)},Qe=r=>{let e=!1;const s=r?.choices?.[0];try{if("delta"in s&&"tool_calls"in s.delta&&Array.isArray(s.delta.tool_calls))return e=!0,{isToolCall:e,data:s.delta.tool_calls[0]};if("delta"in s)return{isToolCall:e,data:s.delta?.content||""};if("text"in s)return{isToolCall:e,data:s.text||""}}catch{}return{isToolCall:!1,data:""}};function me(r){return r instanceof Object&&"usage"in r&&r.usage instanceof Object&&(typeof r.usage.prompt_tokens=="number"&&typeof r.usage.completion_tokens=="number"&&typeof r.usage.total_tokens=="number"||typeof r.usage.input_tokens=="number"&&typeof r.usage.output_tokens=="number"&&typeof r.usage.total_tokens=="number")}const Ve=r=>{let e="",t="";for(const s of r)e=s.function?.name||e,t+=s.function?.arguments||"";return{tool_calls:[{function:{name:e,arguments:t}}]}},fe=r=>{if(typeof r!="object"||r===null)return{model:void 0,modelParameters:void 0,metadata:void 0};const e="model"in r?r.model:void 0,t={},s=["max_output_tokens","parallel_tool_calls","store","temperature","tool_choice","top_p","truncation","user"],n={},o=["reasoning","incomplete_details","instructions","previous_response_id","tools","metadata","status","error"];for(const a of s){const c=a in r?r[a]:null;c!=null&&(t[a]=c)}for(const a of o){const c=a in r?r[a]:null;c&&(n[a]=c)}return{model:e,modelParameters:Object.keys(t).length>0?t:void 0,metadata:Object.keys(n).length>0?n:void 0}},Y=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",We=(r,e)=>(...t)=>Xe(r,e,...t),Xe=(r,e,...t)=>{const{model:s,input:n,modelParameters:o}=ze(t[0]??{}),a={...o,response_format:null},c={...e?.metadata,response_format:"response_format"in o?o.response_format:void 0};let i={model:s,input:n,modelParameters:a,name:e?.generationName,startTime:new Date,promptName:e?.langfusePrompt?.name,promptVersion:e?.langfusePrompt?.version,metadata:c},u;const h=e&&"parent"in e;h?(u=e.parent,i={...{...e,parent:void 0},...i,promptName:e?.promptName??e?.langfusePrompt?.name,promptVersion:e?.promptVersion??e?.langfusePrompt?.version}):u=S.getInstance(e?.clientInitParams).trace({...e,...i,id:e?.traceId,name:e?.traceName,timestamp:i.startTime});try{const l=r(...t);return Y(l)?Z(l,u,h,i):l instanceof Promise?l.then(m=>{if(Y(m))return Z(m,u,h,i);const y=he(m),_=He(m),E=de(m),{model:f,modelParameters:R,metadata:T}=fe(m);return u.generation({...i,output:y,endTime:new Date,usage:_,usageDetails:E,model:f||i.model,modelParameters:{...i.modelParameters,...R},metadata:{...i.metadata,...T}}),h||u.update({output:y}),m}).catch(m=>{throw u.generation({...i,endTime:new Date,statusMessage:String(m),level:"ERROR",usage:{inputCost:0,outputCost:0,totalCost:0},costDetails:{input:0,output:0,total:0}}),m}):l}catch(l){throw u.generation({...i,endTime:new Date,statusMessage:String(l),level:"ERROR",usage:{inputCost:0,outputCost:0,totalCost:0},costDetails:{input:0,output:0,total:0}}),l}};function Z(r,e,t,s){async function*n(){const o=r,a=[],c=[];let i=null,u=null,h,l=null;for await(const p of o){if(i=i??new Date,typeof p=="object"&&p&&"response"in p){const y=p.response;l=he(y),h=de(y);const{model:_,modelParameters:E,metadata:f}=fe(y);s.model=_??s.model,s.modelParameters={...s.modelParameters,...E},s.metadata={...s.metadata,...f}}typeof p=="object"&&p!=null&&"usage"in p&&(u=p.usage);const m=Qe(p);m.isToolCall?c.push(m.data):a.push(m.data),yield p}l=l??(c.length>0?Ve(c):a.join("")),e.generation({...s,output:l,endTime:new Date,completionStartTime:i,usage:u?{input:"prompt_tokens"in u?u.prompt_tokens:void 0,output:"completion_tokens"in u?u.completion_tokens:void 0,total:"total_tokens"in u?u.total_tokens:void 0}:void 0,usageDetails:h??(u?pe(u):void 0)}),t||e.update({output:l})}return n()}const Ye=(r,e)=>new Proxy(r,{get(t,s,n){const o=t[s],a=`${r.constructor?.name}.${s.toString()}`,c=e?.generationName??a,i=e&&"traceName"in e?e.traceName:c,u={...e,generationName:c,traceName:i};if(s==="flushAsync"){let l;return e&&"parent"in e?l=e.parent.client:l=S.getInstance(),l.flushAsync.bind(l)}if(s==="shutdownAsync"){let l;return e&&"parent"in e?l=e.parent.client:l=S.getInstance(),l.shutdownAsync.bind(l)}return typeof o=="function"?We(o.bind(t),u):o&&!Array.isArray(o)&&!(o instanceof Date)&&typeof o=="object"?Ye(o,u):Reflect.get(t,s,n)}});export{Je as Langfuse,v as LangfuseMedia,ot as LangfuseWeb,Je as default,Ye as observeOpenAI};
1
+ import{m as B}from"./langfuse-C4HKZ3NL-CsiDw8Wb.js";import"./index-CFpQGWTL.js";import"./chunk-VL2OQCWN-lvFdpsKs.js";import"./index-DRz5BQNA.js";import"./__vite-browser-external-DFygW7-s.js";import"./path-C9FudP8b.js";var J={};class ge{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(s=>s!==t)}}emit(e,t){for(const s of this.events[e]||[])s(t);for(const s of this.events["*"]||[])s(e,t)}}const ye=60;class be{constructor(e,t){this.value=e,this._expiry=Date.now()+t*1e3}get isExpired(){return Date.now()>this._expiry}}class _e{constructor(){this._cache=new Map,this._defaultTtlSeconds=ye,this._refreshingKeys=new Map}getIncludingExpired(e){return this._cache.get(e)??null}set(e,t,s){const n=s??this._defaultTtlSeconds;this._cache.set(e,new be(t,n))}addRefreshingPromise(e,t){this._refreshingKeys.set(e,t),t.then(()=>{this._refreshingKeys.delete(e)}).catch(()=>{this._refreshingKeys.delete(e)})}isRefreshing(e){return this._refreshingKeys.has(e)}invalidate(e){console.log("invalidating",e,this._cache.keys());for(const t of this._cache.keys())t.startsWith(e)&&this._cache.delete(t)}}var I;(function(r){r.Props="props",r.Queue="queue",r.OptedOut="opted_out"})(I||(I={}));var b;(function(r){r.ChatMessage="chatmessage",r.Placeholder="placeholder"})(b||(b={}));B.escape=function(r){return r};class ee{constructor(e,t=!1,s){this.name=e.name,this.version=e.version,this.config=e.config,this.labels=e.labels,this.tags=e.tags,this.isFallback=t,this.type=s,this.commitMessage=e.commitMessage}_transformToLangchainVariables(e){return this.escapeJsonForLangchain(e).replace(/\{\{(\w+)\}\}/g,"{$1}")}escapeJsonForLangchain(e){const t=[],s=[];let n=0;const o=e.length;for(;n<o;){const a=e[n];if(a==="{"){if(n+1<o&&e[n+1]==="{"){t.push("{{"),n+=2;continue}let c=n+1;for(;c<o&&/\s/.test(e[c]);)c++;const i=c<o&&(e[c]==="'"||e[c]==='"');t.push(i?"{{":"{"),s.push(i),n+=1;continue}if(a==="}"){if(n+1<o&&e[n+1]==="}"){t.push("}}"),n+=2;continue}const c=s.pop()??!1;t.push(c?"}}":"}"),n+=1;continue}t.push(a),n+=1}return t.join("")}}class k extends ee{constructor(e,t=!1){super(e,t,"text"),this.promptResponse=e,this.prompt=e.prompt}compile(e,t){return B.render(this.promptResponse.prompt,e??{})}getLangchainPrompt(e){return this._transformToLangchainVariables(this.prompt)}toJSON(){return JSON.stringify({name:this.name,prompt:this.prompt,version:this.version,isFallback:this.isFallback,tags:this.tags,labels:this.labels,type:this.type,config:this.config})}}class O extends ee{constructor(e,t=!1){const s=O.normalizePrompt(e.prompt),n={...e,prompt:s};super(n,t,"chat"),this.promptResponse=n,this.prompt=s}static normalizePrompt(e){return e.map(t=>"type"in t?t:{type:b.ChatMessage,...t})}compile(e,t){const s=[],n=t??{};for(const o of this.prompt)if("type"in o&&o.type===b.Placeholder){const a=n[o.name];Array.isArray(a)&&a.length>0&&a.every(c=>typeof c=="object"&&"role"in c&&"content"in c)?s.push(...a):Array.isArray(a)&&a.length===0||(a!==void 0?s.push(JSON.stringify(a)):s.push(o))}else"role"in o&&"content"in o&&o.type===b.ChatMessage&&s.push({role:o.role,content:o.content});return s.map(o=>typeof o=="object"&&o!==null&&"role"in o&&"content"in o?{...o,content:B.render(o.content,e??{})}:o)}getLangchainPrompt(e){const t=[],s=e?.placeholders??{};for(const n of this.prompt)if("type"in n&&n.type===b.Placeholder){const o=s[n.name];Array.isArray(o)&&o.length>0&&o.every(a=>typeof a=="object"&&"role"in a&&"content"in a)?t.push(...o.map(a=>({role:a.role,content:this._transformToLangchainVariables(a.content)}))):Array.isArray(o)&&o.length===0||(o!==void 0?t.push(JSON.stringify(o)):t.push({variableName:n.name,optional:!1}))}else"role"in n&&"content"in n&&n.type===b.ChatMessage&&t.push({role:n.role,content:this._transformToLangchainVariables(n.content)});return t}toJSON(){return JSON.stringify({name:this.name,prompt:this.promptResponse.prompt.map(e=>{if("type"in e&&e.type===b.ChatMessage){const{type:t,...s}=e;return s}return e}),version:this.version,isFallback:this.isFallback,tags:this.tags,labels:this.labels,type:this.type,config:this.config})}}function Ee(r,e){if(!r)throw new Error(e)}function te(r){return r?.replace(/\/+$/,"")}async function F(r,e={},t){const{retryCount:s=3,retryDelay:n=5e3,retryCheck:o=()=>!0}=e;let a=null;for(let c=0;c<s+1;c++){c>0&&(await new Promise(i=>setTimeout(i,n)),t(`Retrying ${c+1} of ${s+1}`));try{return await r()}catch(i){if(a=i,!o(i))throw i;t(`Retriable error: ${JSON.stringify(i)}`)}}throw a}function w(r){let e=new Date().getTime(),t=r&&r.performance&&r.performance.now&&r.performance.now()*1e3||0;return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(s){let n=Math.random()*16;return e>0?(n=(e+n)%16|0,e=Math.floor(e/16)):(n=(t+n)%16|0,t=Math.floor(t/16)),(s==="x"?n:n&3|8).toString(16)})}function we(){return new Date().getTime()}function se(){return new Date().toISOString()}function re(r,e){const t=setTimeout(r,e);return t?.unref&&t?.unref(),t}function g(r){if(typeof process<"u"&&J[r])return J[r];if(typeof globalThis<"u")return globalThis[r]}function Se(r,e=!0){const{publicKey:t,secretKey:s,...n}=r??{},o=t??g("LANGFUSE_PUBLIC_KEY"),a=e?s??g("LANGFUSE_SECRET_KEY"):void 0,c=n.baseUrl??g("LANGFUSE_BASEURL"),i={...n,baseUrl:c};return{publicKey:o,...e?{secretKey:a}:void 0,...i}}const C=r=>{const e=new URLSearchParams;return Object.entries(r??{}).forEach(([t,s])=>{s!=null&&(s instanceof Date?e.append(t,s.toISOString()):e.append(t,s.toString()))}),e.toString()};var ne=Object.freeze({__proto__:null,assert:Ee,configLangfuseSDK:Se,currentISOTime:se,currentTimestamp:we,encodeQueryParams:C,generateUUID:w,getEnv:g,removeTrailingSlash:te,retriable:F,safeSetTimeout:re});const ve=["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","TRIGGER_DEPLOYMENT_ID"];function Te(){for(const r of ve){const e=g(r);if(e)return e}}let P=null,$=null;const j=r=>import(r);typeof globalThis.Deno<"u"?Promise.all([j("node:fs"),j("node:crypto")]).then(([r,e])=>{P=r,$=e}).catch():typeof process<"u"&&process.versions?.node?Promise.all([j("fs"),j("crypto")]).then(([r,e])=>{P=r,$=e}).catch():typeof crypto<"u"&&($=crypto);class v{constructor(e){const{obj:t,base64DataUri:s,contentType:n,contentBytes:o,filePath:a}=e;if(this.obj=t,this._mediaId=void 0,s){const[c,i]=this.parseBase64DataUri(s);this._contentBytes=c,this._contentType=i,this._source="base64_data_uri"}else if(o&&n)this._contentBytes=o,this._contentType=n,this._source="bytes";else if(a&&n){if(!P)throw new Error("File system support is not available in this environment");if(!P.existsSync(a))throw new Error(`File at path ${a} does not exist`);this._contentBytes=this.readFile(a),this._contentType=this._contentBytes?n:void 0,this._source=this._contentBytes?"file":void 0}else console.error("base64DataUri, or contentBytes and contentType, or filePath must be provided to LangfuseMedia")}readFile(e){try{if(!P)throw new Error("File system support is not available in this environment");return P.readFileSync(e)}catch(t){console.error(`Error reading file at path ${e}`,t);return}}parseBase64DataUri(e){try{if(!e||typeof e!="string")throw new Error("Data URI is not a string");if(!e.startsWith("data:"))throw new Error("Data URI does not start with 'data:'");const[t,s]=e.slice(5).split(",",2);if(!t||!s)throw new Error("Invalid URI");const n=t.split(";");if(!n.includes("base64"))throw new Error("Data is not base64 encoded");const o=n[0];if(!o)throw new Error("Content type is empty");return[Buffer.from(s,"base64"),o]}catch(t){return console.error("Error parsing base64 data URI",t),[void 0,void 0]}}get contentLength(){return this._contentBytes?.length}get contentSha256Hash(){if(!this._contentBytes)return;if(!$){console.error("Crypto support is not available in this environment");return}return $.createHash("sha256").update(this._contentBytes).digest("base64")}toJSON(){return!this._contentType||!this._source||!this._mediaId?`<Upload handling failed for LangfuseMedia of type ${this._contentType}>`:`@@@langfuseMedia:type=${this._contentType}|id=${this._mediaId}|source=${this._source}@@@`}static parseReferenceString(e){const t="@@@langfuseMedia:";if(!e.startsWith(t))throw new Error("Reference string does not start with '@@@langfuseMedia:type='");if(!e.endsWith("@@@"))throw new Error("Reference string does not end with '@@@'");const o=e.slice(t.length,-3).split("|"),a={};for(const c of o){const[i,u]=c.split("=",2);a[i]=u}if(!("type"in a&&"id"in a&&"source"in a))throw new Error("Missing required fields in reference string");return{mediaId:a.id,source:a.source,contentType:a.type}}static async resolveMediaReferences(e){const{obj:t,langfuseClient:s,maxDepth:n=10}=e;async function o(a,c){if(c>n)return a;if(typeof a=="string"){const i=/@@@langfuseMedia:.+?@@@/g,u=a.match(i);if(!u)return a;let h=a;const l=new Map;await Promise.all(u.map(async p=>{try{const m=v.parseReferenceString(p),y=await s.fetchMedia(m.mediaId),_=await s.fetch(y.url,{method:"GET",headers:{}});if(_.status!==200)throw new Error("Failed to fetch media content");const E=Buffer.from(await _.arrayBuffer()).toString("base64"),f=`data:${y.contentType};base64,${E}`;l.set(p,f)}catch(m){console.warn("Error fetching media content for reference string",p,m)}}));for(const[p,m]of l.entries())h=h.replaceAll(p,m);return h}return Array.isArray(a)?Promise.all(a.map(async i=>await o(i,c+1))):typeof a=="object"&&a!==null?Object.fromEntries(await Promise.all(Object.entries(a).map(async([i,u])=>[i,await o(u,c+1)]))):a}return o(t,0)}}function Ie(r,e){return e===void 0?!0:e===0?!1:e<0||e>1||isNaN(e)?(console.warn("Sample rate must be between 0 and 1. Ignoring setting."),!0):Pe(r)<e}function Pe(r){let e=0;const t=31;for(let s=0;s<r.length;s++)e=e*t+r.charCodeAt(s)>>>0;return e=(e>>>16^e)*73244475,e=(e>>>16^e)*73244475,e=e>>>16^e,Math.abs(e)/2147483647}const z=g("LANGFUSE_MAX_EVENT_SIZE_BYTES")?Number(g("LANGFUSE_MAX_EVENT_SIZE_BYTES")):1e6,Le=g("LANGFUSE_MAX_BATCH_SIZE_BYTES")?Number(g("LANGFUSE_MAX_BATCH_SIZE_BYTES")):25e5,H=/^(?!langfuse)[a-z0-9_-]+$/,Ae=["langfuse-prompt-experiment"];class U extends Error{constructor(e,t){super("HTTP error while fetching Langfuse: "+e.status+" and body: "+t),this.response=e,this.name="LangfuseFetchHttpError"}}class M extends Error{constructor(e){super("Network error while fetching Langfuse",e instanceof Error?{cause:e}:{}),this.error=e,this.name="LangfuseFetchNetworkError"}}function oe(r){return typeof r=="object"&&r.name==="LangfuseFetchHttpError"}function ae(r){return typeof r=="object"&&r.name==="LangfuseFetchNetworkError"}function Ce(r){return oe(r)||ae(r)}const D="https://langfuse.com/support",Oe="https://api.reference.langfuse.com",$e="https://langfuse.com/docs/rbac",Re="https://langfuse.com/docs/sdk/typescript/guide",je="https://langfuse.com/faq/all/api-limits",Ue="https://www.npmjs.com/package/langfuse",Q=`Make sure to keep your SDK updated, refer to ${Ue} for details.`,x=`This is an unusual occurrence and we are monitoring it closely. For help, please contact support: ${D}.`,V=`Unexpected error occurred. Please check your request and contact support: ${D}.`,xe=new Map([[500,`Internal server error occurred. For help, please contact support: ${D}`],[501,`Not implemented. Please check your request and contact support for help: ${D}.`],[502,`Bad gateway. ${x}`],[503,`Service unavailable. ${x}`],[504,`Gateway timeout. ${x}`],[404,`Internal error occurred. ${x}`],[400,`Bad request. Please check your request for any missing or incorrect parameters. Refer to our API docs: ${Oe} for details.`],[401,`Unauthorized. Please check your public/private host settings. Refer to our installation and setup guide: ${Re} for details on SDK configuration.`],[403,`Forbidden. Please check your access control settings. Refer to our RBAC docs: ${$e} for details.`],[429,`Rate limit exceeded. For more information on rate limits please see: ${je}`]]);function De(r){if(!r)return`${V} ${Q}`;const e=xe.get(r)||V;return`${r}: ${e} ${Q}`}function G(r){if(oe(r)){const e=r.response.status,t=De(e);console.error("[Langfuse SDK]",t,`Error details: ${r}`)}else ae(r)?console.error("[Langfuse SDK] Network error: ",r):console.error("[Langfuse SDK] Unknown error:",r)}class ie{constructor(e){this.additionalHeaders={},this.debugMode=!1,this.pendingEventProcessingPromises={},this.pendingIngestionPromises={},this.localEventExportMap=new Map,this._events=new ge;const{publicKey:t,secretKey:s,enabled:n,_projectId:o,_isLocalEventExportEnabled:a,...c}=e;if(this._events.on("error",i=>{console.error(`[Langfuse SDK] ${typeof i=="string"?i:JSON.stringify(i)}`)}),this.enabled=n!==!1,this.publicKey=t??"",this.secretKey=s,this.baseUrl=te(c?.baseUrl||"https://cloud.langfuse.com"),this.additionalHeaders=c?.additionalHeaders||{},this.flushAt=c?.flushAt?Math.max(c?.flushAt,1):15,this.flushInterval=c?.flushInterval??1e4,this.release=c?.release??g("LANGFUSE_RELEASE")??Te()??void 0,this.mask=c?.mask,this.sampleRate=c?.sampleRate??(g("LANGFUSE_SAMPLE_RATE")?Number(g("LANGFUSE_SAMPLE_RATE")):void 0),this.sampleRate&&this._events.emit("debug",`Langfuse trace sampling enabled with sampleRate ${this.sampleRate}.`),this.environment=c?.environment??g("LANGFUSE_TRACING_ENVIRONMENT"),this.environment&&!(H.test(this.environment)||Ae.includes(this.environment))&&!a&&this._events.emit("error",`Invalid tracing environment set: ${this.environment} . Environment must match regex ${H}. Events will be rejected by Langfuse server.`),this._retryOptions={retryCount:c?.fetchRetryCount??3,retryDelay:c?.fetchRetryDelay??3e3,retryCheck:Ce},this.requestTimeout=c?.requestTimeout??5e3,this.sdkIntegration=c?.sdkIntegration??"DEFAULT",this.isLocalEventExportEnabled=a??!1,this.isLocalEventExportEnabled&&!o){this._events.emit("error","Local event export is enabled, but no project ID was provided. Disabling local export."),this.isLocalEventExportEnabled=!1;return}else if(!this.isLocalEventExportEnabled&&o){this._events.emit("error","Local event export is disabled, but a project ID was provided. Disabling local export."),this.isLocalEventExportEnabled=!1;return}else this.projectId=o}getSdkIntegration(){return this.sdkIntegration}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}on(e,t){return this._events.on(e,t)}debug(e=!0){this.removeDebugCallback?.(),this.debugMode=e,e&&(this.removeDebugCallback=this.on("*",(t,s)=>{t!=="error"&&console.log("[Langfuse Debug]",t,JSON.stringify(s))}))}traceStateless(e){const{id:t,timestamp:s,release:n,...o}=e,a=t??w(),c=n??this.release,i={id:a,release:c,timestamp:s??new Date,environment:this.environment,...o};return this.enqueue("trace-create",i),a}eventStateless(e){const{id:t,startTime:s,...n}=e,o=t??w(),a={id:o,startTime:s??new Date,environment:this.environment,...n};return this.enqueue("event-create",a),o}spanStateless(e){const{id:t,startTime:s,...n}=e,o=t||w(),a={id:o,startTime:s??new Date,environment:this.environment,...n};return this.enqueue("span-create",a),o}generationStateless(e){const{id:t,startTime:s,prompt:n,...o}=e,a=n&&!n.isFallback?{promptName:n.name,promptVersion:n.version}:{},c=t||w(),i={id:c,startTime:s??new Date,environment:this.environment,...a,...o};return this.enqueue("generation-create",i),c}scoreStateless(e){const{id:t,...s}=e,n=t||w(),o={id:n,environment:this.environment,...s};return this.enqueue("score-create",o),n}updateSpanStateless(e){return this.enqueue("span-update",e),e.id}updateGenerationStateless(e){const{prompt:t,...s}=e,o={...t&&!t.isFallback?{promptName:t.name,promptVersion:t.version}:{},...s};return this.enqueue("generation-update",o),e.id}async _getDataset(e){const t=encodeURIComponent(e);return this.fetchAndLogErrors(`${this.baseUrl}/api/public/v2/datasets/${t}`,this._getFetchOptions({method:"GET"}))}async _getDatasetItems(e){const t=new URLSearchParams;return Object.entries(e??{}).forEach(([s,n])=>{n!=null&&t.append(s,n.toString())}),this.fetchAndLogErrors(`${this.baseUrl}/api/public/dataset-items?${t}`,this._getFetchOptions({method:"GET"}))}async _fetchMedia(e){return this.fetchAndLogErrors(`${this.baseUrl}/api/public/media/${e}`,this._getFetchOptions({method:"GET"}))}async fetchTraces(e){const{data:t,meta:s}=await this.fetchAndLogErrors(`${this.baseUrl}/api/public/traces?${C(e)}`,this._getFetchOptions({method:"GET"}));return{data:t,meta:s}}async fetchTrace(e){return{data:await this.fetchAndLogErrors(`${this.baseUrl}/api/public/traces/${e}`,this._getFetchOptions({method:"GET"}))}}async fetchObservations(e){const{data:t,meta:s}=await this.fetchAndLogErrors(`${this.baseUrl}/api/public/observations?${C(e)}`,this._getFetchOptions({method:"GET"}));return{data:t,meta:s}}async fetchObservation(e){return{data:await this.fetchAndLogErrors(`${this.baseUrl}/api/public/observations/${e}`,this._getFetchOptions({method:"GET"}))}}async fetchSessions(e){const{data:t,meta:s}=await this.fetchAndLogErrors(`${this.baseUrl}/api/public/sessions?${C(e)}`,this._getFetchOptions({method:"GET"}));return{data:t,meta:s}}async getDatasetRun(e){const t=encodeURIComponent(e.datasetName),s=encodeURIComponent(e.runName);return this.fetchAndLogErrors(`${this.baseUrl}/api/public/datasets/${t}/runs/${s}`,this._getFetchOptions({method:"GET"}))}async getDatasetRuns(e,t){return this.fetchAndLogErrors(`${this.baseUrl}/api/public/datasets/${encodeURIComponent(e)}/runs?${C(t)}`,this._getFetchOptions({method:"GET"}))}async createDatasetRunItem(e){return this.fetchAndLogErrors(`${this.baseUrl}/api/public/dataset-run-items`,this._getFetchOptions({method:"POST",body:JSON.stringify(e)}))}async createDataset(e){const t=typeof e=="string"?{name:e}:e;return this.fetchAndLogErrors(`${this.baseUrl}/api/public/datasets`,this._getFetchOptions({method:"POST",body:JSON.stringify(t)}))}async createDatasetItem(e){return this.fetchAndLogErrors(`${this.baseUrl}/api/public/dataset-items`,this._getFetchOptions({method:"POST",body:JSON.stringify(e)}))}async getDatasetItem(e){return this.fetchAndLogErrors(`${this.baseUrl}/api/public/dataset-items/${e}`,this._getFetchOptions({method:"GET"}))}_parsePayload(e){try{return JSON.parse(e)}catch{return e}}async createPromptStateless(e){return this.fetchAndLogErrors(`${this.baseUrl}/api/public/v2/prompts`,this._getFetchOptions({method:"POST",body:JSON.stringify(e)}))}async updatePromptStateless(e){return this.fetchAndLogErrors(`${this.baseUrl}/api/public/v2/prompts/${encodeURIComponent(e.name)}/versions/${encodeURIComponent(e.version)}`,this._getFetchOptions({method:"PATCH",body:JSON.stringify(e)}))}async getPromptStateless(e,t,s,n,o){const a=encodeURIComponent(e),c=new URLSearchParams;if(t&&s)throw new Error("Provide either version or label, not both.");t&&c.append("version",t.toString()),s&&c.append("label",s);const i=`${this.baseUrl}/api/public/v2/prompts/${a}${c.size?"?"+c:""}`,u=this._getBoundedMaxRetries({maxRetries:n,defaultMaxRetries:2,maxRetriesUpperBound:4}),h={...this._retryOptions,retryCount:u,retryDelay:500};return F(async()=>{const p=await this.fetch(i,this._getFetchOptions({method:"GET",fetchTimeout:o??this.requestTimeout})).catch(y=>{throw y.name==="AbortError"?new M("Fetch request timed out"):new M(y)});if(p.status>=500)throw new U(p,await p.text());const m=await p.json();return{fetchResult:p.status===200?"success":"failure",data:m}},h,p=>this._events.emit("retry",p+", "+i+", "+JSON.stringify(h)))}_getBoundedMaxRetries(e){const t=Math.max(e.defaultMaxRetries??2,0),s=Math.max(e.maxRetriesUpperBound??4,0);return e.maxRetries===void 0?t:Math.min(Math.max(e.maxRetries,0),s)}enqueue(e,t){if(!this.enabled)return;const s=this.parseTraceId(e,t);if(!s)this._events.emit("warning","Failed to parse traceID for sampling. Please open a Github issue in https://github.com/langfuse/langfuse/issues/new/choose");else if(!Ie(s,this.sampleRate)){this._events.emit("debug",`Event with trace ID ${s} is out of sample. Skipping.`);return}const n=this.processEnqueueEvent(e,t),o=w();this.pendingEventProcessingPromises[o]=n,n.catch(a=>{this._events.emit("error",a)}).finally(()=>{delete this.pendingEventProcessingPromises[o]})}async processEnqueueEvent(e,t){this.maskEventBodyInPlace(t),await this.processMediaInEvent(e,t);const s=this.truncateEventBody(t,z);try{JSON.stringify(s)}catch(o){this._events.emit("error",`Event Body for ${e} is not JSON-serializable: ${o}`);return}const n=this.getPersistedProperty(I.Queue)||[];n.push({id:w(),type:e,timestamp:se(),body:s,metadata:void 0}),this.setPersistedProperty(I.Queue,n),this._events.emit(e,s),n.length>=this.flushAt&&this.flush(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=re(()=>this.flush(),this.flushInterval))}maskEventBodyInPlace(e){if(!this.mask)return;const t=["input","output"];for(const s of t)if(s in e)try{e[s]=this.mask({data:e[s]})}catch(n){this._events.emit("error",`Error masking ${s}: ${n}`),e[s]="<fully masked due to failed mask function>"}}truncateEventBody(e,t){const s=this.getByteSize(e);if(s<=t)return e;this._events.emit("warning",`Event Body is too large (${s} bytes) and will be truncated`);const o=["input","output","metadata"].map(i=>({key:i,size:i in e?this.getByteSize(e[i]):0})).sort((i,u)=>u.size-i.size);let a={...e},c=s;for(const{key:i,size:u}of o)c>t&&Object.prototype.hasOwnProperty.call(a,i)&&(a={...a,[i]:"<truncated due to size exceeding limit>"},this._events.emit("warning",`Truncated ${i} due to total size exceeding limit`),c-=u);return a}getByteSize(e){const t=JSON.stringify(e);return typeof TextEncoder<"u"?new TextEncoder().encode(t).length:encodeURIComponent(t).replace(/%[A-F\d]{2}/g,"U").length}async processMediaInEvent(e,t){if(!t)return;const s=this.parseTraceId(e,t);if(!s){this._events.emit("warning","traceId is required for media upload");return}const n=(e.includes("generation")||e.includes("span"))&&t.id?t.id:void 0;await Promise.all(["input","output","metadata"].map(async o=>{t[o]&&(t[o]=await this.findAndProcessMedia({data:t[o],traceId:s,observationId:n,field:o}).catch(a=>{this._events.emit("error",`Error processing multimodal event: ${a}`)})??t[o])}))}parseTraceId(e,t){return"traceId"in t?t.traceId:e.includes("trace")?t.id:void 0}async findAndProcessMedia({data:e,traceId:t,observationId:s,field:n}){const o=new WeakMap,a=10,c=async(i,u)=>{if(typeof i=="string"&&i.startsWith("data:")){const h=new v({base64DataUri:i});return await this.processMediaItem({media:h,traceId:t,observationId:s,field:n}),h}if(typeof i!="object"||i===null||o.has(i)||u>a)return i;if(o.set(i,!0),i instanceof v||Object.prototype.toString.call(i)==="[object LangfuseMedia]")return await this.processMediaItem({media:i,traceId:t,observationId:s,field:n}),i;if(Array.isArray(i))return await Promise.all(i.map(h=>c(h,u+1)));if(typeof i=="object"&&i!==null){if("input_audio"in i&&typeof i.input_audio=="object"&&"data"in i.input_audio){const h=new v({base64DataUri:`data:audio/${i.input_audio.format||"wav"};base64,${i.input_audio.data}`});return await this.processMediaItem({media:h,traceId:t,observationId:s,field:n}),{...i,input_audio:{...i.input_audio,data:h}}}if("audio"in i&&typeof i.audio=="object"&&"data"in i.audio){const h=new v({base64DataUri:`data:audio/${i.audio.format||"wav"};base64,${i.audio.data}`});return await this.processMediaItem({media:h,traceId:t,observationId:s,field:n}),{...i,audio:{...i.audio,data:h}}}return Object.fromEntries(await Promise.all(Object.entries(i).map(async([h,l])=>[h,await c(l,u+1)])))}return i};return await c(e,1)}async processMediaItem({media:e,traceId:t,observationId:s,field:n}){try{if(!e.contentLength||!e._contentType||!e.contentSha256Hash||!e._contentBytes)return;const o={contentLength:e.contentLength,traceId:t,observationId:s,field:n,contentType:e._contentType,sha256Hash:e.contentSha256Hash},c=await(await this.fetch(`${this.baseUrl}/api/public/media`,this._getFetchOptions({method:"POST",body:JSON.stringify(o)}))).json(),{uploadUrl:i,mediaId:u}=c;if(e._mediaId=u,i){this._events.emit("debug",`Uploading media ${u}`);const h=Date.now(),l=await this.uploadMediaWithBackoff({uploadUrl:i,contentBytes:e._contentBytes,contentType:e._contentType,contentSha256Hash:e.contentSha256Hash,maxRetries:3,baseDelay:1e3});if(!l)throw Error("Media upload process failed");const p={uploadedAt:new Date().toISOString(),uploadHttpStatus:l.status,uploadHttpError:await l.text(),uploadTimeMs:Date.now()-h};await this.fetch(`${this.baseUrl}/api/public/media/${u}`,this._getFetchOptions({method:"PATCH",body:JSON.stringify(p)})),this._events.emit("debug",`Media upload status reported for ${u}`)}else this._events.emit("debug",`Media ${u} already uploaded`)}catch(o){this._events.emit("error",`Error processing media item: ${o}`)}}async uploadMediaWithBackoff(e){const{uploadUrl:t,contentType:s,contentSha256Hash:n,contentBytes:o,maxRetries:a,baseDelay:c}=e;for(let i=0;i<=a;i++)try{const u=await this.fetch(t,{method:"PUT",body:o,headers:{"Content-Type":s,"x-amz-checksum-sha256":n,"x-ms-blob-type":"BlockBlob"}});if(i<a&&u.status!==200&&u.status!==201)throw new Error(`Upload failed with status ${u.status}`);return u}catch(u){if(i===a)throw u;const h=c*Math.pow(2,i),l=Math.random()*1e3;await new Promise(p=>setTimeout(p,h+l))}}async flushAsync(){return await Promise.all(Object.values(this.pendingEventProcessingPromises)).catch(e=>{G(e)}),new Promise((e,t)=>{try{this.flush((s,n)=>{s?(G(s),e()):e(n)})}catch(s){console.error("[Langfuse SDK] Error while flushing Langfuse",s)}})}flush(e){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=null);const t=this.getPersistedProperty(I.Queue)||[];if(!t.length)return e?.();const s=t.splice(0,this.flushAt),{processedItems:n,remainingItems:o}=this.processQueueItems(s,z,Le);this.setPersistedProperty(I.Queue,[...o,...t]);const a=w(),c=p=>{p&&this._events.emit("warning",p),e?.(p,s),this._events.emit("flush",s)};if(this.isLocalEventExportEnabled&&this.projectId){this.localEventExportMap.has(this.projectId)?this.localEventExportMap.get(this.projectId)?.push(...s):this.localEventExportMap.set(this.projectId,[...s]),c();return}const i=JSON.stringify({batch:n,metadata:{batch_size:n.length,sdk_integration:this.sdkIntegration,sdk_version:this.getLibraryVersion(),sdk_variant:this.getLibraryId(),public_key:this.publicKey,sdk_name:"langfuse-js"}}),u=`${this.baseUrl}/api/public/ingestion`,h=this._getFetchOptions({method:"POST",body:i}),l=this.fetchWithRetry(u,h).then(()=>c()).catch(p=>{c(p)});this.pendingIngestionPromises[a]=l,l.finally(()=>{delete this.pendingIngestionPromises[a]})}processQueueItems(e,t,s){let n=0;const o=[],a=[];for(let c=0;c<e.length;c++)try{const i=new Blob([JSON.stringify(e[c])]).size;if(i>t){console.warn(`Item exceeds size limit (size: ${i}), dropping item.`);continue}if(n+i>=s){console.debug(`hit batch size limit (size: ${n+i})`),a.push(...e.slice(c)),console.log(`Remaining items: ${a.length}`),console.log(`processes items: ${o.length}`);break}n+=i,o.push(e[c])}catch(i){this._events.emit("error",i),a.push(...e.slice(c));break}return{processedItems:o,remainingItems:a}}_getFetchOptions(e){return{method:e.method,headers:{"Content-Type":"application/json","X-Langfuse-Sdk-Name":"langfuse-js","X-Langfuse-Sdk-Version":this.getLibraryVersion(),"X-Langfuse-Sdk-Variant":this.getLibraryId(),"X-Langfuse-Sdk-Integration":this.sdkIntegration,"X-Langfuse-Public-Key":this.publicKey,...this.additionalHeaders,...this.constructAuthorizationHeader(this.publicKey,this.secretKey)},body:e.body,...e.fetchTimeout!==void 0?{signal:AbortSignal.timeout(e.fetchTimeout)}:{}}}constructAuthorizationHeader(e,t){return t===void 0?{Authorization:"Bearer "+e}:{Authorization:"Basic "+(typeof btoa=="function"?btoa(e+":"+t):Buffer.from(e+":"+t).toString("base64"))}}async fetchWithRetry(e,t,s){return AbortSignal.timeout??=function(o){const a=new AbortController;return setTimeout(()=>a.abort(),o),a.signal},await F(async()=>{let n=null;try{n=await this.fetch(e,{signal:AbortSignal.timeout(this.requestTimeout),...t})}catch(a){throw new M(a)}if(n.status<200||n.status>=400){const a=await n.json();throw new U(n,JSON.stringify(a))}const o=await n.json();if(n.status===207&&o.errors.length>0)throw new U(n,JSON.stringify(o.errors));return n},{...this._retryOptions,...s},n=>this._events.emit("retry",n+", "+e+", "+JSON.stringify(t)))}async fetchAndLogErrors(e,t){const s=await this.fetch(e,t),n=s.status===429?await s.text():await s.json();return(s.status<200||s.status>=400)&&G(new U(s,JSON.stringify(n))),n}async shutdownAsync(){clearTimeout(this._flushTimer);try{await this.flushAsync(),await Promise.all(Object.values(this.pendingIngestionPromises).map(e=>e.catch(()=>{}))),await this.flushAsync()}catch(e){console.error("[Langfuse SDK] Error while shutting down Langfuse",e)}}async _exportLocalEvents(e){if(this.isLocalEventExportEnabled){clearTimeout(this._flushTimer),await this.flushAsync();const t=this.localEventExportMap.get(e)??[];return this.localEventExportMap.delete(e),t}else return this._events.emit("error","Local event exports are disabled, but _exportLocalEvents() was called."),[]}shutdown(){console.warn("shutdown() is deprecated. It does not wait for all events to be processed. Please use shutdownAsync() instead."),this.shutdownAsync()}async awaitAllQueuedAndPendingRequests(){clearTimeout(this._flushTimer),await this.flushAsync(),await Promise.all(Object.values(this.pendingIngestionPromises))}}class qe extends ie{constructor(e){const{flushAt:t,flushInterval:s,publicKey:n,enabled:o,...a}=e;let c=o!==!1;c&&!n&&(c=!1,console.warn("Langfuse public key not passed to constructor and not set as 'LANGFUSE_PUBLIC_KEY' environment variable. No observability data will be sent to Langfuse.")),super({...a,publicKey:n,flushAt:t??1,flushInterval:s??0,enabled:c})}async score(e){return this.scoreStateless(e),await this.awaitAllQueuedAndPendingRequests(),this}}class ke extends ie{constructor(e){const{publicKey:t,secretKey:s,enabled:n,_isLocalEventExportEnabled:o}=e;let a=n!==!1;o?a=!0:s?t||(a=!1,n!==!1&&console.warn("Langfuse public key was not passed to constructor or not set as 'LANGFUSE_PUBLIC_KEY' environment variable. No observability data will be sent to Langfuse.")):(a=!1,n!==!1&&console.warn("Langfuse secret key was not passed to constructor or not set as 'LANGFUSE_SECRET_KEY' environment variable. No observability data will be sent to Langfuse.")),super({...e,enabled:a}),this._promptCache=new _e}trace(e){const t=this.traceStateless(e??{}),s=new Me(this,t);if(g("DEFER")&&e)try{const n=g("__deferRuntime");n&&n.langfuseTraces([{id:t,name:e.name||"",url:s.getTraceUrl()}])}catch{}return s}span(e){const t=e.traceId||this.traceStateless({name:e.name}),s=this.spanStateless({...e,traceId:t});return new Ge(this,s,t)}generation(e){const t=e.traceId||this.traceStateless({name:e.name}),s=this.generationStateless({...e,traceId:t});return new Ne(this,s,t)}event(e){const t=e.traceId||this.traceStateless({name:e.name}),s=this.eventStateless({...e,traceId:t});return new Fe(this,s,t)}score(e){return this.scoreStateless(e),this}async getDataset(e,t){const s=await this._getDataset(e),n=[];let o=1;for(;;){const c=await this._getDatasetItems({datasetName:e,limit:t?.fetchItemsPageSize??50,page:o});if(n.push(...c.data),c.meta.totalPages<=o)break;o++}return{...s,description:s.description??void 0,metadata:s.metadata??void 0,items:n.map(c=>({...c,link:async(i,u,h)=>(await this.awaitAllQueuedAndPendingRequests(),await this.createDatasetRunItem({runName:u,datasetItemId:c.id,observationId:i.observationId,traceId:i.traceId,runDescription:h?.description,metadata:h?.metadata}))}))}}async createPrompt(e){const t=e.labels??[],s=e.type==="chat"?await this.createPromptStateless({...e,prompt:e.prompt.map(n=>"type"in n&&n.type===b.Placeholder?{type:b.Placeholder,name:n.name}:{type:b.ChatMessage,...n}),labels:e.isActive?[...new Set([...t,"production"])]:t}):await this.createPromptStateless({...e,type:e.type??"text",labels:e.isActive?[...new Set([...t,"production"])]:t});return s.type==="chat"?new O(s):new k(s)}async updatePrompt(e){const t=await this.updatePromptStateless(e);return this._promptCache.invalidate(e.name),t}async getPrompt(e,t,s){const n=this._getPromptCacheKey({name:e,version:t,label:s?.label}),o=this._promptCache.getIncludingExpired(n);if(!o||s?.cacheTtlSeconds===0)try{return await this._fetchPromptAndUpdateCache({name:e,version:t,label:s?.label,cacheTtlSeconds:s?.cacheTtlSeconds,maxRetries:s?.maxRetries,fetchTimeout:s?.fetchTimeoutMs})}catch(a){if(s?.fallback){const c={name:e,version:t??0,labels:s.label?[s.label]:[],cacheTtlSeconds:s?.cacheTtlSeconds,config:{},tags:[]};return s.type==="chat"?new O({...c,type:"chat",prompt:s.fallback.map(i=>({type:b.ChatMessage,...i}))},!0):new k({...c,type:"text",prompt:s.fallback},!0)}throw a}if(o.isExpired){if(!this._promptCache.isRefreshing(n)){const a=this._fetchPromptAndUpdateCache({name:e,version:t,label:s?.label,cacheTtlSeconds:s?.cacheTtlSeconds,maxRetries:s?.maxRetries,fetchTimeout:s?.fetchTimeoutMs}).catch(()=>{console.warn(`Failed to refresh prompt cache '${n}', stale cache will be used until next refresh succeeds.`)});this._promptCache.addRefreshingPromise(n,a)}return o.value}return o.value}_getPromptCacheKey(e){const{name:t,version:s,label:n}=e,o=[t];return s!==void 0?o.push("version:"+s.toString()):n!==void 0?o.push("label:"+n):o.push("label:production"),o.join("-")}async _fetchPromptAndUpdateCache(e){const t=this._getPromptCacheKey(e);try{const{name:s,version:n,cacheTtlSeconds:o,label:a,maxRetries:c,fetchTimeout:i}=e,{data:u,fetchResult:h}=await this.getPromptStateless(s,n,a,c,i);if(h==="failure")throw Error(u.message??"Internal error while fetching prompt");let l;return u.type==="chat"?l=new O(u):l=new k(u),this._promptCache.set(t,l,o),l}catch(s){throw console.error(`[Langfuse SDK] Error while fetching prompt '${t}':`,s),s}}async fetchMedia(e){return await this._fetchMedia(e)}async resolveMediaReferences(e){const{obj:t,...s}=e;return v.resolveMediaReferences({...s,langfuseClient:this,obj:t})}_updateSpan(e){return this.updateSpanStateless(e),this}_updateGeneration(e){return this.updateGenerationStateless(e),this}}class ce{constructor({client:e,id:t,traceId:s,observationId:n}){this.client=e,this.id=t,this.traceId=s,this.observationId=n}event(e){return this.client.event({...e,traceId:this.traceId,parentObservationId:this.observationId})}span(e){return this.client.span({...e,traceId:this.traceId,parentObservationId:this.observationId})}generation(e){return this.client.generation({...e,traceId:this.traceId,parentObservationId:this.observationId})}score(e){return this.client.score({...e,traceId:this.traceId,observationId:this.observationId}),this}getTraceUrl(){return`${this.client.baseUrl}/trace/${this.traceId}`}}class Me extends ce{constructor(e,t){super({client:e,id:t,traceId:t,observationId:null})}update(e){return this.client.trace({...e,id:this.id}),this}}class K extends ce{constructor(e,t,s){super({client:e,id:t,traceId:s,observationId:t})}}class Ge extends K{constructor(e,t,s){super(e,t,s)}update(e){return this.client._updateSpan({...e,id:this.id,traceId:this.traceId}),this}end(e){return this.client._updateSpan({...e,id:this.id,traceId:this.traceId,endTime:new Date}),this}}class Ne extends K{constructor(e,t,s){super(e,t,s)}update(e){return this.client._updateGeneration({...e,id:this.id,traceId:this.traceId}),this}end(e){return this.client._updateGeneration({...e,id:this.id,traceId:this.traceId,endTime:new Date}),this}}class Fe extends K{constructor(e,t,s){super(e,t,s)}}const ue={getItem(r){try{const e=r+"=",t=document.cookie.split(";");for(let s=0;s<t.length;s++){let n=t[s];for(;n.charAt(0)==" ";)n=n.substring(1,n.length);if(n.indexOf(e)===0)return decodeURIComponent(n.substring(e.length,n.length))}}catch{}return null},setItem(r,e){try{const o=r+"="+encodeURIComponent(e)+"; path=/";document.cookie=o}catch{return}},removeItem(r){try{ue.setItem(r,"")}catch{return}},clear(){document.cookie=""},getAllKeys(){const r=document.cookie.split(";"),e=[];for(let t=0;t<r.length;t++){let s=r[t];for(;s.charAt(0)==" ";)s=s.substring(1,s.length);e.push(s.split("=")[0])}return e}},W=r=>({getItem(e){return r.getItem(e)},setItem(e,t){r.setItem(e,t)},removeItem(e){r.removeItem(e)},clear(){r.clear()},getAllKeys(){const e=[];for(const t in localStorage)e.push(t);return e}}),X=(r,e="__mplssupport__")=>{if(!window)return!1;try{return r.setItem(e,"xyz"),r.getItem(e)!=="xyz"?!1:(r.removeItem(e),!0)}catch{return!1}};let N,L;const A=()=>{const r={};return{getItem(t){return r[t]},setItem(t,s){r[t]=s!==null?s:void 0},removeItem(t){delete r[t]},clear(){for(const t in r)delete r[t]},getAllKeys(){const t=[];for(const s in r)t.push(s);return t}}},q=(r,e)=>{if(typeof e!==void 0&&e){if(!localStorage){const t=W(e.localStorage);N=X(t)?t:void 0}if(!L){const t=W(e.sessionStorage);L=X(t)?t:void 0}}switch(r){case"cookie":return ue||N||L||A();case"localStorage":return N||L||A();case"sessionStorage":return L||A();case"memory":return A();default:return A()}};var d;(function(r){r.Json="application/json",r.FormData="multipart/form-data",r.UrlEncoded="application/x-www-form-urlencoded",r.Text="text/plain"})(d||(d={}));class Be{constructor(e={}){this.baseUrl="",this.securityData=null,this.abortControllers=new Map,this.customFetch=(...t)=>fetch(...t),this.baseApiParams={credentials:"same-origin",headers:{},redirect:"follow",referrerPolicy:"no-referrer"},this.setSecurityData=t=>{this.securityData=t},this.contentFormatters={[d.Json]:t=>t!==null&&(typeof t=="object"||typeof t=="string")?JSON.stringify(t):t,[d.Text]:t=>t!==null&&typeof t!="string"?JSON.stringify(t):t,[d.FormData]:t=>Object.keys(t||{}).reduce((s,n)=>{const o=t[n];return s.append(n,o instanceof Blob?o:typeof o=="object"&&o!==null?JSON.stringify(o):`${o}`),s},new FormData),[d.UrlEncoded]:t=>this.toQueryString(t)},this.createAbortSignal=t=>{if(this.abortControllers.has(t)){const n=this.abortControllers.get(t);return n?n.signal:void 0}const s=new AbortController;return this.abortControllers.set(t,s),s.signal},this.abortRequest=t=>{const s=this.abortControllers.get(t);s&&(s.abort(),this.abortControllers.delete(t))},this.request=async({body:t,secure:s,path:n,type:o,query:a,format:c,baseUrl:i,cancelToken:u,...h})=>{const l=(typeof s=="boolean"?s:this.baseApiParams.secure)&&this.securityWorker&&await this.securityWorker(this.securityData)||{},p=this.mergeRequestParams(h,l),m=a&&this.toQueryString(a),y=this.contentFormatters[o||d.Json],_=c||p.format;return this.customFetch(`${i||this.baseUrl||""}${n}${m?`?${m}`:""}`,{...p,headers:{...p.headers||{},...o&&o!==d.FormData?{"Content-Type":o}:{}},signal:(u?this.createAbortSignal(u):p.signal)||null,body:typeof t>"u"||t===null?null:y(t)}).then(async E=>{const f=E.clone();f.data=null,f.error=null;const R=_?await E[_]().then(T=>(f.ok?f.data=T:f.error=T,f)).catch(T=>(f.error=T,f)):f;if(u&&this.abortControllers.delete(u),!E.ok)throw R;return R.data})},Object.assign(this,e)}encodeQueryParam(e,t){return`${encodeURIComponent(e)}=${encodeURIComponent(typeof t=="number"?t:`${t}`)}`}addQueryParam(e,t){return this.encodeQueryParam(t,e[t])}addArrayQueryParam(e,t){return e[t].map(n=>this.encodeQueryParam(t,n)).join("&")}toQueryString(e){const t=e||{};return Object.keys(t).filter(n=>typeof t[n]<"u").map(n=>Array.isArray(t[n])?this.addArrayQueryParam(t,n):this.addQueryParam(t,n)).join("&")}addQueryParams(e){const t=this.toQueryString(e);return t?`?${t}`:""}mergeRequestParams(e,t){return{...this.baseApiParams,...e,...t||{},headers:{...this.baseApiParams.headers||{},...e.headers||{},...t&&t.headers||{}}}}}class Ke extends Be{constructor(){super(...arguments),this.api={annotationQueuesCreateQueueItem:(e,t,s={})=>this.request({path:`/api/public/annotation-queues/${e}/items`,method:"POST",body:t,secure:!0,type:d.Json,format:"json",...s}),annotationQueuesDeleteQueueItem:(e,t,s={})=>this.request({path:`/api/public/annotation-queues/${e}/items/${t}`,method:"DELETE",secure:!0,format:"json",...s}),annotationQueuesGetQueue:(e,t={})=>this.request({path:`/api/public/annotation-queues/${e}`,method:"GET",secure:!0,format:"json",...t}),annotationQueuesGetQueueItem:(e,t,s={})=>this.request({path:`/api/public/annotation-queues/${e}/items/${t}`,method:"GET",secure:!0,format:"json",...s}),annotationQueuesListQueueItems:({queueId:e,...t},s={})=>this.request({path:`/api/public/annotation-queues/${e}/items`,method:"GET",query:t,secure:!0,format:"json",...s}),annotationQueuesListQueues:(e,t={})=>this.request({path:"/api/public/annotation-queues",method:"GET",query:e,secure:!0,format:"json",...t}),annotationQueuesUpdateQueueItem:(e,t,s,n={})=>this.request({path:`/api/public/annotation-queues/${e}/items/${t}`,method:"PATCH",body:s,secure:!0,type:d.Json,format:"json",...n}),commentsCreate:(e,t={})=>this.request({path:"/api/public/comments",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),commentsGet:(e,t={})=>this.request({path:"/api/public/comments",method:"GET",query:e,secure:!0,format:"json",...t}),commentsGetById:(e,t={})=>this.request({path:`/api/public/comments/${e}`,method:"GET",secure:!0,format:"json",...t}),datasetItemsCreate:(e,t={})=>this.request({path:"/api/public/dataset-items",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),datasetItemsDelete:(e,t={})=>this.request({path:`/api/public/dataset-items/${e}`,method:"DELETE",secure:!0,format:"json",...t}),datasetItemsGet:(e,t={})=>this.request({path:`/api/public/dataset-items/${e}`,method:"GET",secure:!0,format:"json",...t}),datasetItemsList:(e,t={})=>this.request({path:"/api/public/dataset-items",method:"GET",query:e,secure:!0,format:"json",...t}),datasetRunItemsCreate:(e,t={})=>this.request({path:"/api/public/dataset-run-items",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),datasetRunItemsList:(e,t={})=>this.request({path:"/api/public/dataset-run-items",method:"GET",query:e,secure:!0,...t}),datasetsCreate:(e,t={})=>this.request({path:"/api/public/v2/datasets",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),datasetsDeleteRun:(e,t,s={})=>this.request({path:`/api/public/datasets/${e}/runs/${t}`,method:"DELETE",secure:!0,format:"json",...s}),datasetsGet:(e,t={})=>this.request({path:`/api/public/v2/datasets/${e}`,method:"GET",secure:!0,format:"json",...t}),datasetsGetRun:(e,t,s={})=>this.request({path:`/api/public/datasets/${e}/runs/${t}`,method:"GET",secure:!0,format:"json",...s}),datasetsGetRuns:({datasetName:e,...t},s={})=>this.request({path:`/api/public/datasets/${e}/runs`,method:"GET",query:t,secure:!0,format:"json",...s}),datasetsList:(e,t={})=>this.request({path:"/api/public/v2/datasets",method:"GET",query:e,secure:!0,format:"json",...t}),healthHealth:(e={})=>this.request({path:"/api/public/health",method:"GET",format:"json",...e}),ingestionBatch:(e,t={})=>this.request({path:"/api/public/ingestion",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),mediaGet:(e,t={})=>this.request({path:`/api/public/media/${e}`,method:"GET",secure:!0,format:"json",...t}),mediaGetUploadUrl:(e,t={})=>this.request({path:"/api/public/media",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),mediaPatch:(e,t,s={})=>this.request({path:`/api/public/media/${e}`,method:"PATCH",body:t,secure:!0,type:d.Json,...s}),metricsMetrics:(e,t={})=>this.request({path:"/api/public/metrics",method:"GET",query:e,secure:!0,format:"json",...t}),modelsCreate:(e,t={})=>this.request({path:"/api/public/models",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),modelsDelete:(e,t={})=>this.request({path:`/api/public/models/${e}`,method:"DELETE",secure:!0,...t}),modelsGet:(e,t={})=>this.request({path:`/api/public/models/${e}`,method:"GET",secure:!0,format:"json",...t}),modelsList:(e,t={})=>this.request({path:"/api/public/models",method:"GET",query:e,secure:!0,format:"json",...t}),observationsGet:(e,t={})=>this.request({path:`/api/public/observations/${e}`,method:"GET",secure:!0,format:"json",...t}),observationsGetMany:(e,t={})=>this.request({path:"/api/public/observations",method:"GET",query:e,secure:!0,format:"json",...t}),organizationsGetOrganizationMemberships:(e={})=>this.request({path:"/api/public/organizations/memberships",method:"GET",secure:!0,format:"json",...e}),organizationsGetOrganizationProjects:(e={})=>this.request({path:"/api/public/organizations/projects",method:"GET",secure:!0,format:"json",...e}),organizationsGetProjectMemberships:(e,t={})=>this.request({path:`/api/public/projects/${e}/memberships`,method:"GET",secure:!0,format:"json",...t}),organizationsUpdateOrganizationMembership:(e,t={})=>this.request({path:"/api/public/organizations/memberships",method:"PUT",body:e,secure:!0,type:d.Json,format:"json",...t}),organizationsUpdateProjectMembership:(e,t,s={})=>this.request({path:`/api/public/projects/${e}/memberships`,method:"PUT",body:t,secure:!0,type:d.Json,format:"json",...s}),projectsCreate:(e,t={})=>this.request({path:"/api/public/projects",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),projectsCreateApiKey:(e,t,s={})=>this.request({path:`/api/public/projects/${e}/apiKeys`,method:"POST",body:t,secure:!0,type:d.Json,format:"json",...s}),projectsDelete:(e,t={})=>this.request({path:`/api/public/projects/${e}`,method:"DELETE",secure:!0,format:"json",...t}),projectsDeleteApiKey:(e,t,s={})=>this.request({path:`/api/public/projects/${e}/apiKeys/${t}`,method:"DELETE",secure:!0,format:"json",...s}),projectsGet:(e={})=>this.request({path:"/api/public/projects",method:"GET",secure:!0,format:"json",...e}),projectsGetApiKeys:(e,t={})=>this.request({path:`/api/public/projects/${e}/apiKeys`,method:"GET",secure:!0,format:"json",...t}),projectsUpdate:(e,t,s={})=>this.request({path:`/api/public/projects/${e}`,method:"PUT",body:t,secure:!0,type:d.Json,format:"json",...s}),promptsCreate:(e,t={})=>this.request({path:"/api/public/v2/prompts",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),promptsGet:({promptName:e,...t},s={})=>this.request({path:`/api/public/v2/prompts/${e}`,method:"GET",query:t,secure:!0,format:"json",...s}),promptsList:(e,t={})=>this.request({path:"/api/public/v2/prompts",method:"GET",query:e,secure:!0,format:"json",...t}),promptVersionUpdate:(e,t,s,n={})=>this.request({path:`/api/public/v2/prompts/${e}/versions/${t}`,method:"PATCH",body:s,secure:!0,type:d.Json,format:"json",...n}),scimCreateUser:(e,t={})=>this.request({path:"/api/public/scim/Users",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),scimDeleteUser:(e,t={})=>this.request({path:`/api/public/scim/Users/${e}`,method:"DELETE",secure:!0,format:"json",...t}),scimGetResourceTypes:(e={})=>this.request({path:"/api/public/scim/ResourceTypes",method:"GET",secure:!0,format:"json",...e}),scimGetSchemas:(e={})=>this.request({path:"/api/public/scim/Schemas",method:"GET",secure:!0,format:"json",...e}),scimGetServiceProviderConfig:(e={})=>this.request({path:"/api/public/scim/ServiceProviderConfig",method:"GET",secure:!0,format:"json",...e}),scimGetUser:(e,t={})=>this.request({path:`/api/public/scim/Users/${e}`,method:"GET",secure:!0,format:"json",...t}),scimListUsers:(e,t={})=>this.request({path:"/api/public/scim/Users",method:"GET",query:e,secure:!0,format:"json",...t}),scoreConfigsCreate:(e,t={})=>this.request({path:"/api/public/score-configs",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),scoreConfigsGet:(e,t={})=>this.request({path:"/api/public/score-configs",method:"GET",query:e,secure:!0,format:"json",...t}),scoreConfigsGetById:(e,t={})=>this.request({path:`/api/public/score-configs/${e}`,method:"GET",secure:!0,format:"json",...t}),scoreCreate:(e,t={})=>this.request({path:"/api/public/scores",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),scoreDelete:(e,t={})=>this.request({path:`/api/public/scores/${e}`,method:"DELETE",secure:!0,...t}),scoreV2Get:(e,t={})=>this.request({path:"/api/public/v2/scores",method:"GET",query:e,secure:!0,format:"json",...t}),scoreV2GetById:(e,t={})=>this.request({path:`/api/public/v2/scores/${e}`,method:"GET",secure:!0,format:"json",...t}),sessionsGet:(e,t={})=>this.request({path:`/api/public/sessions/${e}`,method:"GET",secure:!0,format:"json",...t}),sessionsList:(e,t={})=>this.request({path:"/api/public/sessions",method:"GET",query:e,secure:!0,format:"json",...t}),traceDelete:(e,t={})=>this.request({path:`/api/public/traces/${e}`,method:"DELETE",secure:!0,format:"json",...t}),traceDeleteMultiple:(e,t={})=>this.request({path:"/api/public/traces",method:"DELETE",body:e,secure:!0,type:d.Json,format:"json",...t}),traceGet:(e,t={})=>this.request({path:`/api/public/traces/${e}`,method:"GET",secure:!0,format:"json",...t}),traceList:(e,t={})=>this.request({path:"/api/public/traces",method:"GET",query:e,secure:!0,format:"json",...t})}}}var le="3.38.6";class Je extends ke{constructor(e){const t=ne.configLangfuseSDK(e);super(t),typeof window<"u"&&!("Deno"in window)?(this._storageKey=e?.persistence_name?`lf_${e.persistence_name}`:`lf_${t.publicKey}_langfuse`,this._storage=q(e?.persistence||"localStorage",window)):(this._storageKey=`lf_${t.publicKey}_langfuse`,this._storage=q("memory",void 0)),this.api=new Ke({baseUrl:this.baseUrl,baseApiParams:{headers:{"X-Langfuse-Sdk-Name":"langfuse-js","X-Langfuse-Sdk-Version":this.getLibraryVersion(),"X-Langfuse-Sdk-Variant":this.getLibraryId(),"X-Langfuse-Sdk-Integration":this.sdkIntegration,"X-Langfuse-Public-Key":this.publicKey,...this.additionalHeaders,...this.constructAuthorizationHeader(this.publicKey,this.secretKey)}}}).api}getPersistedProperty(e){return this._storageCache||(this._storageCache=JSON.parse(this._storage.getItem(this._storageKey)||"{}")||{}),this._storageCache[e]}setPersistedProperty(e,t){this._storageCache||(this._storageCache=JSON.parse(this._storage.getItem(this._storageKey)||"{}")||{}),t===null?delete this._storageCache[e]:this._storageCache[e]=t,this._storage.setItem(this._storageKey,JSON.stringify(this._storageCache))}fetch(e,t){return fetch(e,t)}getLibraryId(){return"langfuse"}getLibraryVersion(){return le}getCustomUserAgent(){}}class ot extends qe{constructor(e){const t=ne.configLangfuseSDK(e,!1);super(t),typeof window<"u"?(this._storageKey=e?.persistence_name?`lf_${e.persistence_name}`:`lf_${t.publicKey}_langfuse`,this._storage=q(e?.persistence||"localStorage",window)):(this._storageKey=`lf_${t.publicKey}_langfuse`,this._storage=q("memory",void 0))}getPersistedProperty(e){return this._storageCache||(this._storageCache=JSON.parse(this._storage.getItem(this._storageKey)||"{}")||{}),this._storageCache[e]}setPersistedProperty(e,t){this._storageCache||(this._storageCache=JSON.parse(this._storage.getItem(this._storageKey)||"{}")||{}),t===null?delete this._storageCache[e]:this._storageCache[e]=t,this._storage.setItem(this._storageKey,JSON.stringify(this._storageCache))}fetch(e,t){return fetch(e,t)}getLibraryId(){return"langfuse-frontend"}getLibraryVersion(){return le}getCustomUserAgent(){}}class S{static getInstance(e){return S.instance||(S.instance=new Je(e)),S.instance}}S.instance=null;const ze=r=>{let e={};e={frequency_penalty:r.frequency_penalty,logit_bias:r.logit_bias,logprobs:r.logprobs,max_tokens:r.max_tokens,n:r.n,presence_penalty:r.presence_penalty,seed:r.seed,stop:r.stop,stream:r.stream,temperature:r.temperature,top_p:r.top_p,user:r.user,response_format:r.response_format,top_logprobs:r.top_logprobs};let t=r.input;return r&&typeof r=="object"&&!Array.isArray(r)&&"messages"in r?(t={},t.messages=r.messages,"function_call"in r&&(t.function_call=r.function_call),"functions"in r&&(t.functions=r.functions),"tools"in r&&(t.tools=r.tools),"tool_choice"in r&&(t.tool_choice=r.tool_choice)):t||(t=r.prompt),{model:r.model,input:t,modelParameters:e}},he=r=>{if(r instanceof Object&&"output_text"in r&&r.output_text!=="")return r.output_text;if(typeof r=="object"&&r&&"output"in r&&Array.isArray(r.output)){const e=r.output;return e.length>1?e:e.length===1?e[0]:null}return r instanceof Object&&"choices"in r&&Array.isArray(r.choices)?"message"in r.choices[0]?r.choices[0].message:r.choices[0].text??"":""},He=r=>{if(me(r)){const{prompt_tokens:e,completion_tokens:t,total_tokens:s}=r.usage;return{input:e,output:t,total:s}}},pe=r=>{if("prompt_tokens"in r){const{prompt_tokens:e,completion_tokens:t,total_tokens:s,completion_tokens_details:n,prompt_tokens_details:o}=r;return{input:e,output:t,total:s,...Object.fromEntries(Object.entries(o??{}).map(([a,c])=>[`input_${a}`,c])),...Object.fromEntries(Object.entries(n??{}).map(([a,c])=>[`output_${a}`,c]))}}else if("input_tokens"in r){const{input_tokens:e,output_tokens:t,total_tokens:s,input_tokens_details:n,output_tokens_details:o}=r;return{input:e,output:t,total:s,...Object.fromEntries(Object.entries(n??{}).map(([a,c])=>[`input_${a}`,c])),...Object.fromEntries(Object.entries(o??{}).map(([a,c])=>[`output_${a}`,c]))}}},de=r=>{if(me(r))return pe(r.usage)},Qe=r=>{let e=!1;const s=r?.choices?.[0];try{if("delta"in s&&"tool_calls"in s.delta&&Array.isArray(s.delta.tool_calls))return e=!0,{isToolCall:e,data:s.delta.tool_calls[0]};if("delta"in s)return{isToolCall:e,data:s.delta?.content||""};if("text"in s)return{isToolCall:e,data:s.text||""}}catch{}return{isToolCall:!1,data:""}};function me(r){return r instanceof Object&&"usage"in r&&r.usage instanceof Object&&(typeof r.usage.prompt_tokens=="number"&&typeof r.usage.completion_tokens=="number"&&typeof r.usage.total_tokens=="number"||typeof r.usage.input_tokens=="number"&&typeof r.usage.output_tokens=="number"&&typeof r.usage.total_tokens=="number")}const Ve=r=>{let e="",t="";for(const s of r)e=s.function?.name||e,t+=s.function?.arguments||"";return{tool_calls:[{function:{name:e,arguments:t}}]}},fe=r=>{if(typeof r!="object"||r===null)return{model:void 0,modelParameters:void 0,metadata:void 0};const e="model"in r?r.model:void 0,t={},s=["max_output_tokens","parallel_tool_calls","store","temperature","tool_choice","top_p","truncation","user"],n={},o=["reasoning","incomplete_details","instructions","previous_response_id","tools","metadata","status","error"];for(const a of s){const c=a in r?r[a]:null;c!=null&&(t[a]=c)}for(const a of o){const c=a in r?r[a]:null;c&&(n[a]=c)}return{model:e,modelParameters:Object.keys(t).length>0?t:void 0,metadata:Object.keys(n).length>0?n:void 0}},Y=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",We=(r,e)=>(...t)=>Xe(r,e,...t),Xe=(r,e,...t)=>{const{model:s,input:n,modelParameters:o}=ze(t[0]??{}),a={...o,response_format:null},c={...e?.metadata,response_format:"response_format"in o?o.response_format:void 0};let i={model:s,input:n,modelParameters:a,name:e?.generationName,startTime:new Date,promptName:e?.langfusePrompt?.name,promptVersion:e?.langfusePrompt?.version,metadata:c},u;const h=e&&"parent"in e;h?(u=e.parent,i={...{...e,parent:void 0},...i,promptName:e?.promptName??e?.langfusePrompt?.name,promptVersion:e?.promptVersion??e?.langfusePrompt?.version}):u=S.getInstance(e?.clientInitParams).trace({...e,...i,id:e?.traceId,name:e?.traceName,timestamp:i.startTime});try{const l=r(...t);return Y(l)?Z(l,u,h,i):l instanceof Promise?l.then(m=>{if(Y(m))return Z(m,u,h,i);const y=he(m),_=He(m),E=de(m),{model:f,modelParameters:R,metadata:T}=fe(m);return u.generation({...i,output:y,endTime:new Date,usage:_,usageDetails:E,model:f||i.model,modelParameters:{...i.modelParameters,...R},metadata:{...i.metadata,...T}}),h||u.update({output:y}),m}).catch(m=>{throw u.generation({...i,endTime:new Date,statusMessage:String(m),level:"ERROR",usage:{inputCost:0,outputCost:0,totalCost:0},costDetails:{input:0,output:0,total:0}}),m}):l}catch(l){throw u.generation({...i,endTime:new Date,statusMessage:String(l),level:"ERROR",usage:{inputCost:0,outputCost:0,totalCost:0},costDetails:{input:0,output:0,total:0}}),l}};function Z(r,e,t,s){async function*n(){const o=r,a=[],c=[];let i=null,u=null,h,l=null;for await(const p of o){if(i=i??new Date,typeof p=="object"&&p&&"response"in p){const y=p.response;l=he(y),h=de(y);const{model:_,modelParameters:E,metadata:f}=fe(y);s.model=_??s.model,s.modelParameters={...s.modelParameters,...E},s.metadata={...s.metadata,...f}}typeof p=="object"&&p!=null&&"usage"in p&&(u=p.usage);const m=Qe(p);m.isToolCall?c.push(m.data):a.push(m.data),yield p}l=l??(c.length>0?Ve(c):a.join("")),e.generation({...s,output:l,endTime:new Date,completionStartTime:i,usage:u?{input:"prompt_tokens"in u?u.prompt_tokens:void 0,output:"completion_tokens"in u?u.completion_tokens:void 0,total:"total_tokens"in u?u.total_tokens:void 0}:void 0,usageDetails:h??(u?pe(u):void 0)}),t||e.update({output:l})}return n()}const Ye=(r,e)=>new Proxy(r,{get(t,s,n){const o=t[s],a=`${r.constructor?.name}.${s.toString()}`,c=e?.generationName??a,i=e&&"traceName"in e?e.traceName:c,u={...e,generationName:c,traceName:i};if(s==="flushAsync"){let l;return e&&"parent"in e?l=e.parent.client:l=S.getInstance(),l.flushAsync.bind(l)}if(s==="shutdownAsync"){let l;return e&&"parent"in e?l=e.parent.client:l=S.getInstance(),l.shutdownAsync.bind(l)}return typeof o=="function"?We(o.bind(t),u):o&&!Array.isArray(o)&&!(o instanceof Date)&&typeof o=="object"?Ye(o,u):Reflect.get(t,s,n)}});export{Je as Langfuse,v as LangfuseMedia,ot as LangfuseWeb,Je as default,Ye as observeOpenAI};
@@ -1,4 +1,4 @@
1
- import{Langfuse as T}from"./index-B4dcyhl1.js";import{B as I,a as v,A as g,b as y,H as M,C as S,S as w,F as D,T as b}from"./langfuse-C4HKZ3NL-1laIPiUg.js";import"./index-CKNaXAjV.js";import"./chunk-VL2OQCWN-BFKzE0YG.js";import"./index-DRz5BQNA.js";import"./__vite-browser-external-DFygW7-s.js";import"./path-C9FudP8b.js";const u="langsmith:hidden";class k extends I{constructor(t){super(),this.name="CallbackHandler",this.rootProvided=!1,this.updateRoot=!1,this.debugEnabled=!1,this.completionStartTimes={},t&&"root"in t?(this.langfuse=t.root.client,this.rootObservationId=t.root.observationId??void 0,this.traceId=t.root.traceId,this.rootProvided=!0,this.updateRoot=t.updateRoot??!1,this.metadata=t.metadata):(this.langfuse=new T({...t,persistence:"memory",sdkIntegration:t?.sdkIntegration??"LANGCHAIN"}),this.sessionId=t?.sessionId,this.userId=t?.userId,this.metadata=t?.metadata,this.tags=t?.tags),this.version=t?.version,this.promptToParentRunMap=new Map,this.traceUpdates=new Map}async flushAsync(){return this.langfuse.flushAsync()}async shutdownAsync(){return this.langfuse.shutdownAsync()}debug(t=!0){this.langfuse.debug(t),this.debugEnabled=t}_log(t){this.debugEnabled&&console.log(t)}async handleNewToken(t,e){return e&&!(e in this.completionStartTimes)&&(this._log(`LLM first streaming token: ${e}`),this.completionStartTimes[e]=new Date),Promise.resolve()}async handleLLMNewToken(t,e,s,i,n,a){return s&&!(s in this.completionStartTimes)&&(this._log(`LLM first streaming token: ${s}`),this.completionStartTimes[s]=new Date),Promise.resolve()}getTraceId(){return this.traceId}getTraceUrl(){return this.traceId?`${this.langfuse.baseUrl}/trace/${this.traceId}`:void 0}getLangchainRunId(){return this.topLevelObservationId}async handleRetrieverError(t,e,s){try{this._log(`Retriever error: ${t} with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,level:"ERROR",statusMessage:t.toString(),endTime:new Date,version:this.version}),this.updateTrace(e,s,t.toString())}catch(i){this._log(i)}}async handleChainStart(t,e,s,i,n,a,o,h){try{this._log(`Chain start with Id: ${s}`);const d=h??t.id.at(-1)?.toString()??"Langchain Run";this.registerLangfusePrompt(i,a);let r=e;typeof e=="object"&&"input"in e&&Array.isArray(e.input)&&e.input.every(l=>l instanceof v)?r=e.input.map(l=>this.extractChatMessageContent(l)):typeof e=="object"&&"content"in e&&typeof e.content=="string"&&(r=e.content),this.generateTrace(d,s,i,n,a,r),this.langfuse.span({id:s,traceId:this.traceId,parentObservationId:i??this.rootObservationId,name:d,metadata:this.joinTagsAndMetaData(n,a),input:r,version:this.version,level:n&&n.includes(u)?"DEBUG":void 0}),i||this.traceUpdates.set(s,{tags:n,userId:a&&"langfuseUserId"in a&&typeof a.langfuseUserId=="string"?a.langfuseUserId:void 0,sessionId:a&&"langfuseSessionId"in a&&typeof a.langfuseSessionId=="string"?a.langfuseSessionId:void 0})}catch(d){this._log(d)}}registerLangfusePrompt(t,e){e&&"langfusePrompt"in e&&t&&this.promptToParentRunMap.set(t,e.langfusePrompt)}deregisterLangfusePrompt(t){this.promptToParentRunMap.delete(t)}async handleAgentAction(t,e,s){try{this._log(`Agent action with ID: ${e}`),this.langfuse.span({id:e,parentObservationId:s,traceId:this.traceId,endTime:new Date,input:t,version:this.version})}catch(i){this._log(i)}}async handleAgentEnd(t,e,s){try{this._log(`Agent finish with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,endTime:new Date,output:t,version:this.version}),this.updateTrace(e,s,t)}catch(i){this._log(i)}}async handleChainError(t,e,s){try{this._log(`Chain error: ${t} with ID: ${e}`);const i=this.parseAzureRefusalError(t);this.langfuse._updateSpan({id:e,traceId:this.traceId,level:"ERROR",statusMessage:t.toString()+i,endTime:new Date,version:this.version}),this.updateTrace(e,s,t.toString()+i)}catch(i){this._log(i)}}generateTrace(t,e,s,i,n,a){this.traceId&&!s&&!this.rootProvided&&(this.traceId=void 0,this.topLevelObservationId=void 0);const o={name:t,metadata:this.joinTagsAndMetaData(i,n,this.metadata),userId:this.userId,version:this.version,sessionId:this.sessionId,input:a,tags:this.tags};this.traceId||(this.langfuse.trace({id:e,...o}),this.traceId=e),this.rootProvided&&this.updateRoot&&(this.rootObservationId?this.langfuse._updateSpan({id:this.rootObservationId,traceId:this.traceId,...o}):this.langfuse.trace({id:this.traceId,...o})),this.topLevelObservationId=s?this.topLevelObservationId:e}async handleGenerationStart(t,e,s,i,n,a,o,h){this._log(`Generation start with ID: ${s}`);const d=h??t.id.at(-1)?.toString()??"Langchain Generation";this.generateTrace(d,s,i,a,o,e);const r={},l=n?.invocation_params;for(const[f,c]of Object.entries({temperature:l?.temperature,max_tokens:l?.max_tokens,top_p:l?.top_p,frequency_penalty:l?.frequency_penalty,presence_penalty:l?.presence_penalty,request_timeout:l?.request_timeout}))c!=null&&(r[f]=c);let _;if(n){const f=n.invocation_params.model,c=o&&"ls_model_name"in o?o.ls_model_name:void 0;_=f??c}const m=this.promptToParentRunMap.get(i??"root");m&&i&&this.deregisterLangfusePrompt(i),this.langfuse.generation({id:s,traceId:this.traceId,name:h??t.id.at(-1)?.toString(),metadata:this.joinTagsAndMetaData(a,o),parentObservationId:i??this.rootObservationId,input:e,model:_,modelParameters:r,version:this.version,prompt:m,level:a&&a.includes(u)?"DEBUG":void 0})}async handleChatModelStart(t,e,s,i,n,a,o,h){try{this._log(`Chat model start with ID: ${s}`);const d=e.flatMap(r=>r.map(l=>this.extractChatMessageContent(l)));this.handleGenerationStart(t,d,s,i,n,a,o,h)}catch(d){this._log(d)}}async handleChainEnd(t,e,s){try{this._log(`Chain end with ID: ${e}`);let i=t;typeof t=="object"&&"output"in t&&typeof t.output=="string"&&(i=t.output),this.langfuse._updateSpan({id:e,traceId:this.traceId,output:i,endTime:new Date,version:this.version}),this.updateTrace(e,s,i),this.deregisterLangfusePrompt(e)}catch(i){this._log(i)}}async handleLLMStart(t,e,s,i,n,a,o,h){try{this._log(`LLM start with ID: ${s}`),this.handleGenerationStart(t,e,s,i,n,a,o,h)}catch(d){this._log(d)}}async handleToolStart(t,e,s,i,n,a,o){try{this._log(`Tool start with ID: ${s}`),this.langfuse.span({id:s,parentObservationId:i,traceId:this.traceId,name:o??t.id.at(-1)?.toString(),input:e,metadata:this.joinTagsAndMetaData(n,a),version:this.version,level:n&&n.includes(u)?"DEBUG":void 0})}catch(h){this._log(h)}}async handleRetrieverStart(t,e,s,i,n,a,o){try{this._log(`Retriever start with ID: ${s}`),this.langfuse.span({id:s,parentObservationId:i,traceId:this.traceId,name:o??t.id.at(-1)?.toString(),input:e,metadata:this.joinTagsAndMetaData(n,a),version:this.version,level:n&&n.includes(u)?"DEBUG":void 0})}catch(h){this._log(h)}}async handleRetrieverEnd(t,e,s){try{this._log(`Retriever end with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,output:t,endTime:new Date,version:this.version}),this.updateTrace(e,s,t)}catch(i){this._log(i)}}async handleToolEnd(t,e,s){try{this._log(`Tool end with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,output:t,endTime:new Date,version:this.version}),this.updateTrace(e,s,t)}catch(i){this._log(i)}}async handleToolError(t,e,s){try{this._log(`Tool error ${t} with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,level:"ERROR",statusMessage:t.toString(),endTime:new Date,version:this.version}),this.updateTrace(e,s,t.toString())}catch(i){this._log(i)}}async handleLLMEnd(t,e,s){try{this._log(`LLM end with ID: ${e}`);const i=t.generations[t.generations.length-1][t.generations[t.generations.length-1].length-1],n=this.extractUsageMetadata(i)??t.llmOutput?.tokenUsage,a=this.extractModelNameFromMetadata(i),o={input:n?.input_tokens??("promptTokens"in n?n?.promptTokens:void 0),output:n?.output_tokens??("completionTokens"in n?n?.completionTokens:void 0),total:n?.total_tokens??("totalTokens"in n?n?.totalTokens:void 0)};if(n&&"input_token_details"in n)for(const[d,r]of Object.entries(n.input_token_details??{}))o[`input_${d}`]=r,"input"in o&&typeof r=="number"&&(o.input=Math.max(0,o.input-r));if(n&&"output_token_details"in n)for(const[d,r]of Object.entries(n.output_token_details??{}))o[`output_${d}`]=r,"output"in o&&typeof r=="number"&&(o.output=Math.max(0,o.output-r));const h="message"in i&&i.message instanceof v?this.extractChatMessageContent(i.message):i.text;this.langfuse._updateGeneration({id:e,model:a,traceId:this.traceId,output:h,endTime:new Date,completionStartTime:e in this.completionStartTimes?this.completionStartTimes[e]:void 0,usage:o,usageDetails:o,version:this.version}),e in this.completionStartTimes&&delete this.completionStartTimes[e],this.updateTrace(e,s,h)}catch(i){this._log(i)}}extractUsageMetadata(t){try{return"message"in t&&(t.message instanceof g||t.message instanceof y)?t.message.usage_metadata:void 0}catch(e){this._log(`Error extracting usage metadata: ${e}`);return}}extractModelNameFromMetadata(t){try{return"message"in t&&(t.message instanceof g||t.message instanceof y)?t.message.response_metadata.model_name:void 0}catch{}}extractChatMessageContent(t){let e;return t instanceof M?e={content:t.content,role:"user"}:t instanceof S?e={content:t.content,role:t.role}:t instanceof g?e={content:t.content,role:"assistant"}:t instanceof w?e={content:t.content,role:"system"}:t instanceof D?e={content:t.content,additional_kwargs:t.additional_kwargs,role:t.name}:t instanceof b?e={content:t.content,additional_kwargs:t.additional_kwargs,role:t.name}:t.name?e={role:t.name,content:t.content}:e={content:t.content},t.additional_kwargs.function_call||t.additional_kwargs.tool_calls?{...e,additional_kwargs:t.additional_kwargs}:e}async handleLLMError(t,e,s){try{this._log(`LLM error ${t} with ID: ${e}`);const i=this.parseAzureRefusalError(t);this.langfuse._updateGeneration({id:e,traceId:this.traceId,level:"ERROR",statusMessage:t.toString()+i,endTime:new Date,version:this.version}),this.updateTrace(e,s,t.toString()+i)}catch(i){this._log(i)}}parseAzureRefusalError(t){let e="";if(typeof t=="object"&&"error"in t)try{e=`
1
+ import{Langfuse as T}from"./index-DhJ0wa09.js";import{B as I,a as v,A as g,b as y,H as M,C as S,S as w,F as D,T as b}from"./langfuse-C4HKZ3NL-CsiDw8Wb.js";import"./index-CFpQGWTL.js";import"./chunk-VL2OQCWN-lvFdpsKs.js";import"./index-DRz5BQNA.js";import"./__vite-browser-external-DFygW7-s.js";import"./path-C9FudP8b.js";const u="langsmith:hidden";class k extends I{constructor(t){super(),this.name="CallbackHandler",this.rootProvided=!1,this.updateRoot=!1,this.debugEnabled=!1,this.completionStartTimes={},t&&"root"in t?(this.langfuse=t.root.client,this.rootObservationId=t.root.observationId??void 0,this.traceId=t.root.traceId,this.rootProvided=!0,this.updateRoot=t.updateRoot??!1,this.metadata=t.metadata):(this.langfuse=new T({...t,persistence:"memory",sdkIntegration:t?.sdkIntegration??"LANGCHAIN"}),this.sessionId=t?.sessionId,this.userId=t?.userId,this.metadata=t?.metadata,this.tags=t?.tags),this.version=t?.version,this.promptToParentRunMap=new Map,this.traceUpdates=new Map}async flushAsync(){return this.langfuse.flushAsync()}async shutdownAsync(){return this.langfuse.shutdownAsync()}debug(t=!0){this.langfuse.debug(t),this.debugEnabled=t}_log(t){this.debugEnabled&&console.log(t)}async handleNewToken(t,e){return e&&!(e in this.completionStartTimes)&&(this._log(`LLM first streaming token: ${e}`),this.completionStartTimes[e]=new Date),Promise.resolve()}async handleLLMNewToken(t,e,s,i,n,a){return s&&!(s in this.completionStartTimes)&&(this._log(`LLM first streaming token: ${s}`),this.completionStartTimes[s]=new Date),Promise.resolve()}getTraceId(){return this.traceId}getTraceUrl(){return this.traceId?`${this.langfuse.baseUrl}/trace/${this.traceId}`:void 0}getLangchainRunId(){return this.topLevelObservationId}async handleRetrieverError(t,e,s){try{this._log(`Retriever error: ${t} with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,level:"ERROR",statusMessage:t.toString(),endTime:new Date,version:this.version}),this.updateTrace(e,s,t.toString())}catch(i){this._log(i)}}async handleChainStart(t,e,s,i,n,a,o,h){try{this._log(`Chain start with Id: ${s}`);const d=h??t.id.at(-1)?.toString()??"Langchain Run";this.registerLangfusePrompt(i,a);let r=e;typeof e=="object"&&"input"in e&&Array.isArray(e.input)&&e.input.every(l=>l instanceof v)?r=e.input.map(l=>this.extractChatMessageContent(l)):typeof e=="object"&&"content"in e&&typeof e.content=="string"&&(r=e.content),this.generateTrace(d,s,i,n,a,r),this.langfuse.span({id:s,traceId:this.traceId,parentObservationId:i??this.rootObservationId,name:d,metadata:this.joinTagsAndMetaData(n,a),input:r,version:this.version,level:n&&n.includes(u)?"DEBUG":void 0}),i||this.traceUpdates.set(s,{tags:n,userId:a&&"langfuseUserId"in a&&typeof a.langfuseUserId=="string"?a.langfuseUserId:void 0,sessionId:a&&"langfuseSessionId"in a&&typeof a.langfuseSessionId=="string"?a.langfuseSessionId:void 0})}catch(d){this._log(d)}}registerLangfusePrompt(t,e){e&&"langfusePrompt"in e&&t&&this.promptToParentRunMap.set(t,e.langfusePrompt)}deregisterLangfusePrompt(t){this.promptToParentRunMap.delete(t)}async handleAgentAction(t,e,s){try{this._log(`Agent action with ID: ${e}`),this.langfuse.span({id:e,parentObservationId:s,traceId:this.traceId,endTime:new Date,input:t,version:this.version})}catch(i){this._log(i)}}async handleAgentEnd(t,e,s){try{this._log(`Agent finish with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,endTime:new Date,output:t,version:this.version}),this.updateTrace(e,s,t)}catch(i){this._log(i)}}async handleChainError(t,e,s){try{this._log(`Chain error: ${t} with ID: ${e}`);const i=this.parseAzureRefusalError(t);this.langfuse._updateSpan({id:e,traceId:this.traceId,level:"ERROR",statusMessage:t.toString()+i,endTime:new Date,version:this.version}),this.updateTrace(e,s,t.toString()+i)}catch(i){this._log(i)}}generateTrace(t,e,s,i,n,a){this.traceId&&!s&&!this.rootProvided&&(this.traceId=void 0,this.topLevelObservationId=void 0);const o={name:t,metadata:this.joinTagsAndMetaData(i,n,this.metadata),userId:this.userId,version:this.version,sessionId:this.sessionId,input:a,tags:this.tags};this.traceId||(this.langfuse.trace({id:e,...o}),this.traceId=e),this.rootProvided&&this.updateRoot&&(this.rootObservationId?this.langfuse._updateSpan({id:this.rootObservationId,traceId:this.traceId,...o}):this.langfuse.trace({id:this.traceId,...o})),this.topLevelObservationId=s?this.topLevelObservationId:e}async handleGenerationStart(t,e,s,i,n,a,o,h){this._log(`Generation start with ID: ${s}`);const d=h??t.id.at(-1)?.toString()??"Langchain Generation";this.generateTrace(d,s,i,a,o,e);const r={},l=n?.invocation_params;for(const[f,c]of Object.entries({temperature:l?.temperature,max_tokens:l?.max_tokens,top_p:l?.top_p,frequency_penalty:l?.frequency_penalty,presence_penalty:l?.presence_penalty,request_timeout:l?.request_timeout}))c!=null&&(r[f]=c);let _;if(n){const f=n.invocation_params.model,c=o&&"ls_model_name"in o?o.ls_model_name:void 0;_=f??c}const m=this.promptToParentRunMap.get(i??"root");m&&i&&this.deregisterLangfusePrompt(i),this.langfuse.generation({id:s,traceId:this.traceId,name:h??t.id.at(-1)?.toString(),metadata:this.joinTagsAndMetaData(a,o),parentObservationId:i??this.rootObservationId,input:e,model:_,modelParameters:r,version:this.version,prompt:m,level:a&&a.includes(u)?"DEBUG":void 0})}async handleChatModelStart(t,e,s,i,n,a,o,h){try{this._log(`Chat model start with ID: ${s}`);const d=e.flatMap(r=>r.map(l=>this.extractChatMessageContent(l)));this.handleGenerationStart(t,d,s,i,n,a,o,h)}catch(d){this._log(d)}}async handleChainEnd(t,e,s){try{this._log(`Chain end with ID: ${e}`);let i=t;typeof t=="object"&&"output"in t&&typeof t.output=="string"&&(i=t.output),this.langfuse._updateSpan({id:e,traceId:this.traceId,output:i,endTime:new Date,version:this.version}),this.updateTrace(e,s,i),this.deregisterLangfusePrompt(e)}catch(i){this._log(i)}}async handleLLMStart(t,e,s,i,n,a,o,h){try{this._log(`LLM start with ID: ${s}`),this.handleGenerationStart(t,e,s,i,n,a,o,h)}catch(d){this._log(d)}}async handleToolStart(t,e,s,i,n,a,o){try{this._log(`Tool start with ID: ${s}`),this.langfuse.span({id:s,parentObservationId:i,traceId:this.traceId,name:o??t.id.at(-1)?.toString(),input:e,metadata:this.joinTagsAndMetaData(n,a),version:this.version,level:n&&n.includes(u)?"DEBUG":void 0})}catch(h){this._log(h)}}async handleRetrieverStart(t,e,s,i,n,a,o){try{this._log(`Retriever start with ID: ${s}`),this.langfuse.span({id:s,parentObservationId:i,traceId:this.traceId,name:o??t.id.at(-1)?.toString(),input:e,metadata:this.joinTagsAndMetaData(n,a),version:this.version,level:n&&n.includes(u)?"DEBUG":void 0})}catch(h){this._log(h)}}async handleRetrieverEnd(t,e,s){try{this._log(`Retriever end with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,output:t,endTime:new Date,version:this.version}),this.updateTrace(e,s,t)}catch(i){this._log(i)}}async handleToolEnd(t,e,s){try{this._log(`Tool end with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,output:t,endTime:new Date,version:this.version}),this.updateTrace(e,s,t)}catch(i){this._log(i)}}async handleToolError(t,e,s){try{this._log(`Tool error ${t} with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,level:"ERROR",statusMessage:t.toString(),endTime:new Date,version:this.version}),this.updateTrace(e,s,t.toString())}catch(i){this._log(i)}}async handleLLMEnd(t,e,s){try{this._log(`LLM end with ID: ${e}`);const i=t.generations[t.generations.length-1][t.generations[t.generations.length-1].length-1],n=this.extractUsageMetadata(i)??t.llmOutput?.tokenUsage,a=this.extractModelNameFromMetadata(i),o={input:n?.input_tokens??("promptTokens"in n?n?.promptTokens:void 0),output:n?.output_tokens??("completionTokens"in n?n?.completionTokens:void 0),total:n?.total_tokens??("totalTokens"in n?n?.totalTokens:void 0)};if(n&&"input_token_details"in n)for(const[d,r]of Object.entries(n.input_token_details??{}))o[`input_${d}`]=r,"input"in o&&typeof r=="number"&&(o.input=Math.max(0,o.input-r));if(n&&"output_token_details"in n)for(const[d,r]of Object.entries(n.output_token_details??{}))o[`output_${d}`]=r,"output"in o&&typeof r=="number"&&(o.output=Math.max(0,o.output-r));const h="message"in i&&i.message instanceof v?this.extractChatMessageContent(i.message):i.text;this.langfuse._updateGeneration({id:e,model:a,traceId:this.traceId,output:h,endTime:new Date,completionStartTime:e in this.completionStartTimes?this.completionStartTimes[e]:void 0,usage:o,usageDetails:o,version:this.version}),e in this.completionStartTimes&&delete this.completionStartTimes[e],this.updateTrace(e,s,h)}catch(i){this._log(i)}}extractUsageMetadata(t){try{return"message"in t&&(t.message instanceof g||t.message instanceof y)?t.message.usage_metadata:void 0}catch(e){this._log(`Error extracting usage metadata: ${e}`);return}}extractModelNameFromMetadata(t){try{return"message"in t&&(t.message instanceof g||t.message instanceof y)?t.message.response_metadata.model_name:void 0}catch{}}extractChatMessageContent(t){let e;return t instanceof M?e={content:t.content,role:"user"}:t instanceof S?e={content:t.content,role:t.role}:t instanceof g?e={content:t.content,role:"assistant"}:t instanceof w?e={content:t.content,role:"system"}:t instanceof D?e={content:t.content,additional_kwargs:t.additional_kwargs,role:t.name}:t instanceof b?e={content:t.content,additional_kwargs:t.additional_kwargs,role:t.name}:t.name?e={role:t.name,content:t.content}:e={content:t.content},t.additional_kwargs.function_call||t.additional_kwargs.tool_calls?{...e,additional_kwargs:t.additional_kwargs}:e}async handleLLMError(t,e,s){try{this._log(`LLM error ${t} with ID: ${e}`);const i=this.parseAzureRefusalError(t);this.langfuse._updateGeneration({id:e,traceId:this.traceId,level:"ERROR",statusMessage:t.toString()+i,endTime:new Date,version:this.version}),this.updateTrace(e,s,t.toString()+i)}catch(i){this._log(i)}}parseAzureRefusalError(t){let e="";if(typeof t=="object"&&"error"in t)try{e=`
2
2
 
3
3
  Error details:
4
4
  `+JSON.stringify(t.error,null,2)}catch{}return e}updateTrace(t,e,s){const i=this.traceUpdates.get(t);this.traceUpdates.delete(t),!e&&this.traceId&&this.traceId===t&&this.langfuse.trace({id:this.traceId,output:s,...i}),!e&&this.traceId&&this.rootProvided&&this.updateRoot&&(this.rootObservationId?this.langfuse._updateSpan({id:this.rootObservationId,traceId:this.traceId,output:s}):this.langfuse.trace({id:this.traceId,output:s,...i}))}joinTagsAndMetaData(t,e,s){const i={};return t&&t.length>0&&(i.tags=t),e&&Object.assign(i,e),s&&Object.assign(i,s),this.stripLangfuseKeysFromMetadata(i)}stripLangfuseKeysFromMetadata(t){if(!t)return;const e=["langfusePrompt","langfuseUserId","langfuseSessionId"];return Object.fromEntries(Object.entries(t).filter(([s,i])=>!e.includes(s)))}}const P=async p=>{const{runName:t,item:e,langfuseClient:s,options:i}=p,n={dataset_item_id:e.id,dataset_id:e.datasetId,dataset_run_name:t},a=s.trace();return await e.link(a,t,{description:i?.runDescription,metadata:i?.runMetadata}),{handler:new k({root:a,updateRoot:!0,metadata:n}),trace:a}};export{k as CallbackHandler,T as Langfuse,P as createDatasetItemHandler,k as default};
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-HcDeYd8f.js","assets/index-B4dcyhl1.js","assets/index-CKNaXAjV.js","assets/index-DPoppY7E.css","assets/chunk-VL2OQCWN-BFKzE0YG.js","assets/index-DRz5BQNA.js","assets/__vite-browser-external-DFygW7-s.js","assets/path-C9FudP8b.js"])))=>i.map(i=>d[i]);
2
- var yy=Object.defineProperty;var _y=(e,t,n)=>t in e?yy(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var du=(e,t,n)=>_y(e,typeof t!="symbol"?t+"":t,n);import{_ as G,c as Wi,u as gt,a as Tt,d as bs,n as le,s as pe,e as Jt,o as Y,f as wy,Z as M,h as nt,i as hu,l as vr,j as vy,k as Fa,p as sh,m as Ur,r as Ss,q as Ua,t as E,v as by,w as Ba,B as Sy,x as Ty,H as Ey,L as Cy,y as Ay,M as ky,W as Oy,z as xy}from"./index-CKNaXAjV.js";import{u as Iy,w as Hc,x as Py,y as ze,z as Ny,A as My,B as Ry,C as $y,D as Ly,E as jy,F as Dy,G as Fy,H as Uy,I as By,d as kn,J as zy,g as $e,K as Hy,L as ah,M as Vy,N as Gy,O as za,h as Vc,Q as Wy,R as Jy,S as Ky,U as Zy,W as qy,X as Yy,Y as Xy,Z as Qy,a0 as e_,a1 as t_,a2 as n_,a3 as pu,a4 as r_,a5 as s_,a6 as a_,a7 as i_,s as o_,v as ke,P as nn,p as Ha,a as Ts,b as ih,c as oh,i as Gc,j as c_,f as l_,_ as u_,$ as d_,e as h_,k as p_,t as fu,l as ch,V as Wc,m as f_,n as br,o as m_,T as g_,q as Jc,r as y_,a8 as __}from"./chunk-VL2OQCWN-BFKzE0YG.js";import{o as Fo}from"./__vite-browser-external-DFygW7-s.js";import{j as Va,d as mu,i as w_}from"./path-C9FudP8b.js";var Ji,ia,Ki=0,Zi=0;function v_(e,t,n){var r=0,s=t||new Array(16);e=e||{};var a=e.node,i=e.clockseq;if(e._v6||(a||(a=Ji),i==null&&(i=ia)),a==null||i==null){var o=e.random||(e.rng||Iy)();a==null&&(a=[o[0],o[1],o[2],o[3],o[4],o[5]],!Ji&&!e._v6&&(a[0]|=1,Ji=a)),i==null&&(i=(o[6]<<8|o[7])&16383,ia===void 0&&!e._v6&&(ia=i))}var c=e.msecs!==void 0?e.msecs:Date.now(),l=e.nsecs!==void 0?e.nsecs:Zi+1,u=c-Ki+(l-Zi)/1e4;if(u<0&&e.clockseq===void 0&&(i=i+1&16383),(u<0||c>Ki)&&e.nsecs===void 0&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Ki=c,Zi=l,ia=i,c+=122192928e5;var d=((c&268435455)*1e4+l)%4294967296;s[r++]=d>>>24&255,s[r++]=d>>>16&255,s[r++]=d>>>8&255,s[r++]=d&255;var h=c/4294967296*1e4&268435455;s[r++]=h>>>8&255,s[r++]=h&255,s[r++]=h>>>24&15|16,s[r++]=h>>>16&255,s[r++]=i>>>8|128,s[r++]=i&255;for(var p=0;p<6;++p)s[r+p]=a[p];return t||Hc(s)}function b_(e){var t=typeof e=="string"?Py(e):e,n=S_(t);return typeof e=="string"?Hc(n):n}function S_(e,t=!1){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}function gu(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function yu(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?gu(Object(n),!0).forEach(function(r){T_(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):gu(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function T_(e,t,n){return(t=E_(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function E_(e){var t=C_(e,"string");return typeof t=="symbol"?t:t+""}function C_(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function A_(e={},t,n=0){var r=v_(yu(yu({},e),{},{_v6:!0}),new Uint8Array(16));return r=b_(r),Hc(r)}const k_=(e,t)=>{Ny.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Ry(e,n)},flatten:{value:n=>My(e,n)},addIssue:{value:n=>e.issues.push(n)},addIssues:{value:n=>e.issues.push(...n)},isEmpty:{get(){return e.issues.length===0}}})},yi=ze("ZodError",k_,{Parent:Error}),O_=$y(yi),x_=jy(yi),I_=Ly(yi),P_=Dy(yi),ut=ze("ZodType",(e,t)=>(By.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),e.clone=(n,r)=>kn(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>O_(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>I_(e,n,r),e.parseAsync=async(n,r)=>x_(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>P_(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(nw(n,r)),e.superRefine=n=>e.check(rw(n)),e.overwrite=n=>e.check(zy(n)),e.optional=()=>_u(e),e.nullable=()=>wu(e),e.nullish=()=>_u(wu(e)),e.nonoptional=n=>K_(e,n),e.array=()=>R_(e),e.or=n=>L_([e,n]),e.and=n=>D_(e,n),e.transform=n=>vu(e,U_(n)),e.default=n=>V_(e,n),e.prefault=n=>W_(e,n),e.catch=n=>q_(e,n),e.pipe=n=>vu(e,n),e.readonly=()=>Q_(e),e.describe=n=>{const r=e.clone();return $e.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){return $e.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return $e.get(e);const r=e.clone();return $e.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),N_=ze("ZodAny",(e,t)=>{Uy.init(e,t),ut.init(e,t)});function oa(){return Fy(N_)}const M_=ze("ZodArray",(e,t)=>{n_.init(e,t),ut.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(pu(n,r)),e.nonempty=n=>e.check(pu(1,n)),e.max=(n,r)=>e.check(r_(n,r)),e.length=(n,r)=>e.check(s_(n,r)),e.unwrap=()=>e.element});function R_(e,t){return Vy(M_,e,t)}const $_=ze("ZodUnion",(e,t)=>{Ky.init(e,t),ut.init(e,t),e.options=t.options});function L_(e,t){return new $_({type:"union",options:e,...ah(t)})}const j_=ze("ZodIntersection",(e,t)=>{Zy.init(e,t),ut.init(e,t)});function D_(e,t){return new j_({type:"intersection",left:e,right:t})}const F_=ze("ZodTransform",(e,t)=>{Yy.init(e,t),ut.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=a=>{if(typeof a=="string")n.issues.push(za(a,n.value,t));else{const i=a;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=e),i.continue??(i.continue=!0),n.issues.push(za(i))}};const s=t.transform(n.value,n);return s instanceof Promise?s.then(a=>(n.value=a,n)):(n.value=s,n)}});function U_(e){return new F_({type:"transform",transform:e})}const B_=ze("ZodOptional",(e,t)=>{Vc.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType});function _u(e){return new B_({type:"optional",innerType:e})}const z_=ze("ZodNullable",(e,t)=>{Wy.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType});function wu(e){return new z_({type:"nullable",innerType:e})}const H_=ze("ZodDefault",(e,t)=>{Xy.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function V_(e,t){return new H_({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const G_=ze("ZodPrefault",(e,t)=>{Qy.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType});function W_(e,t){return new G_({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const J_=ze("ZodNonOptional",(e,t)=>{Jy.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType});function K_(e,t){return new J_({type:"nonoptional",innerType:e,...ah(t)})}const Z_=ze("ZodCatch",(e,t)=>{e_.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function q_(e,t){return new Z_({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Y_=ze("ZodPipe",(e,t)=>{qy.init(e,t),ut.init(e,t),e.in=t.in,e.out=t.out});function vu(e,t){return new Y_({type:"pipe",in:e,out:t})}const X_=ze("ZodReadonly",(e,t)=>{t_.init(e,t),ut.init(e,t)});function Q_(e){return new X_({type:"readonly",innerType:e})}const ew=ze("ZodCustom",(e,t)=>{a_.init(e,t),ut.init(e,t)});function tw(e){const t=new Gy({check:"custom"});return t._zod.check=e,t}function nw(e,t={}){return Hy(ew,e,t)}function rw(e){const t=tw(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(za(r,n.value,t._zod.def));else{const s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=t),s.continue??(s.continue=!t._zod.def.abort),n.issues.push(za(s))}},e(n.value,n)));return t}async function*lh(e){for await(const t of e)if(t.event==="on_chat_model_stream"&&t.data?.chunk?.text){const n=t.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}}G(lh,"streamEventsToAISDK");function uh(e){return new ReadableStream({async start(t){try{for await(const n of e)t.enqueue(n);t.close()}catch(n){t.error(n)}}})}G(uh,"createReadableStreamFromGenerator");async function*dh(e){for await(const t of e)switch(t.event){case"on_chat_model_stream":if(t.data?.chunk?.text){const n=t.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}break;case"on_tool_start":yield`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-hZz5tb9V.js","assets/index-DhJ0wa09.js","assets/index-CFpQGWTL.js","assets/index-DPoppY7E.css","assets/chunk-VL2OQCWN-lvFdpsKs.js","assets/index-DRz5BQNA.js","assets/__vite-browser-external-DFygW7-s.js","assets/path-C9FudP8b.js"])))=>i.map(i=>d[i]);
2
+ var yy=Object.defineProperty;var _y=(e,t,n)=>t in e?yy(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var du=(e,t,n)=>_y(e,typeof t!="symbol"?t+"":t,n);import{_ as G,c as Wi,u as gt,a as Tt,d as bs,n as le,s as pe,e as Jt,o as Y,f as wy,Z as M,h as nt,i as hu,l as vr,j as vy,k as Fa,p as sh,m as Ur,r as Ss,q as Ua,t as E,v as by,w as Ba,B as Sy,x as Ty,H as Ey,L as Cy,y as Ay,M as ky,W as Oy,z as xy}from"./index-CFpQGWTL.js";import{u as Iy,w as Hc,x as Py,y as ze,z as Ny,A as My,B as Ry,C as $y,D as Ly,E as jy,F as Dy,G as Fy,H as Uy,I as By,d as kn,J as zy,g as $e,K as Hy,L as ah,M as Vy,N as Gy,O as za,h as Vc,Q as Wy,R as Jy,S as Ky,U as Zy,W as qy,X as Yy,Y as Xy,Z as Qy,a0 as e_,a1 as t_,a2 as n_,a3 as pu,a4 as r_,a5 as s_,a6 as a_,a7 as i_,s as o_,v as ke,P as nn,p as Ha,a as Ts,b as ih,c as oh,i as Gc,j as c_,f as l_,_ as u_,$ as d_,e as h_,k as p_,t as fu,l as ch,V as Wc,m as f_,n as br,o as m_,T as g_,q as Jc,r as y_,a8 as __}from"./chunk-VL2OQCWN-lvFdpsKs.js";import{o as Fo}from"./__vite-browser-external-DFygW7-s.js";import{j as Va,d as mu,i as w_}from"./path-C9FudP8b.js";var Ji,ia,Ki=0,Zi=0;function v_(e,t,n){var r=0,s=t||new Array(16);e=e||{};var a=e.node,i=e.clockseq;if(e._v6||(a||(a=Ji),i==null&&(i=ia)),a==null||i==null){var o=e.random||(e.rng||Iy)();a==null&&(a=[o[0],o[1],o[2],o[3],o[4],o[5]],!Ji&&!e._v6&&(a[0]|=1,Ji=a)),i==null&&(i=(o[6]<<8|o[7])&16383,ia===void 0&&!e._v6&&(ia=i))}var c=e.msecs!==void 0?e.msecs:Date.now(),l=e.nsecs!==void 0?e.nsecs:Zi+1,u=c-Ki+(l-Zi)/1e4;if(u<0&&e.clockseq===void 0&&(i=i+1&16383),(u<0||c>Ki)&&e.nsecs===void 0&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Ki=c,Zi=l,ia=i,c+=122192928e5;var d=((c&268435455)*1e4+l)%4294967296;s[r++]=d>>>24&255,s[r++]=d>>>16&255,s[r++]=d>>>8&255,s[r++]=d&255;var h=c/4294967296*1e4&268435455;s[r++]=h>>>8&255,s[r++]=h&255,s[r++]=h>>>24&15|16,s[r++]=h>>>16&255,s[r++]=i>>>8|128,s[r++]=i&255;for(var p=0;p<6;++p)s[r+p]=a[p];return t||Hc(s)}function b_(e){var t=typeof e=="string"?Py(e):e,n=S_(t);return typeof e=="string"?Hc(n):n}function S_(e,t=!1){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}function gu(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function yu(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?gu(Object(n),!0).forEach(function(r){T_(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):gu(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function T_(e,t,n){return(t=E_(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function E_(e){var t=C_(e,"string");return typeof t=="symbol"?t:t+""}function C_(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function A_(e={},t,n=0){var r=v_(yu(yu({},e),{},{_v6:!0}),new Uint8Array(16));return r=b_(r),Hc(r)}const k_=(e,t)=>{Ny.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Ry(e,n)},flatten:{value:n=>My(e,n)},addIssue:{value:n=>e.issues.push(n)},addIssues:{value:n=>e.issues.push(...n)},isEmpty:{get(){return e.issues.length===0}}})},yi=ze("ZodError",k_,{Parent:Error}),O_=$y(yi),x_=jy(yi),I_=Ly(yi),P_=Dy(yi),ut=ze("ZodType",(e,t)=>(By.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),e.clone=(n,r)=>kn(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>O_(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>I_(e,n,r),e.parseAsync=async(n,r)=>x_(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>P_(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(nw(n,r)),e.superRefine=n=>e.check(rw(n)),e.overwrite=n=>e.check(zy(n)),e.optional=()=>_u(e),e.nullable=()=>wu(e),e.nullish=()=>_u(wu(e)),e.nonoptional=n=>K_(e,n),e.array=()=>R_(e),e.or=n=>L_([e,n]),e.and=n=>D_(e,n),e.transform=n=>vu(e,U_(n)),e.default=n=>V_(e,n),e.prefault=n=>W_(e,n),e.catch=n=>q_(e,n),e.pipe=n=>vu(e,n),e.readonly=()=>Q_(e),e.describe=n=>{const r=e.clone();return $e.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){return $e.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return $e.get(e);const r=e.clone();return $e.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),N_=ze("ZodAny",(e,t)=>{Uy.init(e,t),ut.init(e,t)});function oa(){return Fy(N_)}const M_=ze("ZodArray",(e,t)=>{n_.init(e,t),ut.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(pu(n,r)),e.nonempty=n=>e.check(pu(1,n)),e.max=(n,r)=>e.check(r_(n,r)),e.length=(n,r)=>e.check(s_(n,r)),e.unwrap=()=>e.element});function R_(e,t){return Vy(M_,e,t)}const $_=ze("ZodUnion",(e,t)=>{Ky.init(e,t),ut.init(e,t),e.options=t.options});function L_(e,t){return new $_({type:"union",options:e,...ah(t)})}const j_=ze("ZodIntersection",(e,t)=>{Zy.init(e,t),ut.init(e,t)});function D_(e,t){return new j_({type:"intersection",left:e,right:t})}const F_=ze("ZodTransform",(e,t)=>{Yy.init(e,t),ut.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=a=>{if(typeof a=="string")n.issues.push(za(a,n.value,t));else{const i=a;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=e),i.continue??(i.continue=!0),n.issues.push(za(i))}};const s=t.transform(n.value,n);return s instanceof Promise?s.then(a=>(n.value=a,n)):(n.value=s,n)}});function U_(e){return new F_({type:"transform",transform:e})}const B_=ze("ZodOptional",(e,t)=>{Vc.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType});function _u(e){return new B_({type:"optional",innerType:e})}const z_=ze("ZodNullable",(e,t)=>{Wy.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType});function wu(e){return new z_({type:"nullable",innerType:e})}const H_=ze("ZodDefault",(e,t)=>{Xy.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function V_(e,t){return new H_({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const G_=ze("ZodPrefault",(e,t)=>{Qy.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType});function W_(e,t){return new G_({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const J_=ze("ZodNonOptional",(e,t)=>{Jy.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType});function K_(e,t){return new J_({type:"nonoptional",innerType:e,...ah(t)})}const Z_=ze("ZodCatch",(e,t)=>{e_.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function q_(e,t){return new Z_({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Y_=ze("ZodPipe",(e,t)=>{qy.init(e,t),ut.init(e,t),e.in=t.in,e.out=t.out});function vu(e,t){return new Y_({type:"pipe",in:e,out:t})}const X_=ze("ZodReadonly",(e,t)=>{t_.init(e,t),ut.init(e,t)});function Q_(e){return new X_({type:"readonly",innerType:e})}const ew=ze("ZodCustom",(e,t)=>{a_.init(e,t),ut.init(e,t)});function tw(e){const t=new Gy({check:"custom"});return t._zod.check=e,t}function nw(e,t={}){return Hy(ew,e,t)}function rw(e){const t=tw(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(za(r,n.value,t._zod.def));else{const s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=t),s.continue??(s.continue=!t._zod.def.abort),n.issues.push(za(s))}},e(n.value,n)));return t}async function*lh(e){for await(const t of e)if(t.event==="on_chat_model_stream"&&t.data?.chunk?.text){const n=t.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}}G(lh,"streamEventsToAISDK");function uh(e){return new ReadableStream({async start(t){try{for await(const n of e)t.enqueue(n);t.close()}catch(n){t.error(n)}}})}G(uh,"createReadableStreamFromGenerator");async function*dh(e){for await(const t of e)switch(t.event){case"on_chat_model_stream":if(t.data?.chunk?.text){const n=t.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}break;case"on_tool_start":yield`
3
3
  🔧 Using tool: ${t.name}
4
4
  `;break;case"on_tool_end":yield`
5
5
  ✅ Tool completed: ${t.name}
@@ -559,4 +559,4 @@ ${f}`);const b=await s.stream(f);let S=null,w=0;for await(const T of b){if(w++,E
559
559
 
560
560
  Make sure you gather ALL the required information during your task execution.
561
561
  If any required information is missing, continue working to find it.
562
- `}catch(r){return E.warn(`Could not extract schema details: ${r}`),t}}},G(Fr,"MCPAgent"),Fr),Re={},zP=Re.MCP_USE_LANGFUSE?.toLowerCase()==="false",Gs={handler:null,client:null,initPromise:null};async function au(e,t,n,r){try{const s=await Ba(()=>import("./index-HcDeYd8f.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).catch(()=>null);if(!s){E.debug("Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain");return}const{CallbackHandler:a}=s,u=class u extends a{agentId;metadata;metadataProvider;tagsProvider;verbose;constructor(h,p,f,g,b){super(h),this.agentId=p,this.metadata=f,this.metadataProvider=g,this.tagsProvider=b,this.verbose=h?.verbose??!1}async handleChainStart(h,p,f,g,b,S,w,v){E.debug("Langfuse: Chain start intercepted");const T=this.getCustomTags(),k=this.getMetadata(),O=[...b||[],...T],C={...S||{},...k};return this.verbose&&(E.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(O)}`),E.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(C)}`)),super.handleChainStart(h,p,f,g,O,C,w,v)}getCustomTags(){const h=[],p=this.getEnvironmentTag();if(p&&h.push(`env:${p}`),this.agentId&&h.push(`agent_id:${this.agentId}`),this.tagsProvider){const f=this.tagsProvider();f&&f.length>0&&h.push(...f)}return h}getMetadata(){const h={},p=this.getEnvironmentTag();if(p&&(h.env=p),this.agentId&&(h.agent_id=this.agentId),this.metadata&&Object.assign(h,this.metadata),this.metadataProvider){const f=this.metadataProvider();f&&Object.assign(h,f)}return h}getEnvironmentTag(){const h=Re.MCP_USE_AGENT_ENV;if(!h)return"unknown";const p=h.toLowerCase();return p==="local"||p==="development"?"local":p==="production"||p==="prod"?"production":p==="staging"||p==="stage"?"staging":p==="hosted"||p==="cloud"?"hosted":p.replace(/[^a-z0-9_-]/g,"_")}async handleLLMStart(...h){return E.debug("Langfuse: LLM start intercepted"),this.verbose&&E.debug(`Langfuse: LLM start args: ${JSON.stringify(h)}`),super.handleLLMStart(...h)}async handleToolStart(...h){return E.debug("Langfuse: Tool start intercepted"),this.verbose&&E.debug(`Langfuse: Tool start args: ${JSON.stringify(h)}`),super.handleToolStart(...h)}async handleRetrieverStart(...h){return E.debug("Langfuse: Retriever start intercepted"),this.verbose&&E.debug(`Langfuse: Retriever start args: ${JSON.stringify(h)}`),super.handleRetrieverStart(...h)}async handleAgentAction(...h){return E.debug("Langfuse: Agent action intercepted"),this.verbose&&E.debug(`Langfuse: Agent action args: ${JSON.stringify(h)}`),super.handleAgentAction(...h)}async handleAgentEnd(...h){return E.debug("Langfuse: Agent end intercepted"),this.verbose&&E.debug(`Langfuse: Agent end args: ${JSON.stringify(h)}`),super.handleAgentEnd(...h)}};G(u,"LoggingCallbackHandler");let i=u;const o=t||(n?n():{}),c=r?r():[],l={publicKey:Re.LANGFUSE_PUBLIC_KEY,secretKey:Re.LANGFUSE_SECRET_KEY,baseUrl:Re.LANGFUSE_HOST||Re.LANGFUSE_BASEURL||"https://cloud.langfuse.com",flushAt:Number.parseInt(Re.LANGFUSE_FLUSH_AT||"15"),flushInterval:Number.parseInt(Re.LANGFUSE_FLUSH_INTERVAL||"10000"),release:Re.LANGFUSE_RELEASE,requestTimeout:Number.parseInt(Re.LANGFUSE_REQUEST_TIMEOUT||"10000"),enabled:Re.LANGFUSE_ENABLED!=="false",traceName:o.trace_name||Re.LANGFUSE_TRACE_NAME||"mcp-use-agent",sessionId:o.session_id||void 0,userId:o.user_id||void 0,tags:c.length>0?c:void 0,metadata:o||void 0};E.debug("Langfuse handler config:",JSON.stringify({traceName:l.traceName,sessionId:l.sessionId,userId:l.userId,tags:l.tags},null,2)),Gs.handler=new i(l,e,t,n,r),E.debug("Langfuse observability initialized successfully with logging enabled");try{const d=await Ba(()=>import("./index-B4dcyhl1.js"),__vite__mapDeps([1,2,3,4,5,6,7])).catch(()=>null);if(d){const{Langfuse:h}=d;Gs.client=new h({publicKey:Re.LANGFUSE_PUBLIC_KEY,secretKey:Re.LANGFUSE_SECRET_KEY,baseUrl:Re.LANGFUSE_HOST||"https://cloud.langfuse.com"}),E.debug("Langfuse client initialized")}}catch(d){E.debug(`Langfuse client initialization failed: ${d}`)}}catch(s){E.debug(`Langfuse initialization error: ${s}`)}}G(au,"initializeLangfuse");zP?E.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!Re.LANGFUSE_PUBLIC_KEY||!Re.LANGFUSE_SECRET_KEY?E.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):Gs.initPromise=au();var HP=G(()=>Gs.handler,"langfuseHandler"),VP=G(()=>Gs.initPromise,"langfuseInitPromise");const nN=Object.freeze(Object.defineProperty({__proto__:null,BaseAdapter:iy,BaseConnector:Sy,BrowserOAuthClientProvider:Ty,HttpConnector:Ey,LangChainAdapter:Dn,Logger:Cy,MCPAgent:BP,MCPClient:Ay,MCPSession:ky,ObservabilityManager:Uc,RemoteAgent:dy,WebSocketConnector:Oy,createReadableStreamFromGenerator:uh,logger:E,onMcpAuthorization:xy,streamEventsToAISDK:lh,streamEventsToAISDKWithTools:dh},Symbol.toStringTag,{value:"Module"})),rh=Object.freeze(Object.defineProperty({__proto__:null,initializeLangfuse:au,langfuseHandler:HP,langfuseInitPromise:VP},Symbol.toStringTag,{value:"Module"}));export{D as A,es as B,Xn as C,vi as F,he as H,Se as S,X as T,rt as a,yt as b,nN as c,lt as m};
562
+ `}catch(r){return E.warn(`Could not extract schema details: ${r}`),t}}},G(Fr,"MCPAgent"),Fr),Re={},zP=Re.MCP_USE_LANGFUSE?.toLowerCase()==="false",Gs={handler:null,client:null,initPromise:null};async function au(e,t,n,r){try{const s=await Ba(()=>import("./index-hZz5tb9V.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).catch(()=>null);if(!s){E.debug("Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain");return}const{CallbackHandler:a}=s,u=class u extends a{agentId;metadata;metadataProvider;tagsProvider;verbose;constructor(h,p,f,g,b){super(h),this.agentId=p,this.metadata=f,this.metadataProvider=g,this.tagsProvider=b,this.verbose=h?.verbose??!1}async handleChainStart(h,p,f,g,b,S,w,v){E.debug("Langfuse: Chain start intercepted");const T=this.getCustomTags(),k=this.getMetadata(),O=[...b||[],...T],C={...S||{},...k};return this.verbose&&(E.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(O)}`),E.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(C)}`)),super.handleChainStart(h,p,f,g,O,C,w,v)}getCustomTags(){const h=[],p=this.getEnvironmentTag();if(p&&h.push(`env:${p}`),this.agentId&&h.push(`agent_id:${this.agentId}`),this.tagsProvider){const f=this.tagsProvider();f&&f.length>0&&h.push(...f)}return h}getMetadata(){const h={},p=this.getEnvironmentTag();if(p&&(h.env=p),this.agentId&&(h.agent_id=this.agentId),this.metadata&&Object.assign(h,this.metadata),this.metadataProvider){const f=this.metadataProvider();f&&Object.assign(h,f)}return h}getEnvironmentTag(){const h=Re.MCP_USE_AGENT_ENV;if(!h)return"unknown";const p=h.toLowerCase();return p==="local"||p==="development"?"local":p==="production"||p==="prod"?"production":p==="staging"||p==="stage"?"staging":p==="hosted"||p==="cloud"?"hosted":p.replace(/[^a-z0-9_-]/g,"_")}async handleLLMStart(...h){return E.debug("Langfuse: LLM start intercepted"),this.verbose&&E.debug(`Langfuse: LLM start args: ${JSON.stringify(h)}`),super.handleLLMStart(...h)}async handleToolStart(...h){return E.debug("Langfuse: Tool start intercepted"),this.verbose&&E.debug(`Langfuse: Tool start args: ${JSON.stringify(h)}`),super.handleToolStart(...h)}async handleRetrieverStart(...h){return E.debug("Langfuse: Retriever start intercepted"),this.verbose&&E.debug(`Langfuse: Retriever start args: ${JSON.stringify(h)}`),super.handleRetrieverStart(...h)}async handleAgentAction(...h){return E.debug("Langfuse: Agent action intercepted"),this.verbose&&E.debug(`Langfuse: Agent action args: ${JSON.stringify(h)}`),super.handleAgentAction(...h)}async handleAgentEnd(...h){return E.debug("Langfuse: Agent end intercepted"),this.verbose&&E.debug(`Langfuse: Agent end args: ${JSON.stringify(h)}`),super.handleAgentEnd(...h)}};G(u,"LoggingCallbackHandler");let i=u;const o=t||(n?n():{}),c=r?r():[],l={publicKey:Re.LANGFUSE_PUBLIC_KEY,secretKey:Re.LANGFUSE_SECRET_KEY,baseUrl:Re.LANGFUSE_HOST||Re.LANGFUSE_BASEURL||"https://cloud.langfuse.com",flushAt:Number.parseInt(Re.LANGFUSE_FLUSH_AT||"15"),flushInterval:Number.parseInt(Re.LANGFUSE_FLUSH_INTERVAL||"10000"),release:Re.LANGFUSE_RELEASE,requestTimeout:Number.parseInt(Re.LANGFUSE_REQUEST_TIMEOUT||"10000"),enabled:Re.LANGFUSE_ENABLED!=="false",traceName:o.trace_name||Re.LANGFUSE_TRACE_NAME||"mcp-use-agent",sessionId:o.session_id||void 0,userId:o.user_id||void 0,tags:c.length>0?c:void 0,metadata:o||void 0};E.debug("Langfuse handler config:",JSON.stringify({traceName:l.traceName,sessionId:l.sessionId,userId:l.userId,tags:l.tags},null,2)),Gs.handler=new i(l,e,t,n,r),E.debug("Langfuse observability initialized successfully with logging enabled");try{const d=await Ba(()=>import("./index-DhJ0wa09.js"),__vite__mapDeps([1,2,3,4,5,6,7])).catch(()=>null);if(d){const{Langfuse:h}=d;Gs.client=new h({publicKey:Re.LANGFUSE_PUBLIC_KEY,secretKey:Re.LANGFUSE_SECRET_KEY,baseUrl:Re.LANGFUSE_HOST||"https://cloud.langfuse.com"}),E.debug("Langfuse client initialized")}}catch(d){E.debug(`Langfuse client initialization failed: ${d}`)}}catch(s){E.debug(`Langfuse initialization error: ${s}`)}}G(au,"initializeLangfuse");zP?E.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!Re.LANGFUSE_PUBLIC_KEY||!Re.LANGFUSE_SECRET_KEY?E.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):Gs.initPromise=au();var HP=G(()=>Gs.handler,"langfuseHandler"),VP=G(()=>Gs.initPromise,"langfuseInitPromise");const nN=Object.freeze(Object.defineProperty({__proto__:null,BaseAdapter:iy,BaseConnector:Sy,BrowserOAuthClientProvider:Ty,HttpConnector:Ey,LangChainAdapter:Dn,Logger:Cy,MCPAgent:BP,MCPClient:Ay,MCPSession:ky,ObservabilityManager:Uc,RemoteAgent:dy,WebSocketConnector:Oy,createReadableStreamFromGenerator:uh,logger:E,onMcpAuthorization:xy,streamEventsToAISDK:lh,streamEventsToAISDKWithTools:dh},Symbol.toStringTag,{value:"Module"})),rh=Object.freeze(Object.defineProperty({__proto__:null,initializeLangfuse:au,langfuseHandler:HP,langfuseInitPromise:VP},Symbol.toStringTag,{value:"Module"}));export{D as A,es as B,Xn as C,vi as F,he as H,Se as S,X as T,rt as a,yt as b,nN as c,lt as m};