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

🗂️ perf: Index Hot Lookups and Project the Remote Models List (#17259)

Marco Berettab1cf65c7e9e6
diff --git a/api/server/controllers/agents/openai.js b/api/server/controllers/agents/openai.js
index 35fb0495c5..70fbe21d24 100644
--- a/api/server/controllers/agents/openai.js
+++ b/api/server/controllers/agents/openai.js
@@ -1323,7 +1323,7 @@ const ListModelsController = async (req, res) => {
// Get the accessible agents
let agents = [];
if (accessibleAgentIds.length > 0) {
- agents = await db.getAgents({ _id: { $in: accessibleAgentIds } });
+ agents = await db.getAgentModelSummaries(accessibleAgentIds);
}
const models = agents.map((agent) => ({
diff --git a/api/server/controllers/agents/responses.js b/api/server/controllers/agents/responses.js
index 512a28e890..55ccce3a7f 100644
--- a/api/server/controllers/agents/responses.js
+++ b/api/server/controllers/agents/responses.js
@@ -1795,7 +1795,7 @@ const listModels = async (req, res) => {
// Get the accessible agents
let agents = [];
if (accessibleAgentIds.length > 0) {
- agents = await db.getAgents({ _id: { $in: accessibleAgentIds } });
+ agents = await db.getAgentModelSummaries(accessibleAgentIds);
}
// Convert to models format
diff --git a/e2e/specs/mock/scenarios/agent-models-list.spec.ts b/e2e/specs/mock/scenarios/agent-models-list.spec.ts
new file mode 100644
index 0000000000..9dca7f2ffc
--- /dev/null
+++ b/e2e/specs/mock/scenarios/agent-models-list.spec.ts
@@ -0,0 +1,96 @@
+import { randomUUID } from 'node:crypto';
+import { expect, test } from '@playwright/test';
+import type { APIRequestContext, PlaywrightWorkerArgs } from '@playwright/test';
+import { getE2EUser } from '../../../setup/user';
+
+type ModelRow = { id: string; name?: string; description?: string; provider?: string };
+
+async function login(request: APIRequestContext): Promise<string> {
+ const { email, password } = getE2EUser();
+ const response = await request.post('/api/auth/login', { data: { email, password } });
+ expect(response.ok()).toBeTruthy();
+ return ((await response.json()) as { token: string }).token;
+}
+
+async function createAgent(request: APIRequestContext, token: string, name: string) {
+ const response = await request.post('/api/agents', {
+ headers: { Authorization: `Bearer ${token}` },
+ data: {
+ name,
+ description: 'Listed by the remote models route.',
+ provider: 'Mock Provider A',
+ model: 'mock-model-a',
+ model_parameters: {},
+ tools: [],
+ },
+ });
+ expect(response.status()).toBe(201);
+ return ((await response.json()) as { id: string }).id;
+}
+
+async function expectListedAgent(
+ playwright: PlaywrightWorkerArgs['playwright'],
+ baseURL: string | undefined,
+ path: string,
+) {
+ const request = await playwright.request.newContext({ baseURL });
+ let agentId = '';
+ let keyId = '';
+ let token = '';
+ try {
+ token = await login(request);
+ const name = `Models list ${randomUUID().slice(0, 8)}`;
+ agentId = await createAgent(request, token, name);
+ /** The remote routes authenticate with an agent API key, not the session JWT. */
+ const created = await request.post('/api/api-keys', {
+ headers: { Authorization: `Bearer ${token}` },
+ data: { name },
+ });
+ expect(created.status()).toBe(201);
+ const apiKey = (await created.json()) as { id: string; key: string };
+ keyId = apiKey.id;
+
+ const response = await request.get(path, {
+ headers: { Authorization: `Bearer ${apiKey.key}` },
+ });
+ expect(response.status()).toBe(200);
+ const { data } = (await response.json()) as { data: ModelRow[] };
+
+ expect(data.find((row) => row.id === agentId)).toMatchObject({
+ id: agentId,
+ name,
+ description: 'Listed by the remote models route.',
+ provider: 'Mock Provider A',
+ });
+ } finally {
+ if (keyId) {
+ await request.delete(`/api/api-keys/${keyId}`, {
+ headers: { Authorization: `Bearer ${token}` },
+ failOnStatusCode: false,
+ });
+ }
+ if (agentId) {
+ await request.delete(`/api/agents/${agentId}`, {
+ headers: { Authorization: `Bearer ${token}` },
+ failOnStatusCode: false,
+ });
+ }
+ await request.dispose();
+ }
+}
+
+test.describe('remote models list', () => {
+ test("the chat completions models list shows the caller's agent with its details @scenario:remote-models-list-shows-agent-details", async ({
+ playwright,
+ baseURL,
+ }) => {
+ await expectListedAgent(playwright, baseURL, '/api/agents/v1/models');
+ });
+
+ test("the responses models list shows the caller's agent with its details @scenario:remote-responses-models-list-shows-agent-details", async ({
+ playwright,
+ baseURL,
+ }) => {
+ await expectListedAgent(playwright, baseURL, '/api/agents/v1/responses/models');
+ });
+});
diff --git a/packages/api/src/cache/__tests__/keyvMongo.spec.ts b/packages/api/src/cache/__tests__/keyvMongo.spec.ts
new file mode 100644
index 0000000000..84a16333ea
--- /dev/null
+++ b/packages/api/src/cache/__tests__/keyvMongo.spec.ts
@@ -0,0 +1,57 @@
+import mongoose from 'mongoose';
+import { MongoMemoryServer } from 'mongodb-memory-server';
+import keyvMongo from '../keyvMongo';
+
+type Store = typeof keyvMongo;
+const KeyvMongo = keyvMongo.constructor as new (options: { collection: string }) => Store;
+
+let mongoServer: MongoMemoryServer;
+
+async function keyIndexNames(collection: string): Promise<string[]> {
+ const indexes = await mongoose.connection.db!.collection(collection).indexes();
+ return indexes.filter((index) => index.key.key === 1).map((index) => index.name ?? '');
+}
+
+beforeAll(async () => {
+ mongoServer = await MongoMemoryServer.create();
+});
+
+afterEach(async () => {
+ await mongoose.disconnect();
+});
+
+afterAll(async () => {
+ await mongoServer.stop();
+});
+
+describe('KeyvMongo key index', () => {
+ it('indexes the store by key once it is first used', async () => {
+ await mongoose.connect(mongoServer.getUri());
+ const store = new KeyvMongo({ collection: 'keyv_indexed' });
+
+ await store.set('ban:user-1', 'value');
+
+ await waitFor(async () => (await keyIndexNames('keyv_indexed')).length === 1);
+ await expect(store.get('ban:user-1')).resolves.toBe('value');
+ });
+
+ it('builds no index when the deployment disables auto indexing', async () => {
+ await mongoose.connect(mongoServer.getUri(), { autoIndex: false });
+ const store = new KeyvMongo({ collection: 'keyv_unindexed' });
+
+ await store.set('ban:user-1', 'value');
+ await new Promise((resolve) => setTimeout(resolve, 200));
+
+ await expect(keyIndexNames('keyv_unindexed')).resolves.toEqual([]);
+ });
+});
+
+async function waitFor(check: () => Promise<boolean>, timeoutMs = 5_000): Promise<void> {
+ const deadline = Date.now() + timeoutMs;
+ while (!(await check())) {
+ if (Date.now() > deadline) {
+ throw new Error('Timed out waiting for the key index');
+ }
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+}
diff --git a/packages/api/src/cache/keyvMongo.ts b/packages/api/src/cache/keyvMongo.ts
index d020cdedc4..fe2330d0cf 100644
--- a/packages/api/src/cache/keyvMongo.ts
+++ b/packages/api/src/cache/keyvMongo.ts
@@ -76,6 +76,13 @@ class KeyvMongoCustom extends EventEmitter {
const collection = this.opts.collection || 'keyv';
const store = db.collection(collection);
client = { store, db };
+ /** Every read and upsert filters on `key`; unindexed, each one scans the collection.
+ * Built in the background, and skipped when the deployment disables auto indexing. */
+ if (mongoose.connection.config?.autoIndex !== false) {
+ store.createIndex({ key: 1 }).catch((error: unknown) => {
+ logger.warn(`[KeyvMongo] Could not index "${collection}" by key`, error);
+ });
+ }
}
storeMap.set(storeKey, client);
diff --git a/packages/data-schemas/src/methods/action.spec.ts b/packages/data-schemas/src/methods/action.spec.ts
index 7f03d251be..94c99aa72c 100644
--- a/packages/data-schemas/src/methods/action.spec.ts
+++ b/packages/data-schemas/src/methods/action.spec.ts
@@ -123,3 +123,14 @@ describe('action criteria', () => {
expect(found.map((a) => a.action_id)).toEqual(['act-1']);
});
});
+
+describe('action indexes', () => {
+ it.each(['agent_id', 'assistant_id'])('loads actions by %s through an index', async (field) => {
+ await Action.syncIndexes();
+ await seed({ action_id: 'act-1', [field]: 'owner-1' });
+
+ const plan = await Action.find({ [field]: 'owner-1' }).explain();
+
+ expect(JSON.stringify(plan)).toContain('"IXSCAN"');
+ });
+});
diff --git a/packages/data-schemas/src/methods/agent.spec.ts b/packages/data-schemas/src/methods/agent.spec.ts
index cab240cb60..5a7802faf4 100644
--- a/packages/data-schemas/src/methods/agent.spec.ts
+++ b/packages/data-schemas/src/methods/agent.spec.ts
@@ -630,6 +630,31 @@ describe('Agent Methods', () => {
expect(nodes[0]).not.toHaveProperty('_id');
});
+ test('getAgentModelSummaries loads only the models list fields', async () => {
+ const { agentId, authorId } = createTestIds();
+ const agent = await createAgent({
+ id: agentId,
+ name: 'Listed Agent',
+ description: 'shown in the models list',
+ provider: 'test',
+ model: 'test-model',
+ author: authorId,
+ });
+
+ const summaries = await methods.getAgentModelSummaries([agent._id]);
+
+ expect(summaries).toHaveLength(1);
+ expect(summaries[0]).toMatchObject({
+ id: agentId,
+ name: 'Listed Agent',
+ description: 'shown in the models list',
+ provider: 'test',
+ });
+ expect(Object.keys(summaries[0]).sort()).toEqual(
+ ['_id', 'author', 'createdAt', 'description', 'id', 'name', 'provider'].sort(),
+ );
+ });
+
describe('MCP server name candidate lookups', () => {
test('getAgentsWithMCPServerNames returns only agents with a non-empty list, projected', async () => {
const { agentId, authorId } = createTestIds();
diff --git a/packages/data-schemas/src/methods/agent.ts b/packages/data-schemas/src/methods/agent.ts
index 5badb56376..63dbfdd304 100644
--- a/packages/data-schemas/src/methods/agent.ts
+++ b/packages/data-schemas/src/methods/agent.ts
@@ -672,6 +672,12 @@ export interface AgentDeps {
}
/** Plain projection used to discover runnable agent graphs without exposing Mongoose. */
+/** The agent fields a models list reads. */
+export type AgentModelSummary = Pick<
+ IAgent,
+ '_id' | 'id' | 'name' | 'description' | 'provider' | 'author'
+> & { createdAt?: Date };
+
export interface AgentGraphNode {
id: string;
provider: string;
@@ -1068,6 +1074,9 @@ export function createAgentMethods(
createAgent: (agentData: Record<string, unknown>) => Promise<IAgent>;
getAgentIdsByMCPServerName: (serverName: string) => Promise<Types.ObjectId[]>;
getAgentsWithMCPServerNames: () => Promise<Array<Pick<IAgent, '_id' | 'mcpServerNames'>>>;
+ getAgentModelSummaries: (
+ agentIds: Array<Types.ObjectId | string>,
+ ) => Promise<AgentModelSummary[]>;
updateAgent: (
searchParameter: FilterQuery<IAgent>,
updateData: Record<string, unknown>,
@@ -1415,6 +1424,17 @@ export function createAgentMethods(
return agents.map((agent) => agent._id);
}
+ /** Loads only the fields a models list shows, never the unbounded `versions` history. */
+ async function getAgentModelSummaries(
+ agentIds: Array<Types.ObjectId | string>,
+ ): Promise<AgentModelSummary[]> {
+ const Agent = mongoose.models.Agent as Model<IAgent>;
+ return await Agent.find(
+ { _id: { $in: agentIds } },
+ { id: 1, name: 1, description: 1, provider: 1, author: 1, createdAt: 1 },
+ ).lean<AgentModelSummary[]>();
+ }
+
/** Returns every agent with a non-empty `mcpServerNames`, so access
* calculations can start from the (typically small) set of agents that
* actually reference MCP servers instead of every accessible agent. */
@@ -2752,6 +2772,7 @@ export function createAgentMethods(
createAgent,
getAgentIdsByMCPServerName,
getAgentsWithMCPServerNames,
+ getAgentModelSummaries,
updateAgent,
updateAgentAvatar,
deleteAgent,
diff --git a/packages/data-schemas/src/methods/key.spec.ts b/packages/data-schemas/src/methods/key.spec.ts
index 7d0b498e9a..daf0b3b842 100644
--- a/packages/data-schemas/src/methods/key.spec.ts
+++ b/packages/data-schemas/src/methods/key.spec.ts
@@ -67,3 +67,14 @@ describe('user provider keys', () => {
});
});
});
+
+describe('user key indexes', () => {
+ it('reads a user key by user and name through an index', async () => {
+ await mongoose.models.Key.syncIndexes();
+ await methods.updateUserKey({ userId, name: 'openAI', value: 'sk-test' });
+
+ const plan = await mongoose.models.Key.find({ userId, name: 'openAI' }).explain();
+
+ expect(JSON.stringify(plan)).toContain('"IXSCAN"');
+ });
+});
diff --git a/packages/data-schemas/src/schema/action.ts b/packages/data-schemas/src/schema/action.ts
index 771b0301f1..edd6426298 100644
--- a/packages/data-schemas/src/schema/action.ts
+++ b/packages/data-schemas/src/schema/action.ts
@@ -33,8 +33,14 @@ const Action: mongoose.Schema<IAction> = new Schema<IAction>({
default: 'action_prototype',
},
settings: Schema.Types.Mixed,
- agent_id: String,
- assistant_id: String,
+ agent_id: {
+ type: String,
+ index: true,
+ },
+ assistant_id: {
+ type: String,
+ index: true,
+ },
metadata: {
api_key: String,
auth: AuthSchema,
diff --git a/packages/data-schemas/src/schema/key.ts b/packages/data-schemas/src/schema/key.ts
index 330eb23471..5ecf346c57 100644
--- a/packages/data-schemas/src/schema/key.ts
+++ b/packages/data-schemas/src/schema/key.ts
@@ -32,5 +32,7 @@ const keySchema: Schema<IKey> = new Schema({
});
keySchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 });
+/** Not unique: legacy databases can hold duplicate rows for one user and key name. */
+keySchema.index({ userId: 1, name: 1, tenantId: 1 });
export default keySchema;