@mcp-use/inspector 0.5.1 → 0.5.2-canary.1

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 +1 @@
1
- import{m as B}from"./langfuse-C4HKZ3NL-BR3E7iCI.js";import"./index-CNwZaJQ9.js";import"./chunk-VL2OQCWN-DBinT58-.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-CNKDmQgM.js";import"./index-pW-Qf4ti.js";import"./chunk-VL2OQCWN-Btnznw_a.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};
@@ -0,0 +1,70 @@
1
+ import{m as Ft,n as Bt,o as X,q as et,_ as U,r as Ie,s as Se,u as Ae,v as Ne,w as Oe,x as ke,y as Pe,z as Me,D as xe,E as Re,i as wt,G as Le,I as De,J as Fe,K as Be,L as Ue,M as je,N as Ve,k as ze,O as Ge,P as zt,Q as $e,U as Gt,V as Ze,W as He,X as We,Y as H,t as ut,H as Ct,Z as Xe,$ as Ye,a0 as Je,c as $t,a1 as nt,a2 as it,a3 as Zt,a4 as Ht,a5 as ot,l as Ke,a6 as bt,a7 as Ut,a8 as qe,a9 as jt,d as Y,g as Qe,aa as It,b as ta,R as Wt,ab as ea,ac as aa,ad as sa,A as Xt,ae as rt,af as G,ag as Yt,ah as na,ai as Jt,aj as ra,ak as ia,al as oa,am as ca,an as ua,ao as la,ap as ha,aq as ma,ar as fa,as as pa,e as Vt,at as ga,au as da,av as ba,aw as Tt,ax as _a}from"./index-DFGxR74O.js";import{g as ya,T as Ta,d as va}from"./chunk-VL2OQCWN-Btnznw_a.js";import{o as Kt,s as qt}from"./index-pW-Qf4ti.js";function Qt(t,a,n,r,c){if(a!==t){typeof a.toJSON=="function"&&(a=a.toJSON());for(var u=Ft(a),m=Ft(t),l=!1,g=m.length-1;g>=0;g--){var f=m[g],T=t[f];if(Bt(a,f)&&!(a[f]===void 0&&T!==void 0&&Array.isArray(a)===!1)){var _=a[f];typeof T=="object"&&T!=null&&typeof _=="object"&&_!=null&&Array.isArray(T)===Array.isArray(_)?Qt(T,_,n,r+"/"+X(f),c):T!==_&&(c&&n.push({op:"test",path:r+"/"+X(f),value:et(T)}),n.push({op:"replace",path:r+"/"+X(f),value:et(_)}))}else Array.isArray(t)===Array.isArray(a)?(c&&n.push({op:"test",path:r+"/"+X(f),value:et(T)}),n.push({op:"remove",path:r+"/"+X(f)}),l=!0):(c&&n.push({op:"test",path:r,value:t}),n.push({op:"replace",path:r,value:a}))}if(!(!l&&u.length==m.length))for(var g=0;g<u.length;g++){var f=u[g];!Bt(t,f)&&a[f]!==void 0&&n.push({op:"add",path:r+"/"+X(f),value:et(a[f])})}}}function St(t,a,n=!1){var r=[];return Qt(t,a,r,"",n),r}var Ea={};U(Ea,{extendInteropZodObject:()=>We,getInteropZodDefaultGetter:()=>He,getInteropZodObjectShape:()=>Ze,getSchemaDescription:()=>Gt,interopParse:()=>$e,interopParseAsync:()=>zt,interopSafeParse:()=>Ge,interopSafeParseAsync:()=>ze,interopZodObjectMakeFieldsOptional:()=>Ve,interopZodObjectPartial:()=>je,interopZodObjectPassthrough:()=>Ue,interopZodObjectStrict:()=>Be,interopZodTransformInputSchema:()=>Fe,isInteropZodLiteral:()=>De,isInteropZodObject:()=>Le,isInteropZodSchema:()=>wt,isShapelessZodSchema:()=>Re,isSimpleStringZodSchema:()=>xe,isZodArrayV4:()=>Me,isZodLiteralV3:()=>Pe,isZodLiteralV4:()=>ke,isZodObjectV3:()=>Oe,isZodObjectV4:()=>Ne,isZodSchema:()=>Ae,isZodSchemaV3:()=>Se,isZodSchemaV4:()=>Ie});function te(t){return t!==void 0&&Array.isArray(t.lc_namespace)}function ee(t){return t!==void 0&&H.isRunnable(t)&&"lc_name"in t.constructor&&typeof t.constructor.lc_name=="function"&&t.constructor.lc_name()==="RunnableToolLike"}function ae(t){return!!t&&typeof t=="object"&&"name"in t&&"schema"in t&&(wt(t.schema)||t.schema!=null&&typeof t.schema=="object"&&"type"in t.schema&&typeof t.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(t.schema.type))}function se(t){return ae(t)||ee(t)||te(t)}var wa={};U(wa,{convertToOpenAIFunction:()=>ne,convertToOpenAITool:()=>Ca,isLangChainTool:()=>se,isRunnableToolLike:()=>ee,isStructuredTool:()=>te,isStructuredToolParams:()=>ae});function ne(t,a){const n=typeof a=="number"?void 0:a;return{name:t.name,description:t.description,parameters:ut(t.schema),...n?.strict!==void 0?{strict:n.strict}:{}}}function Ca(t,a){const n=typeof a=="number"?void 0:a;let r;return se(t)?r={type:"function",function:ne(t)}:r=t,n?.strict!==void 0&&(r.function.strict=n.strict),r}var Ia={};U(Ia,{BasePromptValue:()=>lt,ChatPromptValue:()=>ie,ImagePromptValue:()=>Sa,StringPromptValue:()=>re});var lt=class extends Ye{},re=class extends lt{static lc_name(){return"StringPromptValue"}lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;value;constructor(t){super({value:t}),this.value=t}toString(){return this.value}toChatMessages(){return[new Ct(this.value)]}},ie=class extends lt{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ChatPromptValue"}messages;constructor(t){Array.isArray(t)&&(t={messages:t}),super(t),this.messages=t.messages}toString(){return Xe(this.messages)}toChatMessages(){return this.messages}},Sa=class extends lt{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ImagePromptValue"}imageUrl;value;constructor(t){"imageUrl"in t||(t={imageUrl:t}),super(t),this.imageUrl=t.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new Ct({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},p="0123456789abcdef".split(""),Aa=[-2147483648,8388608,32768,128],F=[24,16,8,0],at=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],k=[];function B(t,a){a?(k[0]=k[16]=k[1]=k[2]=k[3]=k[4]=k[5]=k[6]=k[7]=k[8]=k[9]=k[10]=k[11]=k[12]=k[13]=k[14]=k[15]=0,this.blocks=k):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=t}B.prototype.update=function(t){if(!this.finalized){var a,n=typeof t;if(n!=="string"){if(n==="object"){if(t===null)throw new Error(ERROR);if(ARRAY_BUFFER&&t.constructor===ArrayBuffer)t=new Uint8Array(t);else if(!Array.isArray(t)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(t)))throw new Error(ERROR)}else throw new Error(ERROR);a=!0}for(var r,c=0,u,m=t.length,l=this.blocks;c<m;){if(this.hashed&&(this.hashed=!1,l[0]=this.block,this.block=l[16]=l[1]=l[2]=l[3]=l[4]=l[5]=l[6]=l[7]=l[8]=l[9]=l[10]=l[11]=l[12]=l[13]=l[14]=l[15]=0),a)for(u=this.start;c<m&&u<64;++c)l[u>>>2]|=t[c]<<F[u++&3];else for(u=this.start;c<m&&u<64;++c)r=t.charCodeAt(c),r<128?l[u>>>2]|=r<<F[u++&3]:r<2048?(l[u>>>2]|=(192|r>>>6)<<F[u++&3],l[u>>>2]|=(128|r&63)<<F[u++&3]):r<55296||r>=57344?(l[u>>>2]|=(224|r>>>12)<<F[u++&3],l[u>>>2]|=(128|r>>>6&63)<<F[u++&3],l[u>>>2]|=(128|r&63)<<F[u++&3]):(r=65536+((r&1023)<<10|t.charCodeAt(++c)&1023),l[u>>>2]|=(240|r>>>18)<<F[u++&3],l[u>>>2]|=(128|r>>>12&63)<<F[u++&3],l[u>>>2]|=(128|r>>>6&63)<<F[u++&3],l[u>>>2]|=(128|r&63)<<F[u++&3]);this.lastByteIndex=u,this.bytes+=u-this.start,u>=64?(this.block=l[16],this.start=u-64,this.hash(),this.hashed=!0):this.start=u}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};B.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,a=this.lastByteIndex;t[16]=this.block,t[a>>>2]|=Aa[a&3],this.block=t[16],a>=56&&(this.hashed||this.hash(),t[0]=this.block,t[16]=t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=t[7]=t[8]=t[9]=t[10]=t[11]=t[12]=t[13]=t[14]=t[15]=0),t[14]=this.hBytes<<3|this.bytes>>>29,t[15]=this.bytes<<3,this.hash()}};B.prototype.hash=function(){var t=this.h0,a=this.h1,n=this.h2,r=this.h3,c=this.h4,u=this.h5,m=this.h6,l=this.h7,g=this.blocks,f,T,_,v,d,y,b,E,w,M,S;for(f=16;f<64;++f)d=g[f-15],T=(d>>>7|d<<25)^(d>>>18|d<<14)^d>>>3,d=g[f-2],_=(d>>>17|d<<15)^(d>>>19|d<<13)^d>>>10,g[f]=g[f-16]+T+g[f-7]+_<<0;for(S=a&n,f=0;f<64;f+=4)this.first?(this.is224?(E=300032,d=g[0]-1413257819,l=d-150054599<<0,r=d+24177077<<0):(E=704751109,d=g[0]-210244248,l=d-1521486534<<0,r=d+143694565<<0),this.first=!1):(T=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),_=(c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7),E=t&a,v=E^t&n^S,b=c&u^~c&m,d=l+_+b+at[f]+g[f],y=T+v,l=r+d<<0,r=d+y<<0),T=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),_=(l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7),w=r&t,v=w^r&a^E,b=m&l^~m&c,d=u+_+b+at[f+1]+g[f+1],y=T+v,m=n+d<<0,n=d+y<<0,T=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),_=(m>>>6|m<<26)^(m>>>11|m<<21)^(m>>>25|m<<7),M=n&r,v=M^n&t^w,b=u&m^~u&l,d=c+_+b+at[f+2]+g[f+2],y=T+v,u=a+d<<0,a=d+y<<0,T=(a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10),_=(u>>>6|u<<26)^(u>>>11|u<<21)^(u>>>25|u<<7),S=a&n,v=S^a&r^M,b=u&m^~u&l,d=c+_+b+at[f+3]+g[f+3],y=T+v,c=t+d<<0,t=d+y<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+t<<0,this.h1=this.h1+a<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+c<<0,this.h5=this.h5+u<<0,this.h6=this.h6+m<<0,this.h7=this.h7+l<<0};B.prototype.hex=function(){this.finalize();var t=this.h0,a=this.h1,n=this.h2,r=this.h3,c=this.h4,u=this.h5,m=this.h6,l=this.h7,g=p[t>>>28&15]+p[t>>>24&15]+p[t>>>20&15]+p[t>>>16&15]+p[t>>>12&15]+p[t>>>8&15]+p[t>>>4&15]+p[t&15]+p[a>>>28&15]+p[a>>>24&15]+p[a>>>20&15]+p[a>>>16&15]+p[a>>>12&15]+p[a>>>8&15]+p[a>>>4&15]+p[a&15]+p[n>>>28&15]+p[n>>>24&15]+p[n>>>20&15]+p[n>>>16&15]+p[n>>>12&15]+p[n>>>8&15]+p[n>>>4&15]+p[n&15]+p[r>>>28&15]+p[r>>>24&15]+p[r>>>20&15]+p[r>>>16&15]+p[r>>>12&15]+p[r>>>8&15]+p[r>>>4&15]+p[r&15]+p[c>>>28&15]+p[c>>>24&15]+p[c>>>20&15]+p[c>>>16&15]+p[c>>>12&15]+p[c>>>8&15]+p[c>>>4&15]+p[c&15]+p[u>>>28&15]+p[u>>>24&15]+p[u>>>20&15]+p[u>>>16&15]+p[u>>>12&15]+p[u>>>8&15]+p[u>>>4&15]+p[u&15]+p[m>>>28&15]+p[m>>>24&15]+p[m>>>20&15]+p[m>>>16&15]+p[m>>>12&15]+p[m>>>8&15]+p[m>>>4&15]+p[m&15];return this.is224||(g+=p[l>>>28&15]+p[l>>>24&15]+p[l>>>20&15]+p[l>>>16&15]+p[l>>>12&15]+p[l>>>8&15]+p[l>>>4&15]+p[l&15]),g};B.prototype.toString=B.prototype.hex;B.prototype.digest=function(){this.finalize();var t=this.h0,a=this.h1,n=this.h2,r=this.h3,c=this.h4,u=this.h5,m=this.h6,l=this.h7,g=[t>>>24&255,t>>>16&255,t>>>8&255,t&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,c>>>24&255,c>>>16&255,c>>>8&255,c&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,m>>>24&255,m>>>16&255,m>>>8&255,m&255];return this.is224||g.push(l>>>24&255,l>>>16&255,l>>>8&255,l&255),g};B.prototype.array=B.prototype.digest;B.prototype.arrayBuffer=function(){this.finalize();var t=new ArrayBuffer(this.is224?28:32),a=new DataView(t);return a.setUint32(0,this.h0),a.setUint32(4,this.h1),a.setUint32(8,this.h2),a.setUint32(12,this.h3),a.setUint32(16,this.h4),a.setUint32(20,this.h5),a.setUint32(24,this.h6),this.is224||a.setUint32(28,this.h7),t};const oe=(...t)=>new B(!1,!0).update(t.join("")).hex();var Na={};U(Na,{sha256:()=>oe});var Oa={};U(Oa,{BaseCache:()=>ue,InMemoryCache:()=>le,defaultHashKeyEncoder:()=>ce,deserializeStoredGeneration:()=>ka,serializeGeneration:()=>Pa});const ce=(...t)=>oe(t.join("_"));function ka(t){return t.message!==void 0?{text:t.text,message:Je(t.message)}:{text:t.text}}function Pa(t){const a={text:t.text};return t.message!==void 0&&(a.message=t.message.toDict()),a}var ue=class{keyEncoder=ce;makeDefaultKeyEncoder(t){this.keyEncoder=t}};const Ma=new Map;var le=class he extends ue{cache;constructor(a){super(),this.cache=a??new Map}lookup(a,n){return Promise.resolve(this.cache.get(this.keyEncoder(a,n))??null)}async update(a,n,r){this.cache.set(this.keyEncoder(a,n),r)}static global(){return new he(Ma)}},xa={};U(xa,{encodingForModel:()=>At,getEncoding:()=>me});const st={},Ra=new $t({});async function me(t){return t in st||(st[t]=Ra.fetch(`https://tiktoken.pages.dev/js/${t}.json`).then(a=>a.json()).then(a=>new Ta(a)).catch(a=>{throw delete st[t],a})),await st[t]}async function At(t){return me(ya(t))}var La={};U(La,{BaseLangChain:()=>pe,BaseLanguageModel:()=>ge,calculateMaxTokens:()=>Ba,getEmbeddingContextSize:()=>Da,getModelContextSize:()=>fe,getModelNameForTiktoken:()=>ht,isOpenAITool:()=>Fa});const ht=t=>t.startsWith("gpt-5")?"gpt-5":t.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":t.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":t.startsWith("gpt-4-32k")?"gpt-4-32k":t.startsWith("gpt-4-")?"gpt-4":t.startsWith("gpt-4o")?"gpt-4o":t,Da=t=>{switch(t){case"text-embedding-ada-002":return 8191;default:return 2046}},fe=t=>{switch(ht(t)){case"gpt-5":case"gpt-5-turbo":case"gpt-5-turbo-preview":return 4e5;case"gpt-4o":case"gpt-4o-mini":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":return 128e3;case"gpt-4-turbo":case"gpt-4-turbo-preview":case"gpt-4-turbo-2024-04-09":case"gpt-4-0125-preview":case"gpt-4-1106-preview":return 128e3;case"gpt-4-32k":case"gpt-4-32k-0314":case"gpt-4-32k-0613":return 32768;case"gpt-4":case"gpt-4-0314":case"gpt-4-0613":return 8192;case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-16k-0613":return 16384;case"gpt-3.5-turbo":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-1106":case"gpt-3.5-turbo-0125":return 4096;case"text-davinci-003":case"text-davinci-002":return 4097;case"text-davinci-001":return 2049;case"text-curie-001":case"text-babbage-001":case"text-ada-001":return 2048;case"code-davinci-002":case"code-davinci-001":return 8e3;case"code-cushman-001":return 2048;case"claude-3-5-sonnet-20241022":case"claude-3-5-sonnet-20240620":case"claude-3-opus-20240229":case"claude-3-sonnet-20240229":case"claude-3-haiku-20240307":case"claude-2.1":return 2e5;case"claude-2.0":case"claude-instant-1.2":return 1e5;case"gemini-1.5-pro":case"gemini-1.5-pro-latest":case"gemini-1.5-flash":case"gemini-1.5-flash-latest":return 1e6;case"gemini-pro":case"gemini-pro-vision":return 32768;default:return 4097}};function Fa(t){return typeof t!="object"||!t?!1:!!("type"in t&&t.type==="function"&&"function"in t&&typeof t.function=="object"&&t.function&&"name"in t.function&&"parameters"in t.function)}const Ba=async({prompt:t,modelName:a})=>{let n;try{n=(await At(ht(a))).encode(t).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),n=Math.ceil(t.length/4)}return fe(a)-n},Ua=()=>!1;var pe=class extends H{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(t){super(t),this.verbose=t.verbose??Ua(),this.callbacks=t.callbacks,this.tags=t.tags??[],this.metadata=t.metadata??{}}},ge=class extends pe{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}caller;cache;constructor({callbacks:t,callbackManager:a,...n}){const{cache:r,...c}=n;super({callbacks:t??a,...c}),typeof r=="object"?this.cache=r:r?this.cache=le.global():this.cache=void 0,this.caller=new $t(n??{})}_encoding;async getNumTokens(t){let a;typeof t=="string"?a=t:a=t.map(r=>typeof r=="string"?r:r.type==="text"&&"text"in r?r.text:"").join("");let n=Math.ceil(a.length/4);if(!this._encoding)try{this._encoding=await At("modelName"in this?ht(this.modelName):"gpt2")}catch(r){console.warn("Failed to calculate number of tokens, falling back to approximate count",r)}if(this._encoding)try{n=this._encoding.encode(a).length}catch(r){console.warn("Failed to calculate number of tokens, falling back to approximate count",r)}return n}static _convertInputToPromptValue(t){return typeof t=="string"?new re(t):Array.isArray(t)?new ie(t.map(nt)):t}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:t,...a}){const n={...this._identifyingParams(),...a,_type:this._llmType(),_model:this._modelType()};return Object.entries(n).filter(([u,m])=>m!==void 0).map(([u,m])=>`${u}:${JSON.stringify(m)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(t){throw new Error("Use .toJSON() instead")}},ct=class extends H{static lc_name(){return"RunnablePassthrough"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;func;constructor(t){super(t),t&&(this.func=t.func)}async invoke(t,a){const n=it(a);return this.func&&await this.func(t,n),this._callWithConfig(r=>Promise.resolve(r),t,n)}async*transform(t,a){const n=it(a);let r,c=!0;for await(const u of this._transformStreamWithConfig(t,m=>m,n))if(yield u,c)if(r===void 0)r=u;else try{r=ot(r,u)}catch{r=void 0,c=!1}this.func&&r!==void 0&&await this.func(r,n)}static assign(t){return new Zt(new Ht({steps:t}))}};const ja=t=>t();function _t(t){const a=t.constructor;return new a({...t,content:t.contentBlocks,response_metadata:{...t.response_metadata,output_version:"v1"}})}var Va={};U(Va,{BaseChatModel:()=>de,SimpleChatModel:()=>za});function yt(t){const a=[];for(const n of t){let r=n;if(Array.isArray(n.content))for(let c=0;c<n.content.length;c++){const u=n.content[c];(ea(u)||aa(u))&&r===n&&(r=new n.constructor({...r,content:[...n.content.slice(0,c),sa(u),...n.content.slice(c+1)]}))}a.push(r)}return a}var de=class $ extends ge{lc_namespace=["langchain","chat_models",this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,"outputVersion"]}constructor(a){super(a),this.outputVersion=ja(()=>{const n=a.outputVersion??Ke("LC_OUTPUT_VERSION");return n&&["v0","v1"].includes(n)?n:"v0"})}_separateRunnableConfigFromCallOptionsCompat(a){const[n,r]=super._separateRunnableConfigFromCallOptions(a);return r.signal=n.signal,[n,r]}async invoke(a,n){const r=$._convertInputToPromptValue(a);return(await this.generatePrompt([r],n,n?.callbacks)).generations[0][0].message}async*_streamResponseChunks(a,n,r){throw new Error("Not implemented.")}async*_streamIterator(a,n){if(this._streamResponseChunks===$.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(a,n);else{const c=$._convertInputToPromptValue(a).toChatMessages(),[u,m]=this._separateRunnableConfigFromCallOptionsCompat(n),l={...u.metadata,...this.getLsParams(m)},g=await bt.configure(u.callbacks,this.callbacks,u.tags,this.tags,l,this.metadata,{verbose:this.verbose}),f={options:m,invocation_params:this?.invocationParams(m),batch_size:1},T=m.outputVersion??this.outputVersion,_=await g?.handleChatModelStart(this.toJSON(),[yt(c)],u.runId,void 0,f,void 0,void 0,u.runName);let v,d;try{for await(const y of this._streamResponseChunks(c,m,_?.[0])){if(y.message.id==null){const b=_?.at(0)?.runId;b!=null&&y.message._updateId(`run-${b}`)}y.message.response_metadata={...y.generationInfo,...y.message.response_metadata},T==="v1"?yield _t(y.message):yield y.message,v?v=v.concat(y):v=y,Ut(y.message)&&y.message.usage_metadata!==void 0&&(d={tokenUsage:{promptTokens:y.message.usage_metadata.input_tokens,completionTokens:y.message.usage_metadata.output_tokens,totalTokens:y.message.usage_metadata.total_tokens}})}}catch(y){throw await Promise.all((_??[]).map(b=>b?.handleLLMError(y))),y}await Promise.all((_??[]).map(y=>y?.handleLLMEnd({generations:[[v]],llmOutput:d})))}}getLsParams(a){const n=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:a.stop,ls_provider:n}}async _generateUncached(a,n,r,c){const u=a.map(v=>v.map(nt));let m;if(c!==void 0&&c.length===u.length)m=c;else{const v={...r.metadata,...this.getLsParams(n)},d=await bt.configure(r.callbacks,this.callbacks,r.tags,this.tags,v,this.metadata,{verbose:this.verbose}),y={options:n,invocation_params:this?.invocationParams(n),batch_size:1};m=await d?.handleChatModelStart(this.toJSON(),u.map(yt),r.runId,void 0,y,void 0,void 0,r.runName)}const l=n.outputVersion??this.outputVersion,g=[],f=[];if(!!m?.[0].handlers.find(qe)&&!this.disableStreaming&&u.length===1&&this._streamResponseChunks!==$.prototype._streamResponseChunks)try{const v=await this._streamResponseChunks(u[0],n,m?.[0]);let d,y;for await(const b of v){if(b.message.id==null){const E=m?.at(0)?.runId;E!=null&&b.message._updateId(`run-${E}`)}d===void 0?d=b:d=ot(d,b),Ut(b.message)&&b.message.usage_metadata!==void 0&&(y={tokenUsage:{promptTokens:b.message.usage_metadata.input_tokens,completionTokens:b.message.usage_metadata.output_tokens,totalTokens:b.message.usage_metadata.total_tokens}})}if(d===void 0)throw new Error("Received empty response from chat model call.");g.push([d]),await m?.[0].handleLLMEnd({generations:g,llmOutput:y})}catch(v){throw await m?.[0].handleLLMError(v),v}else{const v=await Promise.allSettled(u.map(async(d,y)=>{const b=await this._generate(d,{...n,promptIndex:y},m?.[y]);if(l==="v1")for(const E of b.generations)E.message=_t(E.message);return b}));await Promise.all(v.map(async(d,y)=>{if(d.status==="fulfilled"){const b=d.value;for(const E of b.generations){if(E.message.id==null){const w=m?.at(0)?.runId;w!=null&&E.message._updateId(`run-${w}`)}E.message.response_metadata={...E.generationInfo,...E.message.response_metadata}}return b.generations.length===1&&(b.generations[0].message.response_metadata={...b.llmOutput,...b.generations[0].message.response_metadata}),g[y]=b.generations,f[y]=b.llmOutput,m?.[y]?.handleLLMEnd({generations:[b.generations],llmOutput:b.llmOutput})}else return await m?.[y]?.handleLLMError(d.reason),Promise.reject(d.reason)}))}const _={generations:g,llmOutput:f.length?this._combineLLMOutput?.(...f):void 0};return Object.defineProperty(_,jt,{value:m?{runIds:m?.map(v=>v.runId)}:void 0,configurable:!0}),_}async _generateCached({messages:a,cache:n,llmStringKey:r,parsedOptions:c,handledOptions:u}){const m=a.map(w=>w.map(nt)),l={...u.metadata,...this.getLsParams(c)},g=await bt.configure(u.callbacks,this.callbacks,u.tags,this.tags,l,this.metadata,{verbose:this.verbose}),f={options:c,invocation_params:this?.invocationParams(c),batch_size:1},T=await g?.handleChatModelStart(this.toJSON(),m.map(yt),u.runId,void 0,f,void 0,void 0,u.runName),_=[],d=(await Promise.allSettled(m.map(async(w,M)=>{const S=$._convertInputToPromptValue(w).toString(),R=await n.lookup(S,r);return R==null&&_.push(M),R}))).map((w,M)=>({result:w,runManager:T?.[M]})).filter(({result:w})=>w.status==="fulfilled"&&w.value!=null||w.status==="rejected"),y=c.outputVersion??this.outputVersion,b=[];await Promise.all(d.map(async({result:w,runManager:M},S)=>{if(w.status==="fulfilled"){const R=w.value;return b[S]=R.map(D=>("message"in D&&Y(D.message)&&Qe(D.message)&&(D.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},y==="v1"&&(D.message=_t(D.message))),D.generationInfo={...D.generationInfo,tokenUsage:{}},D)),R.length&&await M?.handleLLMNewToken(R[0].text),M?.handleLLMEnd({generations:[R]},void 0,void 0,void 0,{cached:!0})}else return await M?.handleLLMError(w.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(w.reason)}));const E={generations:b,missingPromptIndices:_,startedRunManagers:T};return Object.defineProperty(E,jt,{value:T?{runIds:T?.map(w=>w.runId)}:void 0,configurable:!0}),E}async generate(a,n,r){let c;Array.isArray(n)?c={stop:n}:c=n;const u=a.map(y=>y.map(nt)),[m,l]=this._separateRunnableConfigFromCallOptionsCompat(c);if(m.callbacks=m.callbacks??r,!this.cache)return this._generateUncached(u,l,m);const{cache:g}=this,f=this._getSerializedCacheKeyParametersForCall(l),{generations:T,missingPromptIndices:_,startedRunManagers:v}=await this._generateCached({messages:u,cache:g,llmStringKey:f,parsedOptions:l,handledOptions:m});let d={};if(_.length>0){const y=await this._generateUncached(_.map(b=>u[b]),l,m,v!==void 0?_.map(b=>v?.[b]):void 0);await Promise.all(y.generations.map(async(b,E)=>{const w=_[E];T[w]=b;const M=$._convertInputToPromptValue(u[w]).toString();return g.update(M,f,b)})),d=y.llmOutput??{}}return{generations:T,llmOutput:d}}invocationParams(a){return{}}_modelType(){return"base_chat_model"}async generatePrompt(a,n,r){const c=a.map(u=>u.toChatMessages());return this.generate(c,n,r)}withStructuredOutput(a,n){if(typeof this.bindTools!="function")throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(n?.strict)throw new Error('"strict" mode is not supported for this model by default.');const r=a,c=n?.name,u=Gt(r)??"A function available to call.",m=n?.method,l=n?.includeRaw;if(m==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let g=c??"extract",f;wt(r)?f=[{type:"function",function:{name:g,description:u,parameters:ut(r)}}]:("name"in r&&(g=r.name),f=[{type:"function",function:{name:g,description:u,parameters:r}}]);const T=this.bindTools(f),_=It.from(b=>{if(!ta.isInstance(b))throw new Error("Input is not an AIMessageChunk.");if(!b.tool_calls||b.tool_calls.length===0)throw new Error("No tool calls found in the response.");const E=b.tool_calls.find(w=>w.name===g);if(!E)throw new Error(`No tool call found with name ${g}.`);return E.args});if(!l)return T.pipe(_).withConfig({runName:"StructuredOutput"});const v=ct.assign({parsed:(b,E)=>_.invoke(b.raw,E)}),d=ct.assign({parsed:()=>null}),y=v.withFallbacks({fallbacks:[d]});return Wt.from([{raw:T},y]).withConfig({runName:"StructuredOutputRunnable"})}},za=class extends de{async _generate(t,a,n){const r=await this._call(t,a,n),c=new Xt(r);if(typeof c.content!="string")throw new Error("Cannot generate with a simple chat model when output is not a string.");return{generations:[{text:c.content,message:c}]}}},Ga=class extends H{static lc_name(){return"RouterRunnable"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnables;constructor(t){super(t),this.runnables=t.runnables}async invoke(t,a){const{key:n,input:r}=t,c=this.runnables[n];if(c===void 0)throw new Error(`No runnable associated with key "${n}".`);return c.invoke(r,it(a))}async batch(t,a,n){const r=t.map(_=>_.key),c=t.map(_=>_.input);if(r.find(_=>this.runnables[_]===void 0)!==void 0)throw new Error("One or more keys do not have a corresponding runnable.");const m=r.map(_=>this.runnables[_]),l=this._getOptionsList(a??{},t.length),g=l[0]?.maxConcurrency??n?.maxConcurrency,f=g&&g>0?g:t.length,T=[];for(let _=0;_<c.length;_+=f){const v=c.slice(_,_+f).map((y,b)=>m[b].invoke(y,l[b])),d=await Promise.all(v);T.push(d)}return T.flat()}async stream(t,a){const{key:n,input:r}=t,c=this.runnables[n];if(c===void 0)throw new Error(`No runnable associated with key "${n}".`);return c.stream(r,a)}},$a=class extends H{static lc_name(){return"RunnableBranch"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;default;branches;constructor(t){super(t),this.branches=t.branches,this.default=t.default}static from(t){if(t.length<1)throw new Error("RunnableBranch requires at least one branch");const n=t.slice(0,-1).map(([c,u])=>[rt(c),rt(u)]),r=rt(t[t.length-1]);return new this({branches:n,default:r})}async _invoke(t,a,n){let r;for(let c=0;c<this.branches.length;c+=1){const[u,m]=this.branches[c];if(await u.invoke(t,G(a,{callbacks:n?.getChild(`condition:${c+1}`)}))){r=await m.invoke(t,G(a,{callbacks:n?.getChild(`branch:${c+1}`)}));break}}return r||(r=await this.default.invoke(t,G(a,{callbacks:n?.getChild("branch:default")}))),r}async invoke(t,a={}){return this._callWithConfig(this._invoke,t,a)}async*_streamIterator(t,a){const r=await(await Yt(a))?.handleChainStart(this.toJSON(),na(t,"input"),a?.runId,void 0,void 0,void 0,a?.runName);let c,u=!0,m;try{for(let l=0;l<this.branches.length;l+=1){const[g,f]=this.branches[l];if(await g.invoke(t,G(a,{callbacks:r?.getChild(`condition:${l+1}`)}))){m=await f.stream(t,G(a,{callbacks:r?.getChild(`branch:${l+1}`)}));for await(const _ of m)if(yield _,u)if(c===void 0)c=_;else try{c=ot(c,_)}catch{c=void 0,u=!1}break}}if(m===void 0){m=await this.default.stream(t,G(a,{callbacks:r?.getChild("branch:default")}));for await(const l of m)if(yield l,u)if(c===void 0)c=l;else try{c=ot(c,l)}catch{c=void 0,u=!1}}}catch(l){throw await r?.handleChainError(l),l}await r?.handleChainEnd(c??{})}},Za=class extends Jt{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(t){let a=It.from((u,m)=>this._enterHistory(u,m??{})).withConfig({runName:"loadHistory"});const n=t.historyMessagesKey??t.inputMessagesKey;n&&(a=ct.assign({[n]:a}).withConfig({runName:"insertHistory"}));const r=a.pipe(t.runnable.withListeners({onEnd:(u,m)=>this._exitHistory(u,m??{})})).withConfig({runName:"RunnableWithMessageHistory"}),c=t.config??{};super({...t,config:c,bound:r}),this.runnable=t.runnable,this.getMessageHistory=t.getMessageHistory,this.inputMessagesKey=t.inputMessagesKey,this.outputMessagesKey=t.outputMessagesKey,this.historyMessagesKey=t.historyMessagesKey}_getInputMessages(t){let a;if(typeof t=="object"&&!Array.isArray(t)&&!Y(t)){let n;this.inputMessagesKey?n=this.inputMessagesKey:Object.keys(t).length===1?n=Object.keys(t)[0]:n="input",Array.isArray(t[n])&&Array.isArray(t[n][0])?a=t[n][0]:a=t[n]}else a=t;if(typeof a=="string")return[new Ct(a)];if(Array.isArray(a))return a;if(Y(a))return[a];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.
2
+ Got ${JSON.stringify(a,null,2)}`)}_getOutputMessages(t){let a;if(!Array.isArray(t)&&!Y(t)&&typeof t!="string"){let n;this.outputMessagesKey!==void 0?n=this.outputMessagesKey:Object.keys(t).length===1?n=Object.keys(t)[0]:n="output",t.generations!==void 0?a=t.generations[0][0].message:a=t[n]}else a=t;if(typeof a=="string")return[new Xt(a)];if(Array.isArray(a))return a;if(Y(a))return[a];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(a,null,2)}`)}async _enterHistory(t,a){const r=await(a?.configurable?.messageHistory).getMessages();return this.historyMessagesKey===void 0?r.concat(this._getInputMessages(t)):r}async _exitHistory(t,a){const n=a.configurable?.messageHistory;let r;Array.isArray(t.inputs)&&Array.isArray(t.inputs[0])?r=t.inputs[0]:r=t.inputs;let c=this._getInputMessages(r);if(this.historyMessagesKey===void 0){const l=await n.getMessages();c=c.slice(l.length)}const u=t.outputs;if(!u)throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(t,null,2)}`);const m=this._getOutputMessages(u);await n.addMessages([...c,...m])}async _mergeConfig(...t){const a=await super._mergeConfig(...t);if(!a.configurable||!a.configurable.sessionId){const r={[this.inputMessagesKey??"input"]:"foo"},c={configurable:{sessionId:"123"}};throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()
3
+ eg. chain.invoke(${JSON.stringify(r)}, ${JSON.stringify(c)})`)}const{sessionId:n}=a.configurable;return a.configurable.messageHistory=await this.getMessageHistory(n),a}},Ha={};U(Ha,{RouterRunnable:()=>Ga,Runnable:()=>H,RunnableAssign:()=>Zt,RunnableBinding:()=>Jt,RunnableBranch:()=>$a,RunnableEach:()=>ma,RunnableLambda:()=>It,RunnableMap:()=>Ht,RunnableParallel:()=>ha,RunnablePassthrough:()=>ct,RunnablePick:()=>la,RunnableRetry:()=>ua,RunnableSequence:()=>Wt,RunnableToolLike:()=>ca,RunnableWithFallbacks:()=>oa,RunnableWithMessageHistory:()=>Za,_coerceToRunnable:()=>rt,ensureConfig:()=>it,getCallbackManagerForConfig:()=>Yt,mergeConfigs:()=>ia,patchConfig:()=>G,pickRunnableConfigKeys:()=>ra});var be=class extends H{parseResultWithPrompt(t,a,n){return this.parseResult(t,n)}_baseMessageToString(t){return typeof t.content=="string"?t.content:this._baseMessageContentToString(t.content)}_baseMessageContentToString(t){return JSON.stringify(t)}async invoke(t,a){return typeof t=="string"?this._callWithConfig(async(n,r)=>this.parseResult([{text:n}],r?.callbacks),t,{...a,runType:"parser"}):this._callWithConfig(async(n,r)=>this.parseResult([{message:n,text:this._baseMessageToString(n)}],r?.callbacks),t,{...a,runType:"parser"})}},mt=class extends be{parseResult(t,a){return this.parse(t[0].text,a)}async parseWithPrompt(t,a,n){return this.parse(t,n)}_type(){throw new Error("_type not implemented")}},Z=class extends Error{llmOutput;observation;sendToLLM;constructor(t,a,n,r=!1){if(super(t),this.llmOutput=a,this.observation=n,this.sendToLLM=r,r&&(n===void 0||a===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");fa(this,"OUTPUT_PARSING_FAILURE")}},q=class extends mt{async*_transform(t){for await(const a of t)typeof a=="string"?yield this.parseResult([{text:a}]):yield this.parseResult([{message:a,text:this._baseMessageToString(a)}])}async*transform(t,a){yield*this._transformStreamWithConfig(t,this._transform.bind(this),{...a,runType:"parser"})}},Nt=class extends q{diff=!1;constructor(t){super(t),this.diff=t?.diff??this.diff}async*_transform(t){let a,n;for await(const r of t){if(typeof r!="string"&&typeof r.content!="string")throw new Error("Cannot handle non-string output.");let c;if(pa(r)){if(typeof r.content!="string")throw new Error("Cannot handle non-string message output.");c=new Vt({message:r,text:r.content})}else if(Y(r)){if(typeof r.content!="string")throw new Error("Cannot handle non-string message output.");c=new Vt({message:ga(r),text:r.content})}else c=new da({text:r});n===void 0?n=c:n=n.concat(c);const u=await this.parsePartialResult([n]);u!=null&&!va(u,a)&&(this.diff?yield this._diff(a,u):yield u,a=u)}}getFormatInstructions(){return""}},Wa=class extends q{static lc_name(){return"BytesOutputParser"}lc_namespace=["langchain_core","output_parsers","bytes"];lc_serializable=!0;textEncoder=new TextEncoder;parse(t){return Promise.resolve(this.textEncoder.encode(t))}getFormatInstructions(){return""}},Q=class extends q{re;async*_transform(t){let a="";for await(const n of t)if(typeof n=="string"?a+=n:a+=n.content,this.re){const r=[...a.matchAll(this.re)];if(r.length>1){let c=0;for(const u of r.slice(0,-1))yield[u[1]],c+=(u.index??0)+u[0].length;a=a.slice(c)}}else{const r=await this.parse(a);if(r.length>1){for(const c of r.slice(0,-1))yield[c];a=r[r.length-1]}}for(const n of await this.parse(a))yield[n]}},Xa=class extends Q{static lc_name(){return"CommaSeparatedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;async parse(t){try{return t.trim().split(",").map(a=>a.trim())}catch{throw new Z(`Could not parse output: ${t}`,t)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},Ya=class extends Q{lc_namespace=["langchain_core","output_parsers","list"];length;separator;constructor({length:t,separator:a}){super(...arguments),this.length=t,this.separator=a||","}async parse(t){try{const a=t.trim().split(this.separator).map(n=>n.trim());if(this.length!==void 0&&a.length!==this.length)throw new Z(`Incorrect number of items. Expected ${this.length}, got ${a.length}.`);return a}catch(a){throw Object.getPrototypeOf(a)===Z.prototype?a:new Z(`Could not parse output: ${t}`)}}getFormatInstructions(){return`Your response should be a list of ${this.length===void 0?"":`${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`}},Ja=class extends Q{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
4
+
5
+ 1. foo
6
+
7
+ 2. bar
8
+
9
+ 3. baz`}re=/\d+\.\s([^\n]+)/g;async parse(t){return[...t.matchAll(this.re)??[]].map(a=>a[1])}},Ka=class extends Q{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
10
+
11
+ 1. foo
12
+
13
+ 2. bar
14
+
15
+ 3. baz`}re=/^\s*[-*]\s([^\n]+)$/gm;async parse(t){return[...t.matchAll(this.re)??[]].map(a=>a[1])}},qa=class extends q{static lc_name(){return"StrOutputParser"}lc_namespace=["langchain_core","output_parsers","string"];lc_serializable=!0;parse(t){return Promise.resolve(t)}getFormatInstructions(){return""}_textContentToString(t){return t.text}_imageUrlContentToString(t){throw new Error('Cannot coerce a multimodal "image_url" message part into a string.')}_messageContentToString(t){switch(t.type){case"text":case"text_delta":if("text"in t)return this._textContentToString(t);break;case"image_url":if("image_url"in t)return this._imageUrlContentToString(t);break;default:throw new Error(`Cannot coerce "${t.type}" message part into a string.`)}throw new Error(`Invalid content type: ${t.type}`)}_baseMessageContentToString(t){return t.reduce((a,n)=>a+this._messageContentToString(n),"")}},_e=class extends mt{static lc_name(){return"StructuredOutputParser"}lc_namespace=["langchain","output_parsers","structured"];toJSON(){return this.toJSONNotImplemented()}constructor(t){super(t),this.schema=t}static fromZodSchema(t){return new this(t)}static fromNamesAndDescriptions(t){const a=Kt(Object.fromEntries(Object.entries(t).map(([n,r])=>[n,qt().describe(r)])));return new this(a)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
16
+
17
+ "JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
18
+
19
+ For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
20
+ would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
21
+ Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
22
+
23
+ Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
24
+
25
+ Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
26
+ \`\`\`json
27
+ ${JSON.stringify(ut(this.schema))}
28
+ \`\`\`
29
+ `}async parse(t){try{const a=t.trim(),r=(a.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||a.match(/```json\s*([\s\S]*?)```/)?.[1]||a).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(c,u)=>`"${u.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await zt(this.schema,JSON.parse(r))}catch(a){throw new Z(`Failed to parse. Text: "${t}". Error: ${a}`,t)}}},ye=class extends _e{static lc_name(){return"JsonMarkdownStructuredOutputParser"}getFormatInstructions(t){const a=t?.interpolationDepth??1;if(a<1)throw new Error("f string interpolation depth must be at least 1");return`Return a markdown code snippet with a JSON object formatted to look like:
30
+ \`\`\`json
31
+ ${this._schemaToInstruction(ut(this.schema)).replaceAll("{","{".repeat(a)).replaceAll("}","}".repeat(a))}
32
+ \`\`\``}_schemaToInstruction(t,a=2){const n=t;if("type"in n){let r=!1,c;if(Array.isArray(n.type)){const l=n.type.findIndex(g=>g==="null");l!==-1&&(r=!0,n.type.splice(l,1)),c=n.type.join(" | ")}else c=n.type;if(n.type==="object"&&n.properties){const l=n.description?` // ${n.description}`:"";return`{
33
+ ${Object.entries(n.properties).map(([f,T])=>{const _=n.required?.includes(f)?"":" (optional)";return`${" ".repeat(a)}"${f}": ${this._schemaToInstruction(T,a+2)}${_}`}).join(`
34
+ `)}
35
+ ${" ".repeat(a-2)}}${l}`}if(n.type==="array"&&n.items){const l=n.description?` // ${n.description}`:"";return`array[
36
+ ${" ".repeat(a)}${this._schemaToInstruction(n.items,a+2)}
37
+ ${" ".repeat(a-2)}] ${l}`}const u=r?" (nullable)":"",m=n.description?` // ${n.description}`:"";return`${c}${m}${u}`}if("anyOf"in n)return n.anyOf.map(r=>this._schemaToInstruction(r,a)).join(`
38
+ ${" ".repeat(a-2)}`);throw new Error("unsupported schema type")}static fromZodSchema(t){return new this(t)}static fromNamesAndDescriptions(t){const a=Kt(Object.fromEntries(Object.entries(t).map(([n,r])=>[n,qt().describe(r)])));return new this(a)}},Qa=class extends mt{structuredInputParser;constructor({inputSchema:t}){super(...arguments),this.structuredInputParser=new ye(t)}async parse(t){let a;try{a=await this.structuredInputParser.parse(t)}catch(n){throw new Z(`Failed to parse. Text: "${t}". Error: ${n}`,t)}return this.outputProcessor(a)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}},ts={};U(ts,{applyPatch:()=>ba,compare:()=>St});var es=class extends Nt{static lc_name(){return"JsonOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_concatOutputChunks(t,a){return this.diff?super._concatOutputChunks(t,a):a}_diff(t,a){if(a)return t?St(t,a):[{op:"replace",path:"",value:a}]}async parsePartialResult(t){return Tt(t[0].text)}async parse(t){return Tt(t,JSON.parse)}getFormatInstructions(){return""}};const as=function(){const t={};t.parser=function(s,e){return new n(s,e)},t.SAXParser=n,t.SAXStream=f,t.createStream=g,t.MAX_BUFFER_LENGTH=64*1024;const a=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];t.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function n(s,e){if(!(this instanceof n))return new n(s,e);var h=this;c(h),h.q=h.c="",h.bufferCheckPosition=t.MAX_BUFFER_LENGTH,h.opt=e||{},h.opt.lowercase=h.opt.lowercase||h.opt.lowercasetags,h.looseCase=h.opt.lowercase?"toLowerCase":"toUpperCase",h.tags=[],h.closed=h.closedRoot=h.sawRoot=!1,h.tag=h.error=null,h.strict=!!s,h.noscript=!!(s||h.opt.noscript),h.state=o.BEGIN,h.strictEntities=h.opt.strictEntities,h.ENTITIES=h.strictEntities?Object.create(t.XML_ENTITIES):Object.create(t.ENTITIES),h.attribList=[],h.opt.xmlns&&(h.ns=Object.create(y)),h.trackPosition=h.opt.position!==!1,h.trackPosition&&(h.position=h.line=h.column=0),J(h,"onready")}Object.create||(Object.create=function(s){function e(){}e.prototype=s;var h=new e;return h}),Object.keys||(Object.keys=function(s){var e=[];for(var h in s)s.hasOwnProperty(h)&&e.push(h);return e});function r(s){for(var e=Math.max(t.MAX_BUFFER_LENGTH,10),h=0,i=0,C=a.length;i<C;i++){var N=s[a[i]].length;if(N>e)switch(a[i]){case"textNode":K(s);break;case"cdata":A(s,"oncdata",s.cdata),s.cdata="";break;case"script":A(s,"onscript",s.script),s.script="";break;default:tt(s,"Max buffer length exceeded: "+a[i])}h=Math.max(h,N)}var O=t.MAX_BUFFER_LENGTH-h;s.bufferCheckPosition=O+s.position}function c(s){for(var e=0,h=a.length;e<h;e++)s[a[e]]=""}function u(s){K(s),s.cdata!==""&&(A(s,"oncdata",s.cdata),s.cdata=""),s.script!==""&&(A(s,"onscript",s.script),s.script="")}n.prototype={end:function(){Pt(this)},write:we,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){u(this)}};var m=ReadableStream;m||(m=function(){});var l=t.EVENTS.filter(function(s){return s!=="error"&&s!=="end"});function g(s,e){return new f(s,e)}function f(s,e){if(!(this instanceof f))return new f(s,e);m.apply(this),this._parser=new n(s,e),this.writable=!0,this.readable=!0;var h=this;this._parser.onend=function(){h.emit("end")},this._parser.onerror=function(i){h.emit("error",i),h._parser.error=null},this._decoder=null,l.forEach(function(i){Object.defineProperty(h,"on"+i,{get:function(){return h._parser["on"+i]},set:function(C){if(!C)return h.removeAllListeners(i),h._parser["on"+i]=C,C;h.on(i,C)},enumerable:!0,configurable:!1})})}f.prototype=Object.create(m.prototype,{constructor:{value:f}}),f.prototype.write=function(s){return this._parser.write(s.toString()),this.emit("data",s),!0},f.prototype.end=function(s){return s&&s.length&&this.write(s),this._parser.end(),!0},f.prototype.on=function(s,e){var h=this;return!h._parser["on"+s]&&l.indexOf(s)!==-1&&(h._parser["on"+s]=function(){var i=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);i.splice(0,0,s),h.emit.apply(h,i)}),m.prototype.on.call(h,s,e)};var T="[CDATA[",_="DOCTYPE",v="http://www.w3.org/XML/1998/namespace",d="http://www.w3.org/2000/xmlns/",y={xml:v,xmlns:d},b=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,E=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,w=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,M=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function S(s){return s===" "||s===`
39
+ `||s==="\r"||s===" "}function R(s){return s==='"'||s==="'"}function D(s){return s===">"||S(s)}function j(s,e){return s.test(e)}function ve(s,e){return!j(s,e)}var o=0;t.STATE={BEGIN:o++,BEGIN_WHITESPACE:o++,TEXT:o++,TEXT_ENTITY:o++,OPEN_WAKA:o++,SGML_DECL:o++,SGML_DECL_QUOTED:o++,DOCTYPE:o++,DOCTYPE_QUOTED:o++,DOCTYPE_DTD:o++,DOCTYPE_DTD_QUOTED:o++,COMMENT_STARTING:o++,COMMENT:o++,COMMENT_ENDING:o++,COMMENT_ENDED:o++,CDATA:o++,CDATA_ENDING:o++,CDATA_ENDING_2:o++,PROC_INST:o++,PROC_INST_BODY:o++,PROC_INST_ENDING:o++,OPEN_TAG:o++,OPEN_TAG_SLASH:o++,ATTRIB:o++,ATTRIB_NAME:o++,ATTRIB_NAME_SAW_WHITE:o++,ATTRIB_VALUE:o++,ATTRIB_VALUE_QUOTED:o++,ATTRIB_VALUE_CLOSED:o++,ATTRIB_VALUE_UNQUOTED:o++,ATTRIB_VALUE_ENTITY_Q:o++,ATTRIB_VALUE_ENTITY_U:o++,CLOSE_TAG:o++,CLOSE_TAG_SAW_WHITE:o++,SCRIPT:o++,SCRIPT_ENDING:o++},t.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},t.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(t.ENTITIES).forEach(function(s){var e=t.ENTITIES[s],h=typeof e=="number"?String.fromCharCode(e):e;t.ENTITIES[s]=h});for(var Ot in t.STATE)t.STATE[t.STATE[Ot]]=Ot;o=t.STATE;function J(s,e,h){s[e]&&s[e](h)}function A(s,e,h){s.textNode&&K(s),J(s,e,h)}function K(s){s.textNode=kt(s.opt,s.textNode),s.textNode&&J(s,"ontext",s.textNode),s.textNode=""}function kt(s,e){return s.trim&&(e=e.trim()),s.normalize&&(e=e.replace(/\s+/g," ")),e}function tt(s,e){return K(s),s.trackPosition&&(e+=`
40
+ Line: `+s.line+`
41
+ Column: `+s.column+`
42
+ Char: `+s.c),e=new Error(e),s.error=e,J(s,"onerror",e),s}function Pt(s){return s.sawRoot&&!s.closedRoot&&I(s,"Unclosed root tag"),s.state!==o.BEGIN&&s.state!==o.BEGIN_WHITESPACE&&s.state!==o.TEXT&&tt(s,"Unexpected end"),K(s),s.c="",s.closed=!0,J(s,"onend"),n.call(s,s.strict,s.opt),s}function I(s,e){if(typeof s!="object"||!(s instanceof n))throw new Error("bad call to strictFail");s.strict&&tt(s,e)}function Ee(s){s.strict||(s.tagName=s.tagName[s.looseCase]());var e=s.tags[s.tags.length-1]||s,h=s.tag={name:s.tagName,attributes:{}};s.opt.xmlns&&(h.ns=e.ns),s.attribList.length=0,A(s,"onopentagstart",h)}function ft(s,e){var h=s.indexOf(":"),i=h<0?["",s]:s.split(":"),C=i[0],N=i[1];return e&&s==="xmlns"&&(C="xmlns",N=""),{prefix:C,local:N}}function pt(s){if(s.strict||(s.attribName=s.attribName[s.looseCase]()),s.attribList.indexOf(s.attribName)!==-1||s.tag.attributes.hasOwnProperty(s.attribName)){s.attribName=s.attribValue="";return}if(s.opt.xmlns){var e=ft(s.attribName,!0),h=e.prefix,i=e.local;if(h==="xmlns")if(i==="xml"&&s.attribValue!==v)I(s,"xml: prefix must be bound to "+v+`
43
+ Actual: `+s.attribValue);else if(i==="xmlns"&&s.attribValue!==d)I(s,"xmlns: prefix must be bound to "+d+`
44
+ Actual: `+s.attribValue);else{var C=s.tag,N=s.tags[s.tags.length-1]||s;C.ns===N.ns&&(C.ns=Object.create(N.ns)),C.ns[i]=s.attribValue}s.attribList.push([s.attribName,s.attribValue])}else s.tag.attributes[s.attribName]=s.attribValue,A(s,"onattribute",{name:s.attribName,value:s.attribValue});s.attribName=s.attribValue=""}function z(s,e){if(s.opt.xmlns){var h=s.tag,i=ft(s.tagName);h.prefix=i.prefix,h.local=i.local,h.uri=h.ns[i.prefix]||"",h.prefix&&!h.uri&&(I(s,"Unbound namespace prefix: "+JSON.stringify(s.tagName)),h.uri=i.prefix);var C=s.tags[s.tags.length-1]||s;h.ns&&C.ns!==h.ns&&Object.keys(h.ns).forEach(function(Dt){A(s,"onopennamespace",{prefix:Dt,uri:h.ns[Dt]})});for(var N=0,O=s.attribList.length;N<O;N++){var x=s.attribList[N],L=x[0],W=x[1],P=ft(L,!0),V=P.prefix,Ce=P.local,Lt=V===""?"":h.ns[V]||"",dt={name:L,value:W,prefix:V,local:Ce,uri:Lt};V&&V!=="xmlns"&&!Lt&&(I(s,"Unbound namespace prefix: "+JSON.stringify(V)),dt.uri=V),s.tag.attributes[L]=dt,A(s,"onattribute",dt)}s.attribList.length=0}s.tag.isSelfClosing=!!e,s.sawRoot=!0,s.tags.push(s.tag),A(s,"onopentag",s.tag),e||(!s.noscript&&s.tagName.toLowerCase()==="script"?s.state=o.SCRIPT:s.state=o.TEXT,s.tag=null,s.tagName=""),s.attribName=s.attribValue="",s.attribList.length=0}function gt(s){if(!s.tagName){I(s,"Weird empty close tag."),s.textNode+="</>",s.state=o.TEXT;return}if(s.script){if(s.tagName!=="script"){s.script+="</"+s.tagName+">",s.tagName="",s.state=o.SCRIPT;return}A(s,"onscript",s.script),s.script=""}var e=s.tags.length,h=s.tagName;s.strict||(h=h[s.looseCase]());for(var i=h;e--;){var C=s.tags[e];if(C.name!==i)I(s,"Unexpected close tag");else break}if(e<0){I(s,"Unmatched closing tag: "+s.tagName),s.textNode+="</"+s.tagName+">",s.state=o.TEXT;return}s.tagName=h;for(var N=s.tags.length;N-- >e;){var O=s.tag=s.tags.pop();s.tagName=s.tag.name,A(s,"onclosetag",s.tagName);var x={};for(var L in O.ns)x[L]=O.ns[L];var W=s.tags[s.tags.length-1]||s;s.opt.xmlns&&O.ns!==W.ns&&Object.keys(O.ns).forEach(function(P){var V=O.ns[P];A(s,"onclosenamespace",{prefix:P,uri:V})})}e===0&&(s.closedRoot=!0),s.tagName=s.attribValue=s.attribName="",s.attribList.length=0,s.state=o.TEXT}function Mt(s){var e=s.entity,h=e.toLowerCase(),i,C="";return s.ENTITIES[e]?s.ENTITIES[e]:s.ENTITIES[h]?s.ENTITIES[h]:(e=h,e.charAt(0)==="#"&&(e.charAt(1)==="x"?(e=e.slice(2),i=parseInt(e,16),C=i.toString(16)):(e=e.slice(1),i=parseInt(e,10),C=i.toString(10))),e=e.replace(/^0+/,""),isNaN(i)||C.toLowerCase()!==e?(I(s,"Invalid character entity"),"&"+s.entity+";"):String.fromCodePoint(i))}function xt(s,e){e==="<"?(s.state=o.OPEN_WAKA,s.startTagPosition=s.position):S(e)||(I(s,"Non-whitespace before first tag."),s.textNode=e,s.state=o.TEXT)}function Rt(s,e){var h="";return e<s.length&&(h=s.charAt(e)),h}function we(s){var e=this;if(this.error)throw this.error;if(e.closed)return tt(e,"Cannot write after close. Assign an onready handler.");if(s===null)return Pt(e);typeof s=="object"&&(s=s.toString());for(var h=0,i="";i=Rt(s,h++),e.c=i,!!i;)switch(e.trackPosition&&(e.position++,i===`
45
+ `?(e.line++,e.column=0):e.column++),e.state){case o.BEGIN:if(e.state=o.BEGIN_WHITESPACE,i==="\uFEFF")continue;xt(e,i);continue;case o.BEGIN_WHITESPACE:xt(e,i);continue;case o.TEXT:if(e.sawRoot&&!e.closedRoot){for(var C=h-1;i&&i!=="<"&&i!=="&";)i=Rt(s,h++),i&&e.trackPosition&&(e.position++,i===`
46
+ `?(e.line++,e.column=0):e.column++);e.textNode+=s.substring(C,h-1)}i==="<"&&!(e.sawRoot&&e.closedRoot&&!e.strict)?(e.state=o.OPEN_WAKA,e.startTagPosition=e.position):(!S(i)&&(!e.sawRoot||e.closedRoot)&&I(e,"Text data outside of root node."),i==="&"?e.state=o.TEXT_ENTITY:e.textNode+=i);continue;case o.SCRIPT:i==="<"?e.state=o.SCRIPT_ENDING:e.script+=i;continue;case o.SCRIPT_ENDING:i==="/"?e.state=o.CLOSE_TAG:(e.script+="<"+i,e.state=o.SCRIPT);continue;case o.OPEN_WAKA:if(i==="!")e.state=o.SGML_DECL,e.sgmlDecl="";else if(!S(i))if(j(b,i))e.state=o.OPEN_TAG,e.tagName=i;else if(i==="/")e.state=o.CLOSE_TAG,e.tagName="";else if(i==="?")e.state=o.PROC_INST,e.procInstName=e.procInstBody="";else{if(I(e,"Unencoded <"),e.startTagPosition+1<e.position){var N=e.position-e.startTagPosition;i=new Array(N).join(" ")+i}e.textNode+="<"+i,e.state=o.TEXT}continue;case o.SGML_DECL:(e.sgmlDecl+i).toUpperCase()===T?(A(e,"onopencdata"),e.state=o.CDATA,e.sgmlDecl="",e.cdata=""):e.sgmlDecl+i==="--"?(e.state=o.COMMENT,e.comment="",e.sgmlDecl=""):(e.sgmlDecl+i).toUpperCase()===_?(e.state=o.DOCTYPE,(e.doctype||e.sawRoot)&&I(e,"Inappropriately located doctype declaration"),e.doctype="",e.sgmlDecl=""):i===">"?(A(e,"onsgmldeclaration",e.sgmlDecl),e.sgmlDecl="",e.state=o.TEXT):(R(i)&&(e.state=o.SGML_DECL_QUOTED),e.sgmlDecl+=i);continue;case o.SGML_DECL_QUOTED:i===e.q&&(e.state=o.SGML_DECL,e.q=""),e.sgmlDecl+=i;continue;case o.DOCTYPE:i===">"?(e.state=o.TEXT,A(e,"ondoctype",e.doctype),e.doctype=!0):(e.doctype+=i,i==="["?e.state=o.DOCTYPE_DTD:R(i)&&(e.state=o.DOCTYPE_QUOTED,e.q=i));continue;case o.DOCTYPE_QUOTED:e.doctype+=i,i===e.q&&(e.q="",e.state=o.DOCTYPE);continue;case o.DOCTYPE_DTD:e.doctype+=i,i==="]"?e.state=o.DOCTYPE:R(i)&&(e.state=o.DOCTYPE_DTD_QUOTED,e.q=i);continue;case o.DOCTYPE_DTD_QUOTED:e.doctype+=i,i===e.q&&(e.state=o.DOCTYPE_DTD,e.q="");continue;case o.COMMENT:i==="-"?e.state=o.COMMENT_ENDING:e.comment+=i;continue;case o.COMMENT_ENDING:i==="-"?(e.state=o.COMMENT_ENDED,e.comment=kt(e.opt,e.comment),e.comment&&A(e,"oncomment",e.comment),e.comment=""):(e.comment+="-"+i,e.state=o.COMMENT);continue;case o.COMMENT_ENDED:i!==">"?(I(e,"Malformed comment"),e.comment+="--"+i,e.state=o.COMMENT):e.state=o.TEXT;continue;case o.CDATA:i==="]"?e.state=o.CDATA_ENDING:e.cdata+=i;continue;case o.CDATA_ENDING:i==="]"?e.state=o.CDATA_ENDING_2:(e.cdata+="]"+i,e.state=o.CDATA);continue;case o.CDATA_ENDING_2:i===">"?(e.cdata&&A(e,"oncdata",e.cdata),A(e,"onclosecdata"),e.cdata="",e.state=o.TEXT):i==="]"?e.cdata+="]":(e.cdata+="]]"+i,e.state=o.CDATA);continue;case o.PROC_INST:i==="?"?e.state=o.PROC_INST_ENDING:S(i)?e.state=o.PROC_INST_BODY:e.procInstName+=i;continue;case o.PROC_INST_BODY:if(!e.procInstBody&&S(i))continue;i==="?"?e.state=o.PROC_INST_ENDING:e.procInstBody+=i;continue;case o.PROC_INST_ENDING:i===">"?(A(e,"onprocessinginstruction",{name:e.procInstName,body:e.procInstBody}),e.procInstName=e.procInstBody="",e.state=o.TEXT):(e.procInstBody+="?"+i,e.state=o.PROC_INST_BODY);continue;case o.OPEN_TAG:j(E,i)?e.tagName+=i:(Ee(e),i===">"?z(e):i==="/"?e.state=o.OPEN_TAG_SLASH:(S(i)||I(e,"Invalid character in tag name"),e.state=o.ATTRIB));continue;case o.OPEN_TAG_SLASH:i===">"?(z(e,!0),gt(e)):(I(e,"Forward-slash in opening tag not followed by >"),e.state=o.ATTRIB);continue;case o.ATTRIB:if(S(i))continue;i===">"?z(e):i==="/"?e.state=o.OPEN_TAG_SLASH:j(b,i)?(e.attribName=i,e.attribValue="",e.state=o.ATTRIB_NAME):I(e,"Invalid attribute name");continue;case o.ATTRIB_NAME:i==="="?e.state=o.ATTRIB_VALUE:i===">"?(I(e,"Attribute without value"),e.attribValue=e.attribName,pt(e),z(e)):S(i)?e.state=o.ATTRIB_NAME_SAW_WHITE:j(E,i)?e.attribName+=i:I(e,"Invalid attribute name");continue;case o.ATTRIB_NAME_SAW_WHITE:if(i==="=")e.state=o.ATTRIB_VALUE;else{if(S(i))continue;I(e,"Attribute without value"),e.tag.attributes[e.attribName]="",e.attribValue="",A(e,"onattribute",{name:e.attribName,value:""}),e.attribName="",i===">"?z(e):j(b,i)?(e.attribName=i,e.state=o.ATTRIB_NAME):(I(e,"Invalid attribute name"),e.state=o.ATTRIB)}continue;case o.ATTRIB_VALUE:if(S(i))continue;R(i)?(e.q=i,e.state=o.ATTRIB_VALUE_QUOTED):(I(e,"Unquoted attribute value"),e.state=o.ATTRIB_VALUE_UNQUOTED,e.attribValue=i);continue;case o.ATTRIB_VALUE_QUOTED:if(i!==e.q){i==="&"?e.state=o.ATTRIB_VALUE_ENTITY_Q:e.attribValue+=i;continue}pt(e),e.q="",e.state=o.ATTRIB_VALUE_CLOSED;continue;case o.ATTRIB_VALUE_CLOSED:S(i)?e.state=o.ATTRIB:i===">"?z(e):i==="/"?e.state=o.OPEN_TAG_SLASH:j(b,i)?(I(e,"No whitespace between attributes"),e.attribName=i,e.attribValue="",e.state=o.ATTRIB_NAME):I(e,"Invalid attribute name");continue;case o.ATTRIB_VALUE_UNQUOTED:if(!D(i)){i==="&"?e.state=o.ATTRIB_VALUE_ENTITY_U:e.attribValue+=i;continue}pt(e),i===">"?z(e):e.state=o.ATTRIB;continue;case o.CLOSE_TAG:if(e.tagName)i===">"?gt(e):j(E,i)?e.tagName+=i:e.script?(e.script+="</"+e.tagName,e.tagName="",e.state=o.SCRIPT):(S(i)||I(e,"Invalid tagname in closing tag"),e.state=o.CLOSE_TAG_SAW_WHITE);else{if(S(i))continue;ve(b,i)?e.script?(e.script+="</"+i,e.state=o.SCRIPT):I(e,"Invalid tagname in closing tag."):e.tagName=i}continue;case o.CLOSE_TAG_SAW_WHITE:if(S(i))continue;i===">"?gt(e):I(e,"Invalid characters in closing tag");continue;case o.TEXT_ENTITY:case o.ATTRIB_VALUE_ENTITY_Q:case o.ATTRIB_VALUE_ENTITY_U:var O,x;switch(e.state){case o.TEXT_ENTITY:O=o.TEXT,x="textNode";break;case o.ATTRIB_VALUE_ENTITY_Q:O=o.ATTRIB_VALUE_QUOTED,x="attribValue";break;case o.ATTRIB_VALUE_ENTITY_U:O=o.ATTRIB_VALUE_UNQUOTED,x="attribValue";break}if(i===";")if(e.opt.unparsedEntities){var L=Mt(e);e.entity="",e.state=O,e.write(L)}else e[x]+=Mt(e),e.entity="",e.state=O;else j(e.entity.length?M:w,i)?e.entity+=i:(I(e,"Invalid character in entity name"),e[x]+="&"+e.entity+i,e.entity="",e.state=O);continue;default:throw new Error(e,"Unknown state: "+e.state)}return e.position>=e.bufferCheckPosition&&r(e),e}return String.fromCodePoint||(function(){var s=String.fromCharCode,e=Math.floor,h=function(){var i=16384,C=[],N,O,x=-1,L=arguments.length;if(!L)return"";for(var W="";++x<L;){var P=Number(arguments[x]);if(!isFinite(P)||P<0||P>1114111||e(P)!==P)throw RangeError("Invalid code point: "+P);P<=65535?C.push(P):(P-=65536,N=(P>>10)+55296,O=P%1024+56320,C.push(N,O)),(x+1===L||C.length>i)&&(W+=s.apply(null,C),C.length=0)}return W};Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:h,configurable:!0,writable:!0}):String.fromCodePoint=h})(),t},ss=as(),vt=`The output should be formatted as a XML file.
47
+ 1. Output should conform to the tags below.
48
+ 2. If tags are not given, make them on your own.
49
+ 3. Remember to always open and close all the tags.
50
+
51
+ As an example, for the tags ["foo", "bar", "baz"]:
52
+ 1. String "<foo>
53
+ <bar>
54
+ <baz></baz>
55
+ </bar>
56
+ </foo>" is a well-formatted instance of the schema.
57
+ 2. String "<foo>
58
+ <bar>
59
+ </foo>" is a badly-formatted instance.
60
+ 3. String "<foo>
61
+ <tag>
62
+ </tag>
63
+ </foo>" is a badly-formatted instance.
64
+
65
+ Here are the output tags:
66
+ \`\`\`
67
+ {tags}
68
+ \`\`\``;var ns=class extends Nt{tags;constructor(t){super(t),this.tags=t?.tags}static lc_name(){return"XMLOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_diff(t,a){if(a)return t?St(t,a):[{op:"replace",path:"",value:a}]}async parsePartialResult(t){return Et(t[0].text)}async parse(t){return Et(t)}getFormatInstructions(){return!!(this.tags&&this.tags.length>0)?vt.replace("{tags}",this.tags?.join(", ")??""):vt}};const rs=t=>t.split(`
69
+ `).map(a=>a.replace(/^\s+/,"")).join(`
70
+ `).trim(),Te=t=>{if(Object.keys(t).length===0)return{};const a={};return t.children.length>0?(a[t.name]=t.children.map(Te),a):(a[t.name]=t.text??void 0,a)};function Et(t){const a=rs(t),n=ss.parser(!0);let r={};const c=[];n.onopentag=l=>{const g={name:l.name,attributes:l.attributes,children:[],text:"",isSelfClosing:l.isSelfClosing};c.length>0?c[c.length-1].children.push(g):r=g,l.isSelfClosing||c.push(g)},n.onclosetag=()=>{if(c.length>0){const l=c.pop();c.length===0&&l&&(r=l)}},n.ontext=l=>{if(c.length>0){const g=c[c.length-1];g.text+=l}},n.onattribute=l=>{if(c.length>0){const g=c[c.length-1];g.attributes[l.name]=l.value}};const u=/```(xml)?(.*)```/s.exec(a),m=u?u[2]:a;return n.write(m).close(),r&&r.name==="?xml"&&(r=r.children[0]),Te(r)}var is={};U(is,{AsymmetricStructuredOutputParser:()=>Qa,BaseCumulativeTransformOutputParser:()=>Nt,BaseLLMOutputParser:()=>be,BaseOutputParser:()=>mt,BaseTransformOutputParser:()=>q,BytesOutputParser:()=>Wa,CommaSeparatedListOutputParser:()=>Xa,CustomListOutputParser:()=>Ya,JsonMarkdownStructuredOutputParser:()=>ye,JsonOutputParser:()=>es,ListOutputParser:()=>Q,MarkdownListOutputParser:()=>Ka,NumberedListOutputParser:()=>Ja,OutputParserException:()=>Z,StringOutputParser:()=>qa,StructuredOutputParser:()=>_e,XMLOutputParser:()=>ns,XML_FORMAT_INSTRUCTIONS:()=>vt,parseJsonMarkdown:()=>Tt,parsePartialJson:()=>_a,parseXMLMarkdown:()=>Et});export{be as B,es as J,Z as O,ct as R,_e as S,Fa as a,de as b,Ca as c,Nt as d,ge as e,ae as f,te as g,ee as h,se as i,pe as j};