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: Track Prompt Group Source Identity (#16891)

Atef Bellaajbc66654a9ce8
diff --git a/api/server/routes/prompts.test.js b/api/server/routes/prompts.test.js
index 57b89b57c6..0140628b56 100644
--- a/api/server/routes/prompts.test.js
+++ b/api/server/routes/prompts.test.js
@@ -1577,11 +1577,12 @@ describe('Prompt Routes - response and failure compatibility', () => {
'numberOfGenerations',
'oneliner',
'productionId',
+ 'source',
'updatedAt',
].sort(),
);
expect(response.body).toEqual(
- expect.objectContaining({ name: 'Renamed Group', command: 'renamed' }),
+ expect.objectContaining({ name: 'Renamed Group', command: 'renamed', source: 'native' }),
);
});
diff --git a/client/src/components/SidePanel/Agents/__tests__/InstructionsPromptFields.spec.tsx b/client/src/components/SidePanel/Agents/__tests__/InstructionsPromptFields.spec.tsx
index e3491ef7e9..04c45d2540 100644
--- a/client/src/components/SidePanel/Agents/__tests__/InstructionsPromptFields.spec.tsx
+++ b/client/src/components/SidePanel/Agents/__tests__/InstructionsPromptFields.spec.tsx
@@ -87,6 +87,7 @@ const group = (overrides: Partial<TPromptGroup> = {}): TPromptGroup => ({
author: 'user1',
authorName: 'User One',
_id: 'group1',
+ source: 'native',
...overrides,
});
diff --git a/packages/api/src/prompts/records.spec.ts b/packages/api/src/prompts/records.spec.ts
new file mode 100644
index 0000000000..b593a148e2
--- /dev/null
+++ b/packages/api/src/prompts/records.spec.ts
@@ -0,0 +1,71 @@
+import { toPromptGroupRecord, toPromptRecord } from './records';
+
+const baseGroup = {
+ _id: 'group-1',
+ name: 'Welcome Prompt',
+ author: 'author-1',
+ authorName: 'Ada',
+};
+
+describe('toPromptGroupRecord', () => {
+ it('defaults a stored group with no source to native', () => {
+ const record = toPromptGroupRecord({ ...baseGroup, productionId: 'prompt-1' });
+ expect(record.source).toBe('native');
+ });
+
+ it('keeps a langfuse group source and identity fields', () => {
+ const record = toPromptGroupRecord({
+ ...baseGroup,
+ source: 'langfuse',
+ sourcePromptName: 'welcome-prompt',
+ sourceProjectId: 'project-1',
+ sourceDestination: 'eu',
+ });
+ expect(record.source).toBe('langfuse');
+ expect(record.sourcePromptName).toBe('welcome-prompt');
+ expect(record.sourceProjectId).toBe('project-1');
+ expect(record.sourceDestination).toBe('eu');
+ });
+
+ it('converts ObjectId-like fields to strings, including on a nested production revision', () => {
+ const record = toPromptGroupRecord({
+ ...baseGroup,
+ _id: { toString: () => 'group-1' },
+ author: { toString: () => 'author-1' },
+ productionId: { toString: () => 'prompt-1' },
+ productionPrompt: {
+ _id: { toString: () => 'prompt-1' },
+ groupId: { toString: () => 'group-1' },
+ author: { toString: () => 'author-1' },
+ prompt: 'Hello',
+ },
+ });
+ expect(record._id).toBe('group-1');
+ expect(record.author).toBe('author-1');
+ expect(record.productionId).toBe('prompt-1');
+ expect(record.productionPrompt).toMatchObject({
+ _id: 'prompt-1',
+ groupId: 'group-1',
+ author: 'author-1',
+ });
+ });
+});
+
+describe('toPromptRecord', () => {
+ it('converts ObjectId-like fields to strings', () => {
+ const record = toPromptRecord({
+ _id: { toString: () => 'prompt-1' },
+ groupId: { toString: () => 'group-1' },
+ author: { toString: () => 'author-1' },
+ prompt: 'Hello',
+ type: 'text',
+ });
+ expect(record).toMatchObject({
+ _id: 'prompt-1',
+ groupId: 'group-1',
+ author: 'author-1',
+ prompt: 'Hello',
+ type: 'text',
+ });
+ });
+});
diff --git a/packages/api/src/prompts/records.ts b/packages/api/src/prompts/records.ts
index 71f4ddbba7..e1e2dd0831 100644
--- a/packages/api/src/prompts/records.ts
+++ b/packages/api/src/prompts/records.ts
@@ -21,12 +21,19 @@ export function toPromptRecord(record: object): PromptRecord {
return withStringIds(record) as unknown as PromptRecord;
}
-/** Converts a stored group, and its Production revision when present, to string IDs. */
+/**
+ * Converts a stored group, and its Production revision when present, to string IDs.
+ * A stored group with no `source` predates the field; it defaults here to `native`,
+ * the only place that default is applied.
+ */
export function toPromptGroupRecord(record: object): PromptGroupRecord {
const plain = withStringIds(record);
const production = plain.productionPrompt;
if (production != null && typeof production === 'object') {
plain.productionPrompt = withStringIds(production);
}
+ if (plain.source == null) {
+ plain.source = 'native';
+ }
return plain as unknown as PromptGroupRecord;
}
diff --git a/packages/api/src/prompts/schemas.spec.ts b/packages/api/src/prompts/schemas.spec.ts
index e9a4c2ef4e..088a85b866 100644
--- a/packages/api/src/prompts/schemas.spec.ts
+++ b/packages/api/src/prompts/schemas.spec.ts
@@ -149,6 +149,22 @@ describe('updatePromptGroupSchema', () => {
expect(result.success).toBe(false);
});
+ it('should reject source field', () => {
+ const result = updatePromptGroupSchema.safeParse({
+ name: 'Test',
+ source: 'langfuse',
+ });
+ expect(result.success).toBe(false);
+ });
+
+ it('should reject a source identity field', () => {
+ const result = updatePromptGroupSchema.safeParse({
+ name: 'Test',
+ sourcePromptName: 'langfuse-prompt',
+ });
+ expect(result.success).toBe(false);
+ });
+
it('should reject multiple sensitive fields in a single request', () => {
const result = updatePromptGroupSchema.safeParse({
name: 'Legit Name',
diff --git a/packages/api/src/prompts/service.spec.ts b/packages/api/src/prompts/service.spec.ts
index ff261120e2..3df42449fe 100644
--- a/packages/api/src/prompts/service.spec.ts
+++ b/packages/api/src/prompts/service.spec.ts
@@ -247,6 +247,39 @@ describe('createPromptService', () => {
expect(prompt?.groupId).not.toBe(otherGroupId);
});
+ it('drops client-supplied source identity fields before writing the group', async () => {
+ const create = jest.spyOn(db, 'createPromptGroup');
+ const importedGroup = {
+ name: 'Imported group',
+ source: 'langfuse',
+ sourcePromptName: 'langfuse-prompt',
+ sourceProjectId: 'project-1',
+ sourceDestination: 'destination-1',
+ };
+
+ const result = await service.createPromptGroup({
+ prompt: { prompt: 'New prompt', type: 'text' },
+ group: importedGroup,
+ author,
+ });
+
+ expect(result.ok).toBe(true);
+ expect(create).toHaveBeenCalledWith(
+ expect.objectContaining({ group: { name: 'Imported group' } }),
+ );
+
+ const groupId = result.ok ? result.value.prompt?.groupId : undefined;
+ // Read the raw document directly: toPromptGroupRecord defaults a missing `source` to
+ // 'native', so asserting through it would prove nothing about what was actually stored.
+ const stored = (await mongoose.models.PromptGroup.findById(groupId).lean()) as {
+ source?: string;
+ } | null;
+ expect(stored?.source).toBe('native');
+ expect(stored).not.toHaveProperty('sourcePromptName');
+ expect(stored).not.toHaveProperty('sourceProjectId');
+ expect(stored).not.toHaveProperty('sourceDestination');
+ });
+
it('rejects protected content before writing', async () => {
const create = jest.spyOn(db, 'createPromptGroup');
diff --git a/packages/api/src/prompts/service.ts b/packages/api/src/prompts/service.ts
index 89f1d66aa3..70c225e8b5 100644
--- a/packages/api/src/prompts/service.ts
+++ b/packages/api/src/prompts/service.ts
@@ -183,11 +183,26 @@ export function createPromptServiceFromAdapters(adapters: PromptServiceAdapters)
if (!validation.success) {
return invalidInput(validation.error.issues[0]?.message ?? 'Invalid prompt');
}
- const rejection = inspect({ prompt: validation.data, group: input.group }, filters);
+ // The client create path always produces a native group: source identity is set by
+ // import flows, never by a request body. Drop these fields here regardless of what
+ // the client sent, since the database layer upserts whatever `group` it is given.
+ const {
+ source: _clientSource,
+ sourcePromptName: _clientSourcePromptName,
+ sourceProjectId: _clientSourceProjectId,
+ sourceDestination: _clientSourceDestination,
+ ...group
+ } = input.group as typeof input.group & {
+ source?: unknown;
+ sourcePromptName?: unknown;
+ sourceProjectId?: unknown;
+ sourceDestination?: unknown;
+ };
+ const rejection = inspect({ prompt: validation.data, group }, filters);
if (rejection != null) {
return rejection;
}
- const value = await source.createPromptGroup({ ...input, prompt: validation.data });
+ const value = await source.createPromptGroup({ ...input, group, prompt: validation.data });
const groupId = value.prompt?.groupId;
if (value.prompt?._id && groupId) {
try {
diff --git a/packages/api/src/prompts/types.ts b/packages/api/src/prompts/types.ts
index fb4cc58fac..0304d11108 100644
--- a/packages/api/src/prompts/types.ts
+++ b/packages/api/src/prompts/types.ts
@@ -4,6 +4,7 @@ import type {
TDeletePromptResponse,
TMakePromptProductionResponse,
} from 'librechat-data-provider';
+import type { PromptGroupSource } from '@librechat/data-schemas';
import type { ProtectionFinding } from '../protection/types';
export type PromptKind = 'text' | 'chat';
@@ -49,6 +50,10 @@ export interface PromptGroupRecord {
readonly createdAt?: PromptTimestamp;
readonly updatedAt?: PromptTimestamp;
readonly tenantId?: string;
+ readonly source: PromptGroupSource;
+ readonly sourcePromptName?: string;
+ readonly sourceProjectId?: string;
+ readonly sourceDestination?: string;
}
export type PromptSelection =
diff --git a/packages/data-provider/src/types.ts b/packages/data-provider/src/types.ts
index 22e9444c98..ccb25a9a62 100644
--- a/packages/data-provider/src/types.ts
+++ b/packages/data-provider/src/types.ts
@@ -1117,6 +1117,13 @@ export type TPrompt = {
_id?: string;
};
+export const PromptGroupSources = {
+ native: 'native',
+ langfuse: 'langfuse',
+} as const;
+
+export type TPromptGroupSource = (typeof PromptGroupSources)[keyof typeof PromptGroupSources];
+
export type TPromptGroup = {
name: string;
numberOfGenerations?: number;
@@ -1131,6 +1138,10 @@ export type TPromptGroup = {
createdAt?: Date;
updatedAt?: Date;
_id?: string;
+ source: TPromptGroupSource;
+ sourcePromptName?: string;
+ sourceProjectId?: string;
+ sourceDestination?: string;
};
export type TCreatePrompt = {
@@ -1176,7 +1187,10 @@ export type TCreatePromptResponse = {
group?: TPromptGroup;
};
-export type TUpdatePromptGroupPayload = Partial<TPromptGroup>;
+/** Source identity is set by the server and cannot be updated. */
+export type TUpdatePromptGroupPayload = Partial<
+ Omit<TPromptGroup, 'source' | 'sourcePromptName' | 'sourceProjectId' | 'sourceDestination'>
+>;
export type TUpdatePromptGroupVariables = {
id: string;
diff --git a/packages/data-schemas/src/methods/prompt.spec.ts b/packages/data-schemas/src/methods/prompt.spec.ts
index c9e0b3f342..0b3e5adc8b 100644
--- a/packages/data-schemas/src/methods/prompt.spec.ts
+++ b/packages/data-schemas/src/methods/prompt.spec.ts
@@ -10,6 +10,7 @@ import {
PermissionBits,
} from 'librechat-data-provider';
import type { IPromptGroup, AccessRole as TAccessRole, AclEntry as TAclEntry } from '..';
+import { tenantStorage } from '~/config/tenantContext';
import { createAclEntryMethods } from './aclEntry';
import { createMethods } from './index';
@@ -829,3 +830,266 @@ describe('Prompt group list projections include `command`', () => {
expect(result.data[0].command).toBe('mytest-cmd');
});
});
+
+describe('PromptGroup source identity', () => {
+ beforeAll(async () => {
+ await PromptGroup.syncIndexes();
+ });
+
+ it('rejects a native group (default source) without a productionId', async () => {
+ const group = new PromptGroup({
+ name: 'Native Default Source',
+ author: testUsers.owner._id,
+ authorName: testUsers.owner.name,
+ });
+ await expect(group.validate()).rejects.toThrow(/productionId/);
+ });
+
+ it('rejects a native group (explicit source) without a productionId', async () => {
+ const group = new PromptGroup({
+ name: 'Native Explicit Source',
+ source: 'native',
+ author: testUsers.owner._id,
+ authorName: testUsers.owner.name,
+ });
+ await expect(group.validate()).rejects.toThrow(/productionId/);
+ });
+
+ it('saves a langfuse group with identity fields and no productionId', async () => {
+ const group = (
+ await PromptGroup.create({
+ name: 'Langfuse Mirrored Prompt',
+ source: 'langfuse',
+ sourcePromptName: 'welcome-prompt',
+ sourceProjectId: 'project-1',
+ sourceDestination: 'eu',
+ author: testUsers.owner._id,
+ authorName: testUsers.owner.name,
+ })
+ ).toObject() as unknown as LeanPromptGroup;
+
+ expect(group.productionId).toBeUndefined();
+ expect(group.source).toBe('langfuse');
+ });
+
+ it('rejects a langfuse group missing sourcePromptName', async () => {
+ const group = new PromptGroup({
+ name: 'Langfuse Missing Prompt Name',
+ source: 'langfuse',
+ sourceProjectId: 'project-1',
+ sourceDestination: 'eu',
+ author: testUsers.owner._id,
+ authorName: testUsers.owner.name,
+ });
+ await expect(group.validate()).rejects.toThrow(/sourcePromptName/);
+ });
+
+ it('rejects a langfuse group missing sourceProjectId', async () => {
+ const group = new PromptGroup({
+ name: 'Langfuse Missing Project Id',
+ source: 'langfuse',
+ sourcePromptName: 'welcome-prompt',
+ sourceDestination: 'eu',
+ author: testUsers.owner._id,
+ authorName: testUsers.owner.name,
+ });
+ await expect(group.validate()).rejects.toThrow(/sourceProjectId/);
+ });
+
+ it('rejects a langfuse group missing sourceDestination', async () => {
+ const group = new PromptGroup({
+ name: 'Langfuse Missing Destination',
+ source: 'langfuse',
+ sourcePromptName: 'welcome-prompt',
+ sourceProjectId: 'project-1',
+ author: testUsers.owner._id,
+ authorName: testUsers.owner.name,
+ });
+ await expect(group.validate()).rejects.toThrow(/sourceDestination/);
+ });
+
+ it('rejects a duplicate langfuse identity within the same tenant', async () => {
+ const identity = {
+ source: 'langfuse',
+ sourcePromptName: 'dup-prompt',
+ sourceProjectId: 'project-dup',
+ sourceDestination: 'eu',
+ author: testUsers.owner._id,
+ authorName: testUsers.owner.name,
+ };
+
+ await tenantStorage.run({ tenantId: 'tenant-dup-a' }, async () => {
+ await PromptGroup.create({ ...identity, name: 'Dup Prompt A1' });
+ await expect(PromptGroup.create({ ...identity, name: 'Dup Prompt A2' })).rejects.toThrow(
+ /E11000/,
+ );
+ });
+ });
+
+ it('allows the same langfuse identity in a different tenant', async () => {
+ const identity = {
+ source: 'langfuse',
+ sourcePromptName: 'cross-tenant-prompt',
+ sourceProjectId: 'project-cross',
+ sourceDestination: 'eu',
+ author: testUsers.owner._id,
+ authorName: testUsers.owner.name,
+ };
+
+ await tenantStorage.run({ tenantId: 'tenant-cross-a' }, async () => {
+ await PromptGroup.create({ ...identity, name: 'Cross A' });
+ });
+ await tenantStorage.run({ tenantId: 'tenant-cross-b' }, async () => {
+ await expect(PromptGroup.create({ ...identity, name: 'Cross B' })).resolves.toBeTruthy();
+ });
+ });
+
+ it('creates a new native group instead of matching an existing langfuse group with the same name', async () => {
+ const langfuseGroup = (
+ await PromptGroup.create({
+ name: 'Shared Name Group',
+ source: 'langfuse',
+ sourcePromptName: 'shared-name-group',
+ sourceProjectId: 'project-shared',
+ sourceDestination: 'eu',
+ author: testUsers.owner._id,
+ authorName: testUsers.owner.name,
+ })
+ ).toObject() as unknown as LeanPromptGroup;
+
+ const { group: nativeGroup } = await methods.createPromptGroup({
+ prompt: { prompt: 'Native prompt text', type: 'text' },
+ group: { name: 'Shared Name Group' },
+ author: String(testUsers.owner._id),
+ authorName: testUsers.owner.name ?? '',
+ });
+
+ expect(String((nativeGroup as { _id: unknown })._id)).not.toBe(String(langfuseGroup._id));
+ expect((nativeGroup as { source?: string }).source).toBe('native');
+ expect((nativeGroup as { productionId?: unknown }).productionId).toBeTruthy();
+
+ const unchangedLangfuseGroup = (await PromptGroup.findById(
+ langfuseGroup._id,
+ ).lean()) as unknown as LeanPromptGroup & { source?: string; productionId?: unknown };
+ expect(unchangedLangfuseGroup.productionId).toBeUndefined();
+ expect(unchangedLangfuseGroup.source).toBe('langfuse');
+ });
+
+ it.each([
+ ['missing', {}],
+ ['null', { source: null }],
+ ['native', { source: 'native' }],
+ ])('reuses an unfinished group with %s source', async (label, sourceFields) => {
+ const name = `Unfinished ${label} Source Group`;
+ const { insertedId } = await PromptGroup.collection.insertOne({
+ name,
+ author: new ObjectId(String(testUsers.owner._id)),
+ authorName: testUsers.owner.name,
+ productionId: null,
+ ...sourceFields,
+ });
+ const storedBefore = await PromptGroup.collection.findOne({ _id: insertedId });
+ if (label === 'missing') {
+ expect(storedBefore).not.toHaveProperty('source');
+ }
+
+ const { group, prompt } = await methods.createPromptGroup({
+ prompt: { prompt: 'Native prompt text', type: 'text' },
+ group: { name },
+ author: String(testUsers.owner._id),
+ authorName: testUsers.owner.name ?? '',
+ });
+
+ expect(String(group._id)).toBe(String(insertedId));
+ expect(prompt).not.toBeNull();
+ expect(String(prompt!.groupId)).toBe(String(insertedId));
+ const storedAfter = await PromptGroup.collection.findOne({ _id: insertedId });
+ expect(String(storedAfter?.productionId)).toBe(String(prompt!._id));
+ expect(await PromptGroup.collection.countDocuments({ name })).toBe(1);
+ });
+
+ it('does not attach a native prompt to an unknown external source', async () => {
+ const name = 'Unknown External Source Group';
+ const { insertedId } = await PromptGroup.collection.insertOne({
+ name,
+ author: new ObjectId(String(testUsers.owner._id)),
+ authorName: testUsers.owner.name,
+ source: 'external-catalog',
+ });
+ const storedBefore = await PromptGroup.collection.findOne({ _id: insertedId });
+
+ const { group, prompt } = await methods.createPromptGroup({
+ prompt: { prompt: 'Native prompt text', type: 'text' },
+ group: { name },
+ author: String(testUsers.owner._id),
+ authorName: testUsers.owner.name ?? '',
+ });
+
+ expect(String(group._id)).not.toBe(String(insertedId));
+ expect(group.source).toBe('native');
+ expect(prompt).not.toBeNull();
+ expect(String(prompt!.groupId)).toBe(String(group._id));
+ expect(String(group.productionId)).toBe(String(prompt!._id));
+ expect(await PromptGroup.collection.findOne({ _id: insertedId })).toEqual(storedBefore);
+ expect(await PromptGroup.collection.countDocuments({ name })).toBe(2);
+ });
+
+ it('allows two native groups with the same name', async () => {
+ const first = await PromptGroup.create({
+ name: 'Duplicate Name Group',
+ author: testUsers.owner._id,
+ authorName: testUsers.owner.name,
+ productionId: new ObjectId(),
+ });
+ const second = await PromptGroup.create({
+ name: 'Duplicate Name Group',
+ author: testUsers.owner._id,
+ authorName: testUsers.owner.name,
+ productionId: new ObjectId(),
+ });
+ expect(String(first._id)).not.toBe(String(second._id));
+ });
+});
+
+describe('PromptGroup list projections', () => {
+ it('returns source identity fields from getAllPromptGroups, getPromptGroups, and getListPromptGroupsByAccess', async () => {
+ const langfuseGroup = (
+ await PromptGroup.create({
+ name: 'Projection Langfuse Prompt',
+ source: 'langfuse',
+ sourcePromptName: 'projection-prompt',
+ sourceProjectId: 'project-projection',
+ sourceDestination: 'eu',
+ author: testUsers.owner._id,
+ authorName: testUsers.owner.name,
+ })
+ ).toObject() as unknown as LeanPromptGroup;
+
+ const allGroups = (await methods.getAllPromptGroups({
+ name: 'Projection Langfuse Prompt',
+ })) as Array<Record<string, unknown>>;
+ const fromGetAll = allGroups.find((g) => String(g._id) === String(langfuseGroup._id));
+ expect(fromGetAll?.source).toBe('langfuse');
+ expect(fromGetAll?.sourcePromptName).toBe('projection-prompt');
+ expect(fromGetAll?.sourceProjectId).toBe('project-projection');
+ expect(fromGetAll?.sourceDestination).toBe('eu');
+
+ const paged = (await methods.getPromptGroups({
+ name: 'Projection Langfuse Prompt',
+ })) as { promptGroups: Array<Record<string, unknown>> };
+ const fromGetPage = paged.promptGroups.find((g) => String(g._id) === String(langfuseGroup._id));
+ expect(fromGetPage?.source).toBe('langfuse');
+ expect(fromGetPage?.sourcePromptName).toBe('projection-prompt');
+ expect(fromGetPage?.sourceProjectId).toBe('project-projection');
+ expect(fromGetPage?.sourceDestination).toBe('eu');
+
+ const byAccess = await methods.getListPromptGroupsByAccess({
+ accessibleIds: [langfuseGroup._id],
+ });
+ const fromAccess = byAccess.data.find((g) => String(g._id) === String(langfuseGroup._id));
+ expect(fromAccess?.source).toBe('langfuse');
+ expect(fromAccess?.sourcePromptName).toBe('projection-prompt');
+ expect(fromAccess?.sourceProjectId).toBe('project-projection');
+ expect(fromAccess?.sourceDestination).toBe('eu');
+ });
+});
diff --git a/packages/data-schemas/src/methods/prompt.ts b/packages/data-schemas/src/methods/prompt.ts
index c17d026765..388ffd5b02 100644
--- a/packages/data-schemas/src/methods/prompt.ts
+++ b/packages/data-schemas/src/methods/prompt.ts
@@ -4,6 +4,7 @@ import {
PermissionBits,
ResourceType,
SystemCategories,
+ PromptGroupSources,
Time,
} from 'librechat-data-provider';
import type { Model, Types } from 'mongoose';
@@ -234,7 +235,7 @@ export function createPromptMethods(
const groups = await PromptGroup.find(query)
.sort({ numberOfGenerations: -1, updatedAt: -1, _id: 1 })
.select(
- 'name numberOfGenerations oneliner category author authorName createdAt updatedAt command productionId',
+ 'name numberOfGenerations oneliner category author authorName createdAt updatedAt command productionId source sourcePromptName sourceProjectId sourceDestination',
)
.lean();
return await attachProductionPrompts(groups as unknown as Array<Record<string, unknown>>);
@@ -303,7 +304,7 @@ export function createPromptMethods(
.skip(skip)
.limit(limit)
.select(
- 'name numberOfGenerations oneliner category productionId author authorName createdAt updatedAt command',
+ 'name numberOfGenerations oneliner category productionId author authorName createdAt updatedAt command source sourcePromptName sourceProjectId sourceDestination',
)
.lean(),
PromptGroup.countDocuments(query),
@@ -443,7 +444,7 @@ export function createPromptMethods(
const findQuery = PromptGroup.find(matchQuery)
.sort({ numberOfGenerations: -1, updatedAt: -1, _id: 1 })
.select(
- 'name numberOfGenerations oneliner category productionId author authorName createdAt updatedAt command',
+ 'name numberOfGenerations oneliner category productionId author authorName createdAt updatedAt command source sourcePromptName sourceProjectId sourceDestination',
);
if (isPaginated && normalizedLimit) {
@@ -526,7 +527,17 @@ export function createPromptMethods(
const { prompt, group, author, authorName } = saveData;
let newPromptGroup = await PromptGroup.findOneAndUpdate(
- { ...group, author, authorName, productionId: null },
+ /**
+ * Only reuse native groups, including legacy groups with no source. Mirrored
+ * groups can also lack a productionId, but must not receive a native prompt.
+ */
+ {
+ ...group,
+ author,
+ authorName,
+ productionId: null,
+ source: { $in: [PromptGroupSources.native, null] },
+ },
{ $setOnInsert: { ...group, author, authorName, productionId: null } },
{ new: true, upsert: true },
)
diff --git a/packages/data-schemas/src/schema/promptGroup.ts b/packages/data-schemas/src/schema/promptGroup.ts
index 99dc8bda69..3fcdbb493d 100644
--- a/packages/data-schemas/src/schema/promptGroup.ts
+++ b/packages/data-schemas/src/schema/promptGroup.ts
@@ -1,5 +1,5 @@
import { Schema } from 'mongoose';
-import { Constants } from 'librechat-data-provider';
+import { Constants, PromptGroupSources } from 'librechat-data-provider';
import type { IPromptGroupDocument } from '~/types';
const promptGroupSchema: Schema<IPromptGroupDocument> = new Schema<IPromptGroupDocument>(
@@ -25,7 +25,9 @@ const promptGroupSchema: Schema<IPromptGroupDocument> = new Schema<IPromptGroupD
productionId: {
type: Schema.Types.ObjectId,
ref: 'Prompt',
- required: true,
+ required: function (this: IPromptGroupDocument) {
+ return (this.source ?? PromptGroupSources.native) === PromptGroupSources.native;
+ },
index: true,
},
author: {
@@ -53,6 +55,38 @@ const promptGroupSchema: Schema<IPromptGroupDocument> = new Schema<IPromptGroupD
`Command cannot be longer than ${Constants.COMMANDS_MAX_LENGTH} characters`,
],
}, // Casting here bypasses the type error for the command field.
+ /**
+ * Provenance of this prompt group.
+ *
+ * - `native` — authored directly inside LibreChat.
+ * - `langfuse` — mirrored from a configured Langfuse prompt.
+ */
+ source: {
+ type: String,
+ enum: Object.values(PromptGroupSources),
+ default: PromptGroupSources.native,
+ },
+ /** Name of the prompt in its Langfuse project. */
+ sourcePromptName: {
+ type: String,
+ required: function (this: IPromptGroupDocument) {
+ return this.source === PromptGroupSources.langfuse;
+ },
+ },
+ /** Langfuse project ID the prompt was mirrored from. */
+ sourceProjectId: {
+ type: String,
+ required: function (this: IPromptGroupDocument) {
+ return this.source === PromptGroupSources.langfuse;
+ },
+ },
+ /** Tenant's Langfuse destination key (e.g. `eu`) the prompt was mirrored from. */
+ sourceDestination: {
+ type: String,
+ required: function (this: IPromptGroupDocument) {
+ return this.source === PromptGroupSources.langfuse;
+ },
+ },
tenantId: {
type: String,
index: true,
@@ -64,5 +98,12 @@ const promptGroupSchema: Schema<IPromptGroupDocument> = new Schema<IPromptGroupD
);
promptGroupSchema.index({ numberOfGenerations: -1, updatedAt: -1, _id: 1 });
+promptGroupSchema.index(
+ { tenantId: 1, sourceDestination: 1, sourceProjectId: 1, sourcePromptName: 1 },
+ {
+ unique: true,
+ partialFilterExpression: { sourcePromptName: { $exists: true } },
+ },
+);
export default promptGroupSchema;
diff --git a/packages/data-schemas/src/types/prompts.ts b/packages/data-schemas/src/types/prompts.ts
index 24150ba27f..87873e4452 100644
--- a/packages/data-schemas/src/types/prompts.ts
+++ b/packages/data-schemas/src/types/prompts.ts
@@ -1,3 +1,4 @@
+import type { TPromptGroupSource } from 'librechat-data-provider';
import type { Document, Types } from 'mongoose';
export interface IPrompt extends Document {
@@ -16,12 +17,15 @@ export type IPromptRecord = Pick<
'groupId' | 'author' | 'prompt' | 'type' | 'createdAt' | 'updatedAt' | 'tenantId'
> & { _id: Types.ObjectId; __v?: number };
+export type PromptGroupSource = TPromptGroupSource;
+
export interface IPromptGroup {
name: string;
numberOfGenerations: number;
oneliner: string;
category: string;
- productionId: Types.ObjectId;
+ /** Required for `native` groups; absent for a mirrored group with no production prompt yet. */
+ productionId?: Types.ObjectId;
author: Types.ObjectId;
authorName: string;
command?: string;
@@ -29,6 +33,10 @@ export interface IPromptGroup {
updatedAt?: Date;
isPublic?: boolean;
tenantId?: string;
+ source?: PromptGroupSource;
+ sourcePromptName?: string;
+ sourceProjectId?: string;
+ sourceDestination?: string;
}
export interface IPromptGroupDocument extends IPromptGroup, Document {}