Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🪬 feat: Configure Langfuse Trace User Identity and Metadata (#15667)

Danny Avilab181ef02323a
diff --git a/api/package.json b/api/package.json
index a8eba00ab7..7fa65a7ea7 100644
--- a/api/package.json
+++ b/api/package.json
@@ -46,7 +46,7 @@
"@azure/storage-blob": "^12.30.0",
"@google/genai": "^2.8.0",
"@keyv/redis": "5.1.6",
- "@librechat/agents": "^3.7.21",
+ "@librechat/agents": "^3.8.0",
"@librechat/api": "*",
"@librechat/data-schemas": "*",
"@microsoft/microsoft-graph-client": "^3.0.7",
diff --git a/api/server/controllers/agents/__tests__/client.traceContext.spec.js b/api/server/controllers/agents/__tests__/client.traceContext.spec.js
new file mode 100644
index 0000000000..3377c026ba
--- /dev/null
+++ b/api/server/controllers/agents/__tests__/client.traceContext.spec.js
@@ -0,0 +1,38 @@
+const AgentClient = require('../client');
+
+const { buildTraceContext } = AgentClient;
+
+describe('AgentClient.buildTraceContext', () => {
+ it('reads the model label from the trace-only option the initializer sets', () => {
+ expect(
+ buildTraceContext({
+ endpoint: 'agents',
+ endpointType: undefined,
+ spec: 'support-bot',
+ traceContext: { modelLabel: 'Helper' },
+ }),
+ ).toEqual({
+ endpoint: 'agents',
+ endpointType: undefined,
+ modelLabel: 'Helper',
+ spec: 'support-bot',
+ });
+ });
+
+ it('falls back to a top-level modelLabel option when no trace context is given', () => {
+ expect(buildTraceContext({ endpoint: 'openAI', modelLabel: 'Custom' })).toMatchObject({
+ endpoint: 'openAI',
+ modelLabel: 'Custom',
+ });
+ expect(buildTraceContext({ endpoint: 'openAI' }).modelLabel).toBeUndefined();
+ });
+
+ it('tolerates a client context without options', () => {
+ expect(buildTraceContext(undefined)).toEqual({
+ endpoint: undefined,
+ endpointType: undefined,
+ modelLabel: undefined,
+ spec: undefined,
+ });
+ });
+});
diff --git a/api/server/controllers/agents/__tests__/openai.spec.js b/api/server/controllers/agents/__tests__/openai.spec.js
index 8c8960b2d5..5a764ef7cc 100644
--- a/api/server/controllers/agents/__tests__/openai.spec.js
+++ b/api/server/controllers/agents/__tests__/openai.spec.js
@@ -628,7 +628,11 @@ describe('OpenAIChatCompletionController', () => {
);
const { createRun } = require('@librechat/api');
expect(createRun).toHaveBeenCalledWith(
- expect.objectContaining({ initialSessions: mockInitialSessions }),
+ expect.objectContaining({
+ initialSessions: mockInitialSessions,
+ user: expect.objectContaining({ id: 'user-123' }),
+ traceContext: { endpoint: 'agents' },
+ }),
);
expect(createSubagentUsageSink).toHaveBeenCalledWith(expect.any(Array));
});
diff --git a/api/server/controllers/agents/__tests__/responses.unit.spec.js b/api/server/controllers/agents/__tests__/responses.unit.spec.js
index 5ea0d8628a..31421b3644 100644
--- a/api/server/controllers/agents/__tests__/responses.unit.spec.js
+++ b/api/server/controllers/agents/__tests__/responses.unit.spec.js
@@ -709,7 +709,11 @@ describe('createResponse controller', () => {
);
const { createRun } = require('@librechat/api');
expect(createRun).toHaveBeenCalledWith(
- expect.objectContaining({ initialSessions: mockInitialSessions }),
+ expect.objectContaining({
+ initialSessions: mockInitialSessions,
+ user: expect.objectContaining({ id: 'user-123' }),
+ traceContext: { endpoint: 'agents' },
+ }),
);
});
diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.js
index 5a2e93ba68..b9df554879 100644
--- a/api/server/controllers/agents/client.js
+++ b/api/server/controllers/agents/client.js
@@ -249,6 +249,24 @@ function normalizeEventActorContextMeta(contextMeta) {
* tier and the per-agent map are both passed; the SDK restores each agent from
* its own entry and falls back to the default tier for the first agent.
*/
+/**
+ * Request values `langfuse.trace.conversationMetadataFields` may export.
+ * The model label rides the trace-only `options.traceContext`: the
+ * initialized agent's `model_parameters` drop it (`extractLibreChatParams`),
+ * and a top-level `modelLabel` option would also rename the assistant in
+ * formatted messages. A module function rather than a method so partial
+ * client contexts (tests, resume) need no prototype.
+ * @param {AgentClient['options'] | undefined} options
+ */
+function buildTraceContext(options) {
+ return {
+ endpoint: options?.endpoint,
+ endpointType: options?.endpointType,
+ modelLabel: options?.traceContext?.modelLabel ?? options?.modelLabel,
+ spec: options?.spec,
+ };
+}
+
function resolveRunSeeds(client) {
const prevMeta = client.contextMeta;
if (prevMeta == null) {
@@ -4391,6 +4409,7 @@ class AgentClient extends BaseClient {
customHandlers: reasoningLabel?.handlers(activityHandlers) ?? activityHandlers,
requestBody: config.configurable.requestBody,
user: createSafeUser(this.options.req?.user),
+ traceContext: buildTraceContext(this.options),
tenantId: resolveRequestTenantId(this.options.req ?? {}),
summarizationConfig: appConfig?.summarization,
appConfig,
@@ -4925,6 +4944,7 @@ class AgentClient extends BaseClient {
customHandlers: reasoningLabel?.handlers(activityHandlers) ?? activityHandlers,
requestBody: config.configurable.requestBody,
user: createSafeUser(this.options.req?.user),
+ traceContext: buildTraceContext(this.options),
tenantId: resolveRequestTenantId(this.options.req ?? {}),
summarizationConfig: appConfig?.summarization,
appConfig,
@@ -5434,4 +5454,6 @@ class AgentClient extends BaseClient {
}
}
+AgentClient.buildTraceContext = buildTraceContext;
+
module.exports = AgentClient;
diff --git a/api/server/controllers/agents/openai.js b/api/server/controllers/agents/openai.js
index de275905ad..0706e42cdb 100644
--- a/api/server/controllers/agents/openai.js
+++ b/api/server/controllers/agents/openai.js
@@ -1072,7 +1072,8 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {
signal: execution.signal,
customHandlers: handlers,
requestBody: mcpRequestBody,
- user: { id: userId },
+ user: { ...createSafeUser(req.user), id: userId },
+ traceContext: { endpoint: EModelEndpoint.agents },
tenantId: principal.tenantId,
/** Bills subagent child-run model calls (reported outside the
* streamEvents loop) into the same collectedUsage array. */
diff --git a/api/server/controllers/agents/responses.js b/api/server/controllers/agents/responses.js
index c3632f89c6..0056598338 100644
--- a/api/server/controllers/agents/responses.js
+++ b/api/server/controllers/agents/responses.js
@@ -1185,7 +1185,8 @@ const executeResponse = async (envelope, { req, res }) => {
customHandlers: handlers,
initialSessions,
requestBody: mcpRequestBody,
- user: { id: userId },
+ user: { ...createSafeUser(req.user), id: userId },
+ traceContext: { endpoint: EModelEndpoint.agents },
tenantId: principal.tenantId,
/** Bills subagent child-run model calls (reported outside the
* streamEvents loop) into the same collectedUsage array. */
@@ -1397,7 +1398,8 @@ const executeResponse = async (envelope, { req, res }) => {
customHandlers: handlers,
initialSessions,
requestBody: mcpRequestBody,
- user: { id: userId },
+ user: { ...createSafeUser(req.user), id: userId },
+ traceContext: { endpoint: EModelEndpoint.agents },
tenantId: principal.tenantId,
/** Bills subagent child-run model calls (reported outside the
* streamEvents loop) into the same collectedUsage array. */
diff --git a/api/server/services/Endpoints/agents/initialize.js b/api/server/services/Endpoints/agents/initialize.js
index 764d1f0277..98bc05191a 100644
--- a/api/server/services/Endpoints/agents/initialize.js
+++ b/api/server/services/Endpoints/agents/initialize.js
@@ -1601,6 +1601,7 @@ const initializeClient = async ({
invokedSkillIdentities,
agent: primaryConfig,
spec: endpointOption.spec,
+ traceContext: { modelLabel: endpointOption.model_parameters?.modelLabel },
iconURL: endpointOption.iconURL,
chatProjectId: endpointOption.chatProjectId,
attachments: primaryConfig.requestAttachments ?? primaryConfig.attachments,
diff --git a/librechat.example.yaml b/librechat.example.yaml
index 1ae4800d4e..c6b25bda42 100644
--- a/librechat.example.yaml
+++ b/librechat.example.yaml
@@ -36,10 +36,24 @@ cache: true
# only Authorization upstream, so a tenant Langfuse behind its own proxy is not
# covered even when the collector receives these.
#
+# Traces carry the internal user id as the Langfuse userId and no user or
+# request metadata unless langfuse.trace opts in. userIdField picks the user
+# field that becomes the trace userId (id, email, username, name, openidId,
+# samlId, ldapId, googleId, githubId, discordId, appleId, facebookId); a user
+# without a value for that field keeps the internal id. The two allowlists copy
+# fields into trace metadata as librechat.user.<field> (the userId fields plus
+# role and provider) and librechat.conversation.id, librechat.endpoint,
+# librechat.endpoint.type, librechat.provider, librechat.model,
+# librechat.model.label, librechat.spec.
+#
# langfuse:
# headers:
# CF-Access-Client-Id: "${CF_ACCESS_CLIENT_ID}"
# CF-Access-Client-Secret: "${CF_ACCESS_CLIENT_SECRET}"
+# trace:
+# userIdField: email
+# userMetadataFields: [email, username, role, provider]
+# conversationMetadataFields: [conversationId, endpoint, model, modelLabel, spec]
# File storage configuration
# Single strategy for all file types (legacy format, still supported)
diff --git a/package-lock.json b/package-lock.json
index d874a2565f..0532220708 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -65,7 +65,7 @@
"@azure/storage-blob": "^12.30.0",
"@google/genai": "^2.8.0",
"@keyv/redis": "5.1.6",
- "@librechat/agents": "^3.7.21",
+ "@librechat/agents": "^3.8.0",
"@librechat/api": "*",
"@librechat/data-schemas": "*",
"@microsoft/microsoft-graph-client": "^3.0.7",
@@ -11157,9 +11157,9 @@
}
},
"node_modules/@librechat/agents": {
- "version": "3.7.21",
- "resolved": "https://registry.npmjs.org/@librechat/agents/-/agents-3.7.21.tgz",
- "integrity": "sha512-n0dd7Xzh8Rnx4TGYBOqSGzSBoDMwyV28710Xn/q/Id6p7Z0CEnv4sLuQTHR1UMvhmOHs4kz2/pYynnaz60WbaA==",
+ "version": "3.8.0",
+ "resolved": "https://registry.npmjs.org/@librechat/agents/-/agents-3.8.0.tgz",
+ "integrity": "sha512-d3MGLuxin2RRzOilqE2i9pAMYutKpYVhffm7AE5Q770Ai4Y6+xrHO8vlaRCy7hACUlM92mx1c2553maH9ID3rg==",
"license": "MIT",
"dependencies": {
"@anthropic-ai/sdk": "^0.115.0",
@@ -44824,7 +44824,7 @@
"@azure/storage-blob": "^12.30.0",
"@google/genai": "^2.8.0",
"@keyv/redis": "5.1.6",
- "@librechat/agents": "^3.7.21",
+ "@librechat/agents": "^3.8.0",
"@librechat/data-schemas": "*",
"@modelcontextprotocol/sdk": "^1.30.0",
"@opentelemetry/api": "^1.9.0",
diff --git a/packages/api/package.json b/packages/api/package.json
index 55a48f2495..38365831f7 100644
--- a/packages/api/package.json
+++ b/packages/api/package.json
@@ -114,7 +114,7 @@
"@azure/storage-blob": "^12.30.0",
"@google/genai": "^2.8.0",
"@keyv/redis": "5.1.6",
- "@librechat/agents": "^3.7.21",
+ "@librechat/agents": "^3.8.0",
"@librechat/data-schemas": "*",
"@modelcontextprotocol/sdk": "^1.30.0",
"@opentelemetry/api": "^1.9.0",
diff --git a/packages/api/src/agents/__tests__/run-summarization.test.ts b/packages/api/src/agents/__tests__/run-summarization.test.ts
index 6d3e923f23..f728ed4918 100644
--- a/packages/api/src/agents/__tests__/run-summarization.test.ts
+++ b/packages/api/src/agents/__tests__/run-summarization.test.ts
@@ -2509,6 +2509,45 @@ describe('Langfuse run config', () => {
});
});
+ it('forwards the requesting user and trace context into the Langfuse run config', async () => {
+ await createRun({
+ agents: [makeAgent()] as never,
+ signal: new AbortController().signal,
+ streaming: true,
+ streamUsage: true,
+ user: { id: 'user-1', email: '[email protected]', role: 'ADMIN' } as never,
+ conversationId: 'convo-1',
+ requestBody: { conversationId: 'convo-stale' },
+ traceContext: { endpoint: 'agents', spec: 'support-bot' },
+ appConfig: {
+ langfuse: {
+ trace: {
+ userIdField: 'email',
+ userMetadataFields: ['role'],
+ conversationMetadataFields: ['conversationId', 'endpoint', 'provider', 'model', 'spec'],
+ },
+ },
+ } as unknown as AppConfig,
+ });
+
+ const createMock = Run.create as jest.Mock;
+ expect(createMock).toHaveBeenCalledTimes(1);
+ const callArgs = createMock.mock.calls[0][0] as Record<string, unknown>;
+ expect(callArgs.langfuse).toEqual({
+ deterministicTraceId: true,
+ userId: '[email protected]',
+ metadata: {
+ 'librechat.user.role': 'ADMIN',
+ 'librechat.conversation.id': 'convo-1',
+ 'librechat.endpoint': 'agents',
+ 'librechat.provider': 'openAI',
+ 'librechat.model': 'gpt-4o',
+ 'librechat.spec': 'support-bot',
+ },
+ librechatTraceAttributes: exportTelemetry('central_only', 'fanout_disabled'),
+ });
+ });
+
it('adds tenant Langfuse credentials from tenant-scoped app config', async () => {
process.env.LANGFUSE_FANOUT_ENABLED = 'true';
process.env.LANGFUSE_FANOUT_COLLECTOR_URL = 'http://langfuse-fanout-collector:4318';
diff --git a/packages/api/src/agents/openai/service.ts b/packages/api/src/agents/openai/service.ts
index 9713486b9d..eb5e7ddad7 100644
--- a/packages/api/src/agents/openai/service.ts
+++ b/packages/api/src/agents/openai/service.ts
@@ -19,7 +19,7 @@
* ```
*/
import { nanoid } from 'nanoid';
-import { AgentCapabilities } from 'librechat-data-provider';
+import { AgentCapabilities, EModelEndpoint } from 'librechat-data-provider';
import type {
FiltersConfig,
MessageFilterConfig,
@@ -46,6 +46,7 @@ import type {
} from '~/protection';
import type { InitializeAgentParams as CoreInitializeAgentParams } from '../initialize';
import type { OpenAIStreamHandlerConfig, EventHandler } from './handlers';
+import type { LangfuseTraceContext } from '~/langfuse/identity';
import type { MCPRuntimeRequestBody } from '~/mcp/request';
import type { ToolExecuteOptions } from '../handlers';
import {
@@ -256,6 +257,7 @@ type CreateRunFn = (params: {
customHandlers: Record<string, EventHandler>;
requestBody: Record<string, unknown>;
user: Record<string, unknown>;
+ traceContext?: LangfuseTraceContext;
tenantId?: string;
appConfig?: CreateRunAppConfig;
tokenCounter?: (message: unknown) => number;
@@ -800,6 +802,7 @@ export async function createAgentChatCompletion(
customHandlers: eventHandlers,
requestBody: mcpRequestBody,
user: safeUser,
+ traceContext: { endpoint: EModelEndpoint.agents },
tenantId: typeof reqUser?.tenantId === 'string' ? reqUser.tenantId : undefined,
appConfig: selectCreateRunAppConfig(deps.appConfig),
});
diff --git a/packages/api/src/agents/run.ts b/packages/api/src/agents/run.ts
index 66bb4f4fca..28ff2dc40c 100644
--- a/packages/api/src/agents/run.ts
+++ b/packages/api/src/agents/run.ts
@@ -50,6 +50,7 @@ import type { ModelBoundChatModelCallback } from '~/middleware/modelBoundContent
import type { ToolInputValidationError } from '~/agents/toolValidation';
import type { ResolvedToolApprovalHook } from '~/agents/hitl/hooks';
import type { TerminalSteerHook } from '~/agents/steering/runtime';
+import type { LangfuseTraceContext } from '~/langfuse/identity';
import type { ResolvedAlwaysApplySkill } from '~/agents/skills';
import type { CodeExecutionContext } from '~/agents/execution';
import type { MCPToolAlias } from '~/tools/classification';
@@ -1521,6 +1522,27 @@ function buildSubagentConfigs(
* their defer_loading overridden to false, preventing redundant re-discovery.
* @returns {Promise<Run<IState>>} A promise that resolves to a new Run instance.
*/
+/** The caller's trace context over run-derived defaults for the fields it left unset. */
+function resolveRunTraceContext({
+ agents,
+ conversationId,
+ requestBody,
+ traceContext,
+}: {
+ agents: RunAgent[];
+ conversationId?: string;
+ requestBody?: t.RequestBody;
+ traceContext?: LangfuseTraceContext;
+}): LangfuseTraceContext {
+ const primaryAgent = agents[0];
+ return {
+ ...traceContext,
+ conversationId: traceContext?.conversationId ?? conversationId ?? requestBody?.conversationId,
+ provider: traceContext?.provider ?? primaryAgent?.provider,
+ model: traceContext?.model ?? primaryAgent?.model_parameters?.model ?? primaryAgent?.model,
+ };
+}
+
export async function createRun({
runId,
signal,
@@ -1532,6 +1554,7 @@ export async function createRun({
user,
tenantId,
centralTraceExportEnabled,
+ traceContext,
tokenCounter,
customHandlers,
indexTokenCountMap,
@@ -1573,6 +1596,12 @@ export async function createRun({
* run. Tenant fanout can still export when tenant routing is available.
*/
centralTraceExportEnabled?: boolean;
+ /**
+ * Request values the deployment may export as Langfuse trace metadata
+ * (`langfuse.trace.conversationMetadataFields`). The conversation id,
+ * provider, and model default from the run itself.
+ */
+ traceContext?: LangfuseTraceContext;
/** Message history for extracting previously discovered tools */
messages?: BaseMessage[];
/**
@@ -2330,6 +2359,8 @@ export async function createRun({
runId: resolvedRunId,
tenantId: tenantId ?? user?.tenantId,
centralTraceExportEnabled,
+ user,
+ traceContext: resolveRunTraceContext({ agents, conversationId, requestBody, traceContext }),
}),
...(enableToolOutputReferences && {
toolOutputReferences: { enabled: true },
diff --git a/packages/api/src/langfuse/config.spec.ts b/packages/api/src/langfuse/config.spec.ts
index 857a84bfe2..e398d32a44 100644
--- a/packages/api/src/langfuse/config.spec.ts
+++ b/packages/api/src/langfuse/config.spec.ts
@@ -79,6 +79,71 @@ describe('buildLangfuseConfig', () => {
});
});
+ it('stamps the configured trace identity and allowlisted metadata on the run config', async () => {
+ delete process.env.TENANT_ISOLATION_STRICT;
+ process.env.LANGFUSE_PUBLIC_KEY = 'pk-env';
+ process.env.LANGFUSE_SECRET_KEY = 'sk-env';
+ const { buildLangfuseConfig } = await import('./config');
+
+ expect(
+ buildLangfuseConfig({
+ runId: 'run-1',
+ tenantId: 'tenant-1',
+ appConfig: {
+ langfuse: {
+ trace: {
+ userIdField: 'email',
+ userMetadataFields: ['email', 'role', 'samlId'],
+ conversationMetadataFields: ['conversationId', 'model', 'spec'],
+ },
+ },
+ } as unknown as AppConfig,
+ user: { id: 'user-1', email: '[email protected]', role: 'USER', username: 'alice' },
+ traceContext: {
+ conversationId: 'convo-1',
+ model: 'gpt-5',
+ modelLabel: 'Helper',
+ spec: 'support',
+ },
+ }),
+ ).toEqual({
+ deterministicTraceId: true,
+ userId: '[email protected]',
+ metadata: {
+ 'librechat.user.email': '[email protected]',
+ 'librechat.user.role': 'USER',
+ 'librechat.conversation.id': 'convo-1',
+ 'librechat.model': 'gpt-5',
+ 'librechat.spec': 'support',
+ 'librechat.tenant.id': 'tenant-1',
+ },
+ tags: ['tenant:tenant-1'],
+ publicKey: 'pk-env',
+ secretKey: 'sk-env',
+ baseUrl: 'https://cloud.langfuse.com',
+ });
+ });
+
+ it('exports neither user identity nor metadata until trace fields are configured', async () => {
+ delete process.env.TENANT_ISOLATION_STRICT;
+ process.env.LANGFUSE_PUBLIC_KEY = 'pk-env';
+ process.env.LANGFUSE_SECRET_KEY = 'sk-env';
+ const { buildLangfuseConfig } = await import('./config');
+
+ expect(
+ buildLangfuseConfig({
+ runId: 'run-1',
+ user: { id: 'user-1', email: '[email protected]', role: 'USER' },
+ traceContext: { conversationId: 'convo-1', model: 'gpt-5', endpoint: 'agents' },
+ }),
+ ).toEqual({
+ deterministicTraceId: true,
+ publicKey: 'pk-env',
+ secretKey: 'sk-env',
+ baseUrl: 'https://cloud.langfuse.com',
+ });
+ });
+
it('prefers environment credentials in single-tenant mode', async () => {
delete process.env.TENANT_ISOLATION_STRICT;
process.env.LANGFUSE_PUBLIC_KEY = 'pk-env';
diff --git a/packages/api/src/langfuse/config.ts b/packages/api/src/langfuse/config.ts
index b9dc1f3bb6..376758e472 100644
--- a/packages/api/src/langfuse/config.ts
+++ b/packages/api/src/langfuse/config.ts
@@ -1,5 +1,6 @@
import type { AppConfig } from '@librechat/data-schemas';
import type { RunConfig } from '@librechat/agents';
+import type { LangfuseTraceContext, LangfuseTraceUser } from './identity';
import {
hasLangfuseEnvCredentials,
isLangfuseCentralMediaUploadDisabled,
@@ -10,6 +11,7 @@ import {
usesLangfuseMultiTenantRouting,
} from './policy';
import { normalizeBoolean, resolveLangfuseHeaders, resolveTenantCredentials } from './utils';
+import { buildLangfuseTraceMetadata, resolveLangfuseTraceUserId } from './identity';
import { resolveLangfuseTenantDestination } from './tenantDestinations';
import { scopeHeadersToDestination } from './destinations';
import { normalizeString } from '~/utils/text';
@@ -248,6 +250,8 @@ export function buildLangfuseConfig({
runId,
tenantId,
centralTraceExportEnabled = true,
+ user,
+ traceContext,
}: {
appConfig?: AppConfig;
runId?: string;
@@ -258,6 +262,10 @@ export function buildLangfuseConfig({
* to drop the central pipeline while preserving tenant fanout when available.
*/
centralTraceExportEnabled?: boolean;
+ /** The requesting user, read only for the fields `langfuse.trace` allowlists. */
+ user?: LangfuseTraceUser;
+ /** Request values `langfuse.trace.conversationMetadataFields` may export. */
+ traceContext?: LangfuseTraceContext;
} = {}): LangfuseRunConfig {
const normalizedTenantId = normalizeString(tenantId);
const config = appConfig?.langfuse;
@@ -265,7 +273,14 @@ export function buildLangfuseConfig({
const langfuse: LangfuseRunConfigWithTraceAttributes = {
deterministicTraceId: true,
};
- const metadata = mergeTraceMetadata(undefined, normalizedTenantId);
+ const traceUserId = resolveLangfuseTraceUserId(config?.trace, user);
+ if (traceUserId != null) {
+ langfuse.userId = traceUserId;
+ }
+ const metadata = mergeTraceMetadata(
+ buildLangfuseTraceMetadata({ trace: config?.trace, user, context: traceContext }),
+ normalizedTenantId,
+ );
const tags = mergeTags(undefined, normalizedTenantId);
if (metadata) {
langfuse.metadata = metadata;
diff --git a/packages/api/src/langfuse/identity.spec.ts b/packages/api/src/langfuse/identity.spec.ts
new file mode 100644
index 0000000000..9cb27084dc
--- /dev/null
+++ b/packages/api/src/langfuse/identity.spec.ts
@@ -0,0 +1,154 @@
+import { logger } from '@librechat/data-schemas';
+import { buildLangfuseTraceMetadata, resolveLangfuseTraceUserId } from './identity';
+
+const user = {
+ id: 'user-1',
+ email: '[email protected]',
+ username: 'alice',
+ name: ' Alice ',
+ role: 'ADMIN',
+ provider: 'openid',
+ openidId: 'oidc-sub-1',
+};
+
+describe('resolveLangfuseTraceUserId', () => {
+ it('keeps the SDK default when no field is configured', () => {
+ expect(resolveLangfuseTraceUserId(undefined, user)).toBeUndefined();
+ expect(resolveLangfuseTraceUserId({}, user)).toBeUndefined();
+ });
+
+ it('keeps the SDK default when the internal id is selected explicitly', () => {
+ expect(resolveLangfuseTraceUserId({ userIdField: 'id' }, user)).toBeUndefined();
+ });
+
+ it('selects the configured user field, trimmed', () => {
+ expect(resolveLangfuseTraceUserId({ userIdField: 'email' }, user)).toBe('[email protected]');
+ expect(resolveLangfuseTraceUserId({ userIdField: 'name' }, user)).toBe('Alice');
+ expect(resolveLangfuseTraceUserId({ userIdField: 'openidId' }, user)).toBe('oidc-sub-1');
+ });
+
+ it('falls back to the internal id when the user lacks the configured field, warning once', () => {
+ const warn = jest.spyOn(logger, 'warn').mockImplementation(() => logger);
+ expect(resolveLangfuseTraceUserId({ userIdField: 'samlId' }, user)).toBeUndefined();
+ expect(resolveLangfuseTraceUserId({ userIdField: 'samlId' }, { id: 'user-3' })).toBeUndefined();
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(warn.mock.calls[0][0]).toContain('"samlId"');
+ warn.mockRestore();
+ expect(resolveLangfuseTraceUserId({ userIdField: 'email' }, { id: 'user-2' })).toBeUndefined();
+ expect(
+ resolveLangfuseTraceUserId({ userIdField: 'email' }, { id: 'user-2', email: ' ' }),
+ ).toBeUndefined();
+ expect(resolveLangfuseTraceUserId({ userIdField: 'email' }, undefined)).toBeUndefined();
+ });
+
+ it('ignores a field name outside the allowlist that bypassed schema validation', () => {
+ const warn = jest.spyOn(logger, 'warn').mockImplementation(() => logger);
+ const trace = { userIdField: 'federatedTokens' as never };
+ expect(
+ resolveLangfuseTraceUserId(trace, { ...user, federatedTokens: 'secret' } as never),
+ ).toBeUndefined();
+ expect(resolveLangfuseTraceUserId(trace, user)).toBeUndefined();
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(warn.mock.calls[0][0]).toContain('not an allowed user field');
+ warn.mockRestore();
+ });
+});
+
+describe('buildLangfuseTraceMetadata', () => {
+ const context = {
+ conversationId: 'convo-1',
+ endpoint: 'agents',
+ endpointType: undefined,
+ provider: 'openAI',
+ model: 'gpt-5',
+ modelLabel: '',
+ spec: 'support-bot',
+ };
+
+ it('skips metadata field names outside the allowlists that bypassed schema validation', () => {
+ expect(
+ buildLangfuseTraceMetadata({
+ trace: {
+ userMetadataFields: ['federatedTokens', 'email'] as never,
+ conversationMetadataFields: ['text', 'spec'] as never,
+ },
+ user: { ...user, federatedTokens: 'secret' } as never,
+ context: { ...context, text: 'prompt' } as never,
+ }),
+ ).toEqual({
+ 'librechat.user.email': '[email protected]',
+ 'librechat.spec': 'support-bot',
+ });
+ });
+
+ it('exports nothing unless a field is allowlisted', () => {
+ expect(buildLangfuseTraceMetadata({ trace: undefined, user, context })).toBeUndefined();
+ expect(buildLangfuseTraceMetadata({ trace: {}, user, context })).toBeUndefined();
+ expect(
+ buildLangfuseTraceMetadata({
+ trace: { userMetadataFields: [], conversationMetadataFields: [] },
+ user,
+ context,
+ }),
+ ).toBeUndefined();
+ });
+
+ it('exports only the allowlisted user fields under librechat.user', () => {
+ expect(
+ buildLangfuseTraceMetadata({
+ trace: { userMetadataFields: ['email', 'role', 'email'] },
+ user,
+ context,
+ }),
+ ).toEqual({
+ 'librechat.user.email': '[email protected]',
+ 'librechat.user.role': 'ADMIN',
+ });
+ });
+
+ it('exports only the allowlisted request fields under their trace keys', () => {
+ expect(
+ buildLangfuseTraceMetadata({
+ trace: {
+ conversationMetadataFields: [
+ 'conversationId',
+ 'endpoint',
+ 'endpointType',
+ 'provider',
+ 'model',
+ 'modelLabel',
+ 'spec',
+ ],
+ },
+ user,
+ context,
+ }),
+ ).toEqual({
+ 'librechat.conversation.id': 'convo-1',
+ 'librechat.endpoint': 'agents',
+ 'librechat.provider': 'openAI',
+ 'librechat.model': 'gpt-5',
+ 'librechat.spec': 'support-bot',
+ });
+ });
+
+ it('skips blank and missing values instead of exporting empty keys', () => {
+ expect(
+ buildLangfuseTraceMetadata({
+ trace: {
+ userMetadataFields: ['samlId', 'name'],
+ conversationMetadataFields: ['modelLabel'],
+ },
+ user: { ...user, name: ' ' },
+ context,
+ }),
+ ).toBeUndefined();
+ expect(
+ buildLangfuseTraceMetadata({
+ trace: { userMetadataFields: ['email'], conversationMetadataFields: ['model'] },
+ user: undefined,
+ context: undefined,
+ }),
+ ).toBeUndefined();
+ });
+});
diff --git a/packages/api/src/langfuse/identity.ts b/packages/api/src/langfuse/identity.ts
new file mode 100644
index 0000000000..de1fddb358
--- /dev/null
+++ b/packages/api/src/langfuse/identity.ts
@@ -0,0 +1,129 @@
+import { logger } from '@librechat/data-schemas';
+import {
+ LANGFUSE_TRACE_CONVERSATION_METADATA_FIELDS,
+ LANGFUSE_TRACE_USER_METADATA_FIELDS,
+ LANGFUSE_TRACE_USER_ID_FIELDS,
+} from 'librechat-data-provider';
+import type {
+ LangfuseTraceConversationMetadataField,
+ LangfuseTraceUserMetadataField,
+ LangfuseTraceUserIdField,
+ LangfuseTraceConfig,
+ DeepPartial,
+} from 'librechat-data-provider';
+import type { IUser } from '@librechat/data-schemas';
+import { normalizeString } from '~/utils/text';
+
+export type LangfuseTraceUser = Partial<Pick<IUser, LangfuseTraceUserMetadataField>>;
+
+/** Request-scoped values a run may expose as trace metadata when allowlisted. */
+export type LangfuseTraceContext = Partial<
+ Record<LangfuseTraceConversationMetadataField, string | null>
+>;
+
+export type LangfuseTraceIdentityConfig = DeepPartial<LangfuseTraceConfig>;
+
+const DEFAULT_USER_ID_FIELD = 'id';
+/** Fields already reported (unset or unknown), so a busy deployment logs each once. */
+const userIdFieldWarnings = new Set<string>();
+/**
+ * Runtime copies of the schema allowlists. Admin config patches persist
+ * overrides without schema validation, so a field name is checked again at
+ * the point it is read rather than trusted from the config type.
+ */
+const USER_ID_FIELDS = new Set<string>(LANGFUSE_TRACE_USER_ID_FIELDS);
+const USER_METADATA_FIELDS = new Set<string>(LANGFUSE_TRACE_USER_METADATA_FIELDS);
+const CONVERSATION_METADATA_FIELDS = new Set<string>(LANGFUSE_TRACE_CONVERSATION_METADATA_FIELDS);
+
+function isUserIdField(field: string): field is LangfuseTraceUserIdField {
+ return USER_ID_FIELDS.has(field);
+}
+
+function isUserMetadataField(field: unknown): field is LangfuseTraceUserMetadataField {
+ return typeof field === 'string' && USER_METADATA_FIELDS.has(field);
+}
+
+function isConversationMetadataField(
+ field: unknown,
+): field is LangfuseTraceConversationMetadataField {
+ return typeof field === 'string' && CONVERSATION_METADATA_FIELDS.has(field);
+}
+
+function warnOnce(field: string, message: string): void {
+ if (userIdFieldWarnings.has(field)) {
+ return;
+ }
+ userIdFieldWarnings.add(field);
+ logger.warn(`[langfuse] trace.userIdField "${field}" ${message} Reported once per field.`);
+}
+const USER_METADATA_PREFIX = 'librechat.user.';
+const CONVERSATION_METADATA_KEYS: Record<LangfuseTraceConversationMetadataField, string> = {
+ conversationId: 'librechat.conversation.id',
+ endpoint: 'librechat.endpoint',
+ endpointType: 'librechat.endpoint.type',
+ provider: 'librechat.provider',
+ model: 'librechat.model',
+ modelLabel: 'librechat.model.label',
+ spec: 'librechat.spec',
+};
+
+/**
+ * The trace `userId` a deployment selected, or `undefined` to keep the SDK's
+ * default (`configurable.user_id`, the internal id). A user without a value
+ * for the configured field also yields `undefined`, so the trace still
+ * carries the internal id rather than no user at all.
+ */
+export function resolveLangfuseTraceUserId(
+ trace: LangfuseTraceIdentityConfig | undefined,
+ user: LangfuseTraceUser | undefined,
+): string | undefined {
+ const field: string = trace?.userIdField ?? DEFAULT_USER_ID_FIELD;
+ if (field === DEFAULT_USER_ID_FIELD) {
+ return undefined;
+ }
+ if (!isUserIdField(field)) {
+ warnOnce(field, 'is not an allowed user field; the trace keeps the internal id.');
+ return undefined;
+ }
+ const value = normalizeString(user?.[field]);
+ if (value == null) {
+ warnOnce(
+ field,
+ `is unset for user ${user?.id ?? '(unknown)'}; the trace keeps the internal id.`,
+ );
+ }
+ return value;
+}
+
+/**
+ * Allowlisted user and request fields as trace metadata. Only fields the
+ * deployment listed are read, blank values are skipped, and `undefined` is
+ * returned when nothing survives so callers can leave the metadata untouched.
+ */
+export function buildLangfuseTraceMetadata({
+ trace,
+ user,
+ context,
+}: {
+ trace: LangfuseTraceIdentityConfig | undefined;
+ user: LangfuseTraceUser | undefined;
+ context: LangfuseTraceContext | undefined;
+}): Record<string, string> | undefined {
+ const metadata: Record<string, string> = {};
+ for (const field of new Set(trace?.userMetadataFields ?? [])) {
+ const value = isUserMetadataField(field) ? normalizeString(user?.[field]) : undefined;
+ if (value != null) {
+ metadata[`${USER_METADATA_PREFIX}${field}`] = value;
+ }
+ }
+ for (const field of new Set(trace?.conversationMetadataFields ?? [])) {
+ if (!isConversationMetadataField(field)) {
+ continue;
+ }
+ const value = normalizeString(context?.[field]);
+ if (value != null) {
+ metadata[CONVERSATION_METADATA_KEYS[field]] = value;
+ }
+ }
+ return Object.keys(metadata).length > 0 ? metadata : undefined;
+}
diff --git a/packages/data-provider/specs/config-schemas.spec.ts b/packages/data-provider/specs/config-schemas.spec.ts
index d9f14ead77..7d6f4cf14e 100644
--- a/packages/data-provider/specs/config-schemas.spec.ts
+++ b/packages/data-provider/specs/config-schemas.spec.ts
@@ -1787,6 +1787,42 @@ describe('configSchema langfuse', () => {
expect(result.success).toBe(true);
});
+ it('accepts trace identity and metadata allowlists', () => {
+ const result = configSchema.safeParse({
+ version: '1.3.7',
+ langfuse: {
+ trace: {
+ userIdField: 'email',
+ userMetadataFields: ['email', 'username', 'role', 'provider'],
+ conversationMetadataFields: ['conversationId', 'endpoint', 'model', 'spec'],
+ },
+ },
+ });
+
+ expect(result.success).toBe(true);
+ });
+
+ it('rejects trace fields outside the allowlists', () => {
+ expect(
+ configSchema.safeParse({
+ version: '1.3.7',
+ langfuse: { trace: { userIdField: 'password' } },
+ }).success,
+ ).toBe(false);
+ expect(
+ configSchema.safeParse({
+ version: '1.3.7',
+ langfuse: { trace: { userMetadataFields: ['totpSecret'] } },
+ }).success,
+ ).toBe(false);
+ expect(
+ configSchema.safeParse({
+ version: '1.3.7',
+ langfuse: { trace: { conversationMetadataFields: ['text'] } },
+ }).success,
+ ).toBe(false);
+ });
+
it('rejects non-string Langfuse header values', () => {
const result = configSchema.safeParse({
version: '1.3.7',
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index 89b3865cae..ccdee85169 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -2502,6 +2502,69 @@ export const messageFilterSchema = z.object({
export type MessageFilterConfig = z.infer<typeof messageFilterSchema>;
+/** User fields a deployment may select as the Langfuse trace `userId`. */
+export const LANGFUSE_TRACE_USER_ID_FIELDS = [
+ 'id',
+ 'email',
+ 'username',
+ 'name',
+ 'openidId',
+ 'samlId',
+ 'ldapId',
+ 'googleId',
+ 'githubId',
+ 'discordId',
+ 'appleId',
+ 'facebookId',
+] as const;
+export type LangfuseTraceUserIdField = (typeof LANGFUSE_TRACE_USER_ID_FIELDS)[number];
+
+/** User fields a deployment may copy into Langfuse trace metadata. */
+export const LANGFUSE_TRACE_USER_METADATA_FIELDS = [
+ ...LANGFUSE_TRACE_USER_ID_FIELDS,
+ 'role',
+ 'provider',
+] as const;
+export type LangfuseTraceUserMetadataField = (typeof LANGFUSE_TRACE_USER_METADATA_FIELDS)[number];
+
+/** Request fields a deployment may copy into Langfuse trace metadata. */
+export const LANGFUSE_TRACE_CONVERSATION_METADATA_FIELDS = [
+ 'conversationId',
+ 'endpoint',
+ 'endpointType',
+ 'provider',
+ 'model',
+ 'modelLabel',
+ 'spec',
+] as const;
+export type LangfuseTraceConversationMetadataField =
+ (typeof LANGFUSE_TRACE_CONVERSATION_METADATA_FIELDS)[number];
+
+/**
+ * What a deployment attaches to every Langfuse trace beyond the defaults.
+ * Nothing here is exported unless explicitly listed, so the default trace
+ * carries only the internal user id and no user or request metadata.
+ */
+export const langfuseTraceConfigSchema = z.object({
+ /**
+ * Which user field becomes the trace `userId`. Defaults to the internal user
+ * id; a user with no value for the chosen field keeps the internal id.
+ */
+ userIdField: z.enum(LANGFUSE_TRACE_USER_ID_FIELDS).optional(),
+ /** User fields exported as `librechat.user.<field>` trace metadata. */
+ userMetadataFields: z.array(z.enum(LANGFUSE_TRACE_USER_METADATA_FIELDS)).optional(),
+ /**
+ * Request fields exported as trace metadata: `librechat.conversation.id`,
+ * `librechat.endpoint`, `librechat.endpoint.type`, `librechat.provider`,
+ * `librechat.model`, `librechat.model.label`, and `librechat.spec`.
+ */
+ conversationMetadataFields: z
+ .array(z.enum(LANGFUSE_TRACE_CONVERSATION_METADATA_FIELDS))
+ .optional(),
+});
+
+export type LangfuseTraceConfig = z.infer<typeof langfuseTraceConfigSchema>;
+
export const langfuseConfigSchema = z.object({
enabled: z.boolean().optional(),
publicKey: z.string().optional(),
@@ -2534,6 +2597,8 @@ export const langfuseConfigSchema = z.object({
* `Authorization` upstream regardless.
*/
headers: z.record(z.string()).optional(),
+ /** Trace user identity and allowlisted user/request metadata. */
+ trace: langfuseTraceConfigSchema.optional(),
});
export type LangfuseConfig = z.infer<typeof langfuseConfigSchema>;