Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(openapi): add eval read routes for runs, datasets and topics (#19423)

Rdmclin2e85ae5188021
diff --git a/packages/database/src/models/agentEval/__tests__/dataset.test.ts b/packages/database/src/models/agentEval/__tests__/dataset.test.ts
index 865e635b359..99e5d9abf9f 100644
--- a/packages/database/src/models/agentEval/__tests__/dataset.test.ts
+++ b/packages/database/src/models/agentEval/__tests__/dataset.test.ts
@@ -50,6 +50,41 @@ afterEach(async () => {
});
describe('AgentEvalDatasetModel', () => {
+ describe('queryList / count', () => {
+ beforeEach(async () => {
+ await serverDB.insert(agentEvalDatasets).values([
+ { benchmarkId, identifier: 'own-a', name: 'Own A', userId },
+ { benchmarkId, identifier: 'own-b', name: 'Own B', userId },
+ // System dataset (userId NULL) is readable by everyone
+ { benchmarkId, identifier: 'system', name: 'System' },
+ // Another user's dataset must never be listed
+ { benchmarkId, identifier: 'other', name: 'Other', userId: userId2 },
+ ]);
+ });
+
+ it('should list own and system datasets only', async () => {
+ const results = await datasetModel.queryList();
+
+ expect(results).toHaveLength(3);
+ expect(results.map((d) => d.identifier).sort()).toEqual(['own-a', 'own-b', 'system']);
+ });
+
+ it('should apply limit and offset pagination', async () => {
+ const all = await datasetModel.queryList();
+ const firstPage = await datasetModel.queryList({ limit: 2, offset: 0 });
+ const secondPage = await datasetModel.queryList({ limit: 2, offset: 2 });
+
+ expect(firstPage).toHaveLength(2);
+ expect(secondPage).toHaveLength(1);
+ expect([...firstPage, ...secondPage].map((d) => d.id)).toEqual(all.map((d) => d.id));
+ });
+
+ it('should count with the same ownership predicate', async () => {
+ expect(await datasetModel.count()).toBe(3);
+ expect(await datasetModel.count({ benchmarkId: 'nonexistent' })).toBe(0);
+ });
+ });
+
describe('create', () => {
it('should create a new dataset with userId', async () => {
const params = {
diff --git a/packages/database/src/models/agentEval/__tests__/run.test.ts b/packages/database/src/models/agentEval/__tests__/run.test.ts
index 96b3710dedb..476a5f21ef7 100644
--- a/packages/database/src/models/agentEval/__tests__/run.test.ts
+++ b/packages/database/src/models/agentEval/__tests__/run.test.ts
@@ -64,6 +64,27 @@ afterEach(async () => {
});
describe('AgentEvalRunModel', () => {
+ describe('count', () => {
+ beforeEach(async () => {
+ await serverDB.insert(agentEvalRuns).values([
+ { datasetId, status: 'completed', userId },
+ { datasetId, status: 'running', userId },
+ // Another user's run must never be counted
+ { datasetId, status: 'completed', userId: userId2 },
+ ]);
+ });
+
+ it('should count only runs owned by the user', async () => {
+ expect(await runModel.count()).toBe(2);
+ });
+
+ it('should apply status and datasetId filters', async () => {
+ expect(await runModel.count({ status: 'completed' })).toBe(1);
+ expect(await runModel.count({ datasetId })).toBe(2);
+ expect(await runModel.count({ datasetId: 'nonexistent' })).toBe(0);
+ });
+ });
+
describe('create', () => {
it('should create a new run with minimal parameters', async () => {
const params = {
diff --git a/packages/database/src/models/agentEval/__tests__/runTopic.test.ts b/packages/database/src/models/agentEval/__tests__/runTopic.test.ts
index 27b70bfcb0e..8b32bb6c8a9 100644
--- a/packages/database/src/models/agentEval/__tests__/runTopic.test.ts
+++ b/packages/database/src/models/agentEval/__tests__/runTopic.test.ts
@@ -227,6 +227,45 @@ describe('AgentEvalRunTopicModel', () => {
expect(results).toHaveLength(0);
});
+
+ it('should apply limit and offset pagination', async () => {
+ const firstPage = await runTopicModel.findByRunId(runId, { limit: 1, offset: 0 });
+ const secondPage = await runTopicModel.findByRunId(runId, { limit: 1, offset: 1 });
+
+ expect(firstPage).toHaveLength(1);
+ expect(secondPage).toHaveLength(1);
+ expect(firstPage[0].topicId).toBe(topicId1);
+ expect(secondPage[0].topicId).toBe(topicId2);
+ });
+ });
+
+ describe('countByRunId', () => {
+ beforeEach(async () => {
+ await serverDB.insert(agentEvalRunTopics).values([
+ {
+ userId,
+ runId,
+ topicId: topicId1,
+ testCaseId: testCaseId1,
+ },
+ {
+ userId,
+ runId,
+ topicId: topicId2,
+ testCaseId: testCaseId2,
+ },
+ ]);
+ });
+
+ it('should count topics of a run', async () => {
+ expect(await runTopicModel.countByRunId(runId)).toBe(2);
+ });
+
+ it('should not count rows owned by another user', async () => {
+ const otherModel = new AgentEvalRunTopicModel(serverDB, 'someone-else');
+
+ expect(await otherModel.countByRunId(runId)).toBe(0);
+ });
});
describe('deleteByRunId', () => {
diff --git a/packages/database/src/models/agentEval/dataset.ts b/packages/database/src/models/agentEval/dataset.ts
index 8882b9ada94..8a2ac55bd07 100644
--- a/packages/database/src/models/agentEval/dataset.ts
+++ b/packages/database/src/models/agentEval/dataset.ts
@@ -100,6 +100,52 @@ export class AgentEvalDatasetModel {
.orderBy(desc(agentEvalDatasets.createdAt));
};
+ /**
+ * Read-only paginated list (system + user/workspace-owned), without the
+ * test-case join used by `query`
+ */
+ queryList = async (filter?: { benchmarkId?: string; limit?: number; offset?: number }) => {
+ const conditions = [this.ownership()];
+
+ if (filter?.benchmarkId) {
+ conditions.push(eq(agentEvalDatasets.benchmarkId, filter.benchmarkId));
+ }
+
+ const query = this.db
+ .select()
+ .from(agentEvalDatasets)
+ .where(and(...conditions))
+ .orderBy(desc(agentEvalDatasets.createdAt))
+ .$dynamic();
+
+ if (filter?.limit !== undefined) {
+ query.limit(filter.limit);
+ }
+
+ if (filter?.offset !== undefined) {
+ query.offset(filter.offset);
+ }
+
+ return query;
+ };
+
+ /**
+ * Count datasets (system + user/workspace-owned) with the same predicates as `queryList`
+ */
+ count = async (filter?: { benchmarkId?: string }) => {
+ const conditions = [this.ownership()];
+
+ if (filter?.benchmarkId) {
+ conditions.push(eq(agentEvalDatasets.benchmarkId, filter.benchmarkId));
+ }
+
+ const result = await this.db
+ .select({ value: count() })
+ .from(agentEvalDatasets)
+ .where(and(...conditions));
+ return Number(result[0]?.value) || 0;
+ };
+
/**
* Find dataset by id (with test cases)
*/
diff --git a/packages/database/src/models/agentEval/run.ts b/packages/database/src/models/agentEval/run.ts
index 98727fff4ef..9b0fa187910 100644
--- a/packages/database/src/models/agentEval/run.ts
+++ b/packages/database/src/models/agentEval/run.ts
@@ -81,6 +81,30 @@ export class AgentEvalRunModel {
return query;
};
+ /**
+ * Count runs with optional filters (same predicates as `query`)
+ */
+ count = async (filter?: {
+ datasetId?: string;
+ status?: 'idle' | 'pending' | 'running' | 'completed' | 'failed' | 'aborted' | 'external';
+ }) => {
+ const conditions = [this.ownership()];
+
+ if (filter?.datasetId) {
+ conditions.push(eq(agentEvalRuns.datasetId, filter.datasetId));
+ }
+
+ if (filter?.status) {
+ conditions.push(eq(agentEvalRuns.status, filter.status));
+ }
+
+ const result = await this.db
+ .select({ value: count() })
+ .from(agentEvalRuns)
+ .where(and(...conditions));
+ return Number(result[0]?.value) || 0;
+ };
+
/**
* Find run by id
*/
diff --git a/packages/database/src/models/agentEval/runTopic.ts b/packages/database/src/models/agentEval/runTopic.ts
index 695df03de87..5dcd643deab 100644
--- a/packages/database/src/models/agentEval/runTopic.ts
+++ b/packages/database/src/models/agentEval/runTopic.ts
@@ -1,4 +1,4 @@
-import { and, asc, desc, eq, lt, or } from 'drizzle-orm';
+import { and, asc, count, desc, eq, lt, or } from 'drizzle-orm';
import {
agentEvalRuns,
@@ -41,8 +41,8 @@ export class AgentEvalRunTopicModel {
/**
* Find all topics for a run (with TestCase and Topic details)
*/
- findByRunId = async (runId: string) => {
- const rows = await this.db
+ findByRunId = async (runId: string, pagination?: { limit?: number; offset?: number }) => {
+ const query = this.db
.select({
createdAt: agentEvalRunTopics.createdAt,
evalResult: agentEvalRunTopics.evalResult,
@@ -59,9 +59,29 @@ export class AgentEvalRunTopicModel {
.leftJoin(agentEvalTestCases, eq(agentEvalRunTopics.testCaseId, agentEvalTestCases.id))
.leftJoin(topics, eq(agentEvalRunTopics.topicId, topics.id))
.where(and(eq(agentEvalRunTopics.runId, runId), this.ownership()))
- .orderBy(asc(agentEvalTestCases.sortOrder));
+ .orderBy(asc(agentEvalTestCases.sortOrder))
+ .$dynamic();
- return rows;
+ if (pagination?.limit !== undefined) {
+ query.limit(pagination.limit);
+ }
+
+ if (pagination?.offset !== undefined) {
+ query.offset(pagination.offset);
+ }
+
+ return query;
+ };
+
+ /**
+ * Count topics for a run
+ */
+ countByRunId = async (runId: string) => {
+ const result = await this.db
+ .select({ value: count() })
+ .from(agentEvalRunTopics)
+ .where(and(eq(agentEvalRunTopics.runId, runId), this.ownership()));
+ return Number(result[0]?.value) || 0;
};
/**
diff --git a/packages/openapi/openapi.yml b/packages/openapi/openapi.yml
index 482112ac5db..6270752a5f0 100644
--- a/packages/openapi/openapi.yml
+++ b/packages/openapi/openapi.yml
@@ -3409,6 +3409,351 @@ paths:
- datasetId
- targetAgentId
additionalProperties: false
+ get:
+ operationId: getApiV1EvalRuns
+ summary: List eval runs
+ tags:
+ - eval
+ responses:
+ "200":
+ content:
+ application/json:
+ schema:
+ additionalProperties: false
+ properties:
+ data:
+ $ref: "#/components/schemas/EvalRun"
+ message:
+ type: string
+ success:
+ const: true
+ type: boolean
+ timestamp:
+ format: date-time
+ type: string
+ required:
+ - success
+ - timestamp
+ type: object
+ description: Successful response
+ "400":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Invalid request
+ "401":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Authentication required
+ "403":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Insufficient permission
+ "404":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Resource not found
+ "409":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Resource conflict
+ "429":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Rate limit exceeded
+ "500":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Internal server error
+ parameters:
+ - in: query
+ name: page
+ schema:
+ type: string
+ - in: query
+ name: pageSize
+ schema:
+ type: string
+ - in: query
+ name: datasetId
+ schema:
+ type: string
+ minLength: 1
+ maxLength: 128
+ - in: query
+ name: status
+ schema:
+ type: string
+ enum:
+ - idle
+ - pending
+ - running
+ - completed
+ - failed
+ - aborted
+ - external
+ /api/v1/eval/datasets:
+ get:
+ operationId: getApiV1EvalDatasets
+ summary: List eval datasets
+ tags:
+ - eval
+ responses:
+ "200":
+ content:
+ application/json:
+ schema:
+ additionalProperties: false
+ properties:
+ data:
+ $ref: "#/components/schemas/EvalRun"
+ message:
+ type: string
+ success:
+ const: true
+ type: boolean
+ timestamp:
+ format: date-time
+ type: string
+ required:
+ - success
+ - timestamp
+ type: object
+ description: Successful response
+ "400":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Invalid request
+ "401":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Authentication required
+ "403":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Insufficient permission
+ "404":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Resource not found
+ "409":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Resource conflict
+ "429":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Rate limit exceeded
+ "500":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Internal server error
+ parameters:
+ - in: query
+ name: page
+ schema:
+ type: string
+ - in: query
+ name: pageSize
+ schema:
+ type: string
+ - in: query
+ name: benchmarkId
+ schema:
+ type: string
+ minLength: 1
+ maxLength: 128
+ /api/v1/eval/datasets/{id}:
+ get:
+ operationId: getApiV1EvalDatasetsById
+ summary: Get an eval dataset
+ tags:
+ - eval
+ responses:
+ "200":
+ content:
+ application/json:
+ schema:
+ additionalProperties: false
+ properties:
+ data:
+ $ref: "#/components/schemas/EvalRun"
+ message:
+ type: string
+ success:
+ const: true
+ type: boolean
+ timestamp:
+ format: date-time
+ type: string
+ required:
+ - success
+ - timestamp
+ type: object
+ description: Successful response
+ "400":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Invalid request
+ "401":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Authentication required
+ "403":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Insufficient permission
+ "404":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Resource not found
+ "409":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Resource conflict
+ "429":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Rate limit exceeded
+ "500":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Internal server error
+ parameters:
+ - in: path
+ name: id
+ schema:
+ type: string
+ minLength: 1
+ maxLength: 128
+ required: true
+ /api/v1/eval/runs/{id}/topics:
+ get:
+ operationId: getApiV1EvalRunsByIdTopics
+ summary: List topic results of an eval run
+ tags:
+ - eval
+ responses:
+ "200":
+ content:
+ application/json:
+ schema:
+ additionalProperties: false
+ properties:
+ data:
+ $ref: "#/components/schemas/EvalRun"
+ message:
+ type: string
+ success:
+ const: true
+ type: boolean
+ timestamp:
+ format: date-time
+ type: string
+ required:
+ - success
+ - timestamp
+ type: object
+ description: Successful response
+ "400":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Invalid request
+ "401":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Authentication required
+ "403":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Insufficient permission
+ "404":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Resource not found
+ "409":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Resource conflict
+ "429":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Rate limit exceeded
+ "500":
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiError"
+ description: Internal server error
+ parameters:
+ - in: path
+ name: id
+ schema:
+ type: string
+ minLength: 1
+ maxLength: 128
+ required: true
+ - in: query
+ name: page
+ schema:
+ type: string
+ - in: query
+ name: pageSize
+ schema:
+ type: string
/api/v1/eval/runs/{id}:
get:
operationId: getApiV1EvalRunsById
diff --git a/packages/openapi/scripts/generate-openapi.ts b/packages/openapi/scripts/generate-openapi.ts
index 19dec71581a..3636244d7c7 100644
--- a/packages/openapi/scripts/generate-openapi.ts
+++ b/packages/openapi/scripts/generate-openapi.ts
@@ -27,9 +27,17 @@ const PKG_ROOT = path.join(import.meta.dirname, '..');
const SPEC_PATH = path.join(PKG_ROOT, 'openapi.yml');
const HTTP_METHODS = new Set(['DELETE', 'GET', 'PATCH', 'POST', 'PUT']);
-// Documentation-serving routes: real endpoints, deliberately not part of the
-// API surface described by the spec.
-const SPEC_EXEMPT = new Set(['GET /api/v1/docs', 'GET /api/v1/openapi.json']);
+// Real endpoints deliberately kept out of the API surface described by the
+// spec: the documentation routes themselves, plus the heterogeneous-agent
+// relays. The relays speak the Anthropic/OpenAI wire formats and are gated by
+// `requireHeteroModelInvocation` (operation JWT), so no API key holder can
+// call them and their schemas belong to the upstream vendors, not LobeHub.
+const SPEC_EXEMPT = new Set([
+ 'GET /api/v1/docs',
+ 'GET /api/v1/openapi.json',
+ 'POST /api/v1/anthropic/v1/messages',
+ 'POST /api/v1/openai/v1/responses',
+]);
// Import after the env defaults above are in place.
const { honoApp } = await import('../src/app');
diff --git a/packages/openapi/src/controllers/eval.controller.ts b/packages/openapi/src/controllers/eval.controller.ts
index 4ddecfaa66d..7cf27150b6d 100644
--- a/packages/openapi/src/controllers/eval.controller.ts
+++ b/packages/openapi/src/controllers/eval.controller.ts
@@ -2,7 +2,12 @@ import type { Context } from 'hono';
import { BaseController } from '../common/base.controller';
import { EvalService } from '../services/eval.service';
-import type { CreateEvalRunRequest } from '../types/eval.type';
+import type {
+ CreateEvalRunRequest,
+ EvalDatasetListQuery,
+ EvalRunListQuery,
+ EvalRunTopicListQuery,
+} from '../types/eval.type';
export class EvalController extends BaseController {
private async getService(c: Context) {
@@ -20,6 +25,59 @@ export class EvalController extends BaseController {
}
}
+ async listRuns(c: Context) {
+ try {
+ const query = this.getQuery<EvalRunListQuery>(c);
+ return this.success(
+ c,
+ await (await this.getService(c)).listRuns(query),
+ 'Eval runs retrieved',
+ );
+ } catch (error) {
+ return this.handleError(c, error);
+ }
+ }
+
+ async listDatasets(c: Context) {
+ try {
+ const query = this.getQuery<EvalDatasetListQuery>(c);
+ return this.success(
+ c,
+ await (await this.getService(c)).listDatasets(query),
+ 'Eval datasets retrieved',
+ );
+ } catch (error) {
+ return this.handleError(c, error);
+ }
+ }
+
+ async getDataset(c: Context) {
+ try {
+ const { id } = this.getParams<{ id: string }>(c);
+ return this.success(
+ c,
+ await (await this.getService(c)).getDataset(id),
+ 'Eval dataset retrieved',
+ );
+ } catch (error) {
+ return this.handleError(c, error);
+ }
+ }
+
+ async getRunTopics(c: Context) {
+ try {
+ const { id } = this.getParams<{ id: string }>(c);
+ const query = this.getQuery<EvalRunTopicListQuery>(c);
+ return this.success(
+ c,
+ await (await this.getService(c)).getRunTopics(id, query),
+ 'Eval run topics retrieved',
+ );
+ } catch (error) {
+ return this.handleError(c, error);
+ }
+ }
+
async getRun(c: Context) {
try {
const { id } = this.getParams<{ id: string }>(c);
diff --git a/packages/openapi/src/helpers/public-fields.ts b/packages/openapi/src/helpers/public-fields.ts
index 5022c9d97d0..782084f5b27 100644
--- a/packages/openapi/src/helpers/public-fields.ts
+++ b/packages/openapi/src/helpers/public-fields.ts
@@ -1,4 +1,8 @@
import type {
+ AgentEvalDatasetItem,
+ AgentEvalRunItem,
+ AgentEvalRunTopicItem,
+ AgentEvalTestCaseItem,
AgentItem,
AiModelSelectItem,
AiProviderSelectItem,
@@ -220,6 +224,58 @@ export const PUBLIC_PERMISSION_FIELDS = [
'updatedAt',
] as const satisfies readonly (keyof PermissionItem)[];
+export const PUBLIC_EVAL_RUN_FIELDS = [
+ 'config',
+ 'createdAt',
+ 'datasetId',
+ 'experimentId',
+ 'id',
+ 'metrics',
+ 'name',
+ 'parentRunId',
+ 'startedAt',
+ 'status',
+ 'targetAgentId',
+ 'updatedAt',
+] as const satisfies readonly (keyof AgentEvalRunItem)[];
+
+export const PUBLIC_EVAL_DATASET_FIELDS = [
+ 'benchmarkId',
+ 'createdAt',
+ 'description',
+ 'evalConfig',
+ 'evalMode',
+ 'id',
+ 'identifier',
+ 'metadata',
+ 'name',
+ 'sourceExperimentId',
+ 'updatedAt',
+] as const satisfies readonly (keyof AgentEvalDatasetItem)[];
+
+export const PUBLIC_EVAL_TEST_CASE_FIELDS = [
+ 'content',
+ 'createdAt',
+ 'datasetId',
+ 'evalConfig',
+ 'evalMode',
+ 'id',
+ 'metadata',
+ 'sortOrder',
+ 'updatedAt',
+] as const satisfies readonly (keyof AgentEvalTestCaseItem)[];
+
+export const PUBLIC_EVAL_RUN_TOPIC_FIELDS = [
+ 'createdAt',
+ 'evalResult',
+ 'passed',
+ 'runId',
+ 'score',
+ 'status',
+ 'testCaseId',
+ 'topicId',
+] as const satisfies readonly (keyof AgentEvalRunTopicItem)[];
+
export type PublicAgent = Pick<AgentItem, (typeof PUBLIC_AGENT_FIELDS)[number]>;
export type PublicUser = Pick<UserItem, (typeof PUBLIC_USER_FIELDS)[number]>;
export type PublicProvider = Pick<AiProviderSelectItem, (typeof PUBLIC_PROVIDER_FIELDS)[number]>;
@@ -233,6 +289,19 @@ export type PublicAgentGroup = Pick<SessionGroupItem, (typeof PUBLIC_AGENT_GROUP
export type PublicSession = Pick<SessionItem, (typeof PUBLIC_SESSION_FIELDS)[number]>;
export type PublicTopic = Pick<TopicItem, (typeof PUBLIC_TOPIC_FIELDS)[number]>;
export type PublicMessage = Pick<MessageItem, (typeof PUBLIC_MESSAGE_FIELDS)[number]>;
+export type PublicEvalRun = Pick<AgentEvalRunItem, (typeof PUBLIC_EVAL_RUN_FIELDS)[number]>;
+export type PublicEvalDataset = Pick<
+ AgentEvalDatasetItem,
+ (typeof PUBLIC_EVAL_DATASET_FIELDS)[number]
+>;
+export type PublicEvalTestCase = Pick<
+ AgentEvalTestCaseItem,
+ (typeof PUBLIC_EVAL_TEST_CASE_FIELDS)[number]
+>;
+export type PublicEvalRunTopic = Pick<
+ AgentEvalRunTopicItem,
+ (typeof PUBLIC_EVAL_RUN_TOPIC_FIELDS)[number]
+>;
export type PublicRole = Pick<RoleItem, (typeof PUBLIC_ROLE_FIELDS)[number]>;
export type PublicPermission = Pick<PermissionItem, (typeof PUBLIC_PERMISSION_FIELDS)[number]>;
@@ -266,6 +335,20 @@ export const projectPublicTopic = (value: TopicItem): PublicTopic =>
export const projectPublicMessage = (value: MessageItem): PublicMessage =>
pickPublicFields(value, PUBLIC_MESSAGE_FIELDS);
+export const projectPublicEvalRun = (value: AgentEvalRunItem): PublicEvalRun =>
+ pickPublicFields(value, PUBLIC_EVAL_RUN_FIELDS);
+
+export const projectPublicEvalDataset = (value: AgentEvalDatasetItem): PublicEvalDataset =>
+ pickPublicFields(value, PUBLIC_EVAL_DATASET_FIELDS);
+
+export const projectPublicEvalTestCase = (value: AgentEvalTestCaseItem): PublicEvalTestCase =>
+ pickPublicFields(value, PUBLIC_EVAL_TEST_CASE_FIELDS);
+
+// Accepts any row that carries the public columns (e.g. joined run-topic rows
+// without userId/workspaceId), while still projecting only the public fields.
+export const projectPublicEvalRunTopic = (value: PublicEvalRunTopic): PublicEvalRunTopic =>
+ pickPublicFields(value, PUBLIC_EVAL_RUN_TOPIC_FIELDS);
+
export const projectPublicRole = (value: RoleItem): PublicRole =>
pickPublicFields(value, PUBLIC_ROLE_FIELDS);
diff --git a/packages/openapi/src/routes/eval.route.ts b/packages/openapi/src/routes/eval.route.ts
index 855c0c5e7ec..309a4673504 100644
--- a/packages/openapi/src/routes/eval.route.ts
+++ b/packages/openapi/src/routes/eval.route.ts
@@ -7,7 +7,14 @@ import { zValidator } from '../common/validator';
import { EvalController } from '../controllers/eval.controller';
import { requireAuth } from '../middleware/auth';
import { requireAnyPermission, requireApiKeyScope } from '../middleware/permission-check';
-import { CreateEvalRunRequestSchema, EvalRunIdParamSchema } from '../types/eval.type';
+import {
+ CreateEvalRunRequestSchema,
+ EvalDatasetIdParamSchema,
+ EvalDatasetListQuerySchema,
+ EvalRunIdParamSchema,
+ EvalRunListQuerySchema,
+ EvalRunTopicListQuerySchema,
+} from '../types/eval.type';
const app = new Hono();
const requireRead = requireAnyPermission(getAllScopePermissions('AGENT_READ'));
@@ -31,6 +38,43 @@ app.post(
async (c) => new EvalController().createRun(c),
);
+app.get(
+ '/runs',
+ describeRoute({ summary: 'List eval runs', tags: ['eval'] }),
+ requireAuth,
+ requireRead,
+ zValidator('query', EvalRunListQuerySchema),
+ async (c) => new EvalController().listRuns(c),
+);
+
+app.get(
+ '/datasets',
+ describeRoute({ summary: 'List eval datasets', tags: ['eval'] }),
+ requireAuth,
+ requireRead,
+ zValidator('query', EvalDatasetListQuerySchema),
+ async (c) => new EvalController().listDatasets(c),
+);
+
+app.get(
+ '/datasets/:id',
+ describeRoute({ summary: 'Get an eval dataset', tags: ['eval'] }),
+ requireAuth,
+ requireRead,
+ zValidator('param', EvalDatasetIdParamSchema),
+ async (c) => new EvalController().getDataset(c),
+);
+
+app.get(
+ '/runs/:id/topics',
+ describeRoute({ summary: 'List topic results of an eval run', tags: ['eval'] }),
+ requireAuth,
+ requireRead,
+ zValidator('param', EvalRunIdParamSchema),
+ zValidator('query', EvalRunTopicListQuerySchema),
+ async (c) => new EvalController().getRunTopics(c),
+);
+
app.get(
'/runs/:id',
requireAuth,
diff --git a/packages/openapi/src/services/eval.service.test.ts b/packages/openapi/src/services/eval.service.test.ts
new file mode 100644
index 00000000000..9fba132b692
--- /dev/null
+++ b/packages/openapi/src/services/eval.service.test.ts
@@ -0,0 +1,258 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { LobeChatDatabase } from '@/database/type';
+
+import { EvalService } from './eval.service';
+
+const {
+ datasetCountMock,
+ datasetFindByIdMock,
+ datasetQueryListMock,
+ runCountMock,
+ runFindByIdMock,
+ runQueryMock,
+ runTopicCountByRunIdMock,
+ runTopicFindByRunIdMock,
+} = vi.hoisted(() => ({
+ datasetCountMock: vi.fn(),
+ datasetFindByIdMock: vi.fn(),
+ datasetQueryListMock: vi.fn(),
+ runCountMock: vi.fn(),
+ runFindByIdMock: vi.fn(),
+ runQueryMock: vi.fn(),
+ runTopicCountByRunIdMock: vi.fn(),
+ runTopicFindByRunIdMock: vi.fn(),
+}));
+
+vi.mock('@/const/rbac', () => ({ ALL_SCOPE: 'all' }));
+vi.mock('@lobechat/database', () => ({
+ buildWorkspacePayload: vi.fn(),
+ buildWorkspaceWhere: vi.fn(),
+}));
+vi.mock('@/utils/rbac', () => ({ getScopePermissions: () => [] }));
+vi.mock('@/database/models/rbac', () => ({ RbacModel: class {} }));
+vi.mock('@/database/schemas', () => ({
+ agents: {},
+ aiModels: {},
+ aiProviders: {},
+ files: {},
+ knowledgeBases: {},
+ messages: {},
+ sessions: {},
+ topics: {},
+}));
+vi.mock('@/database/models/agentEval', () => ({
+ AgentEvalDatasetModel: class {
+ count = datasetCountMock;
+ findById = datasetFindByIdMock;
+ queryList = datasetQueryListMock;
+ },
+ AgentEvalRunModel: class {
+ count = runCountMock;
+ findById = runFindByIdMock;
+ query = runQueryMock;
+ },
+ AgentEvalRunTopicModel: class {
+ countByRunId = runTopicCountByRunIdMock;
+ findByRunId = runTopicFindByRunIdMock;
+ },
+}));
+vi.mock('@/server/services/agentEvalRun', () => ({
+ AgentEvalRunService: class {},
+ RUN_CREATE_ID_CONFLICT: 'RUN_CREATE_ID_CONFLICT',
+}));
+vi.mock('@/server/workflows/agentEvalRun', () => ({
+ AgentEvalRunWorkflow: { triggerRunBenchmark: vi.fn() },
+}));
+
+const now = new Date('2026-01-01T00:00:00Z');
+
+const runRow = {
+ clientId: 'internal-client',
+ config: { k: 1 },
+ createdAt: now,
+ datasetId: 'ds-1',
+ experimentId: null,
+ id: 'run-1',
+ metrics: null,
+ name: 'run one',
+ parentRunId: null,
+ startedAt: null,
+ status: 'completed',
+ targetAgentId: 'agent-1',
+ updatedAt: now,
+ userId: 'user-1',
+ workspaceId: 'ws-1',
+};
+
+const datasetRow = {
+ benchmarkId: 'bm-1',
+ createdAt: now,
+ description: null,
+ evalConfig: null,
+ evalMode: null,
+ id: 'ds-1',
+ identifier: 'my-dataset',
+ metadata: null,
+ name: 'dataset one',
+ sourceExperimentId: null,
+ updatedAt: now,
+ userId: 'user-1',
+ workspaceId: null,
+};
+
+const service = () => new EvalService({} as LobeChatDatabase, 'user-1', 'ws-1');
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('EvalService.listRuns', () => {
+ it('translates page/pageSize into limit/offset and forwards filters', async () => {
+ runQueryMock.mockResolvedValue([]);
+ runCountMock.mockResolvedValue(0);
+
+ await service().listRuns({ datasetId: 'ds-1', page: 3, pageSize: 5, status: 'completed' });
+
+ expect(runQueryMock).toHaveBeenCalledWith({
+ datasetId: 'ds-1',
+ limit: 5,
+ offset: 10,
+ status: 'completed',
+ });
+ expect(runCountMock).toHaveBeenCalledWith({ datasetId: 'ds-1', status: 'completed' });
+ });
+
+ it('returns projected runs without internal columns, plus total', async () => {
+ runQueryMock.mockResolvedValue([runRow]);
+ runCountMock.mockResolvedValue(42);
+
+ const result = await service().listRuns({});
+
+ expect(result.total).toBe(42);
+ expect(result.runs).toHaveLength(1);
+ expect(result.runs[0]).not.toHaveProperty('userId');
+ expect(result.runs[0]).not.toHaveProperty('workspaceId');
+ expect(result.runs[0]).not.toHaveProperty('clientId');
+ expect(result.runs[0]).toMatchObject({ datasetId: 'ds-1', id: 'run-1', status: 'completed' });
+ });
+});
+
+describe('EvalService.listDatasets', () => {
+ it('applies default pagination (page 1 / 20 items)', async () => {
+ datasetQueryListMock.mockResolvedValue([]);
+ datasetCountMock.mockResolvedValue(0);
+
+ await service().listDatasets({});
+
+ expect(datasetQueryListMock).toHaveBeenCalledWith({
+ benchmarkId: undefined,
+ limit: 20,
+ offset: 0,
+ });
+ });
+
+ it('returns projected datasets without internal columns', async () => {
+ datasetQueryListMock.mockResolvedValue([datasetRow]);
+ datasetCountMock.mockResolvedValue(1);
+
+ const result = await service().listDatasets({ page: 1, pageSize: 10 });
+
+ expect(result.total).toBe(1);
+ expect(result.datasets[0]).not.toHaveProperty('userId');
+ expect(result.datasets[0]).not.toHaveProperty('workspaceId');
+ expect(result.datasets[0]).toMatchObject({ id: 'ds-1', identifier: 'my-dataset' });
+ });
+});
+
+describe('EvalService.getDataset', () => {
+ it('throws NotFoundError when the dataset belongs to someone else (model filters it out)', async () => {
+ datasetFindByIdMock.mockResolvedValue(undefined);
+
+ await expect(service().getDataset('ds-other')).rejects.toMatchObject({
+ message: 'Eval dataset not found',
+ name: 'NotFoundError',
+ });
+ });
+
+ it('projects the dataset and its test cases', async () => {
+ datasetFindByIdMock.mockResolvedValue({
+ ...datasetRow,
+ testCases: [
+ {
+ content: { input: 'q1' },
+ createdAt: now,
+ datasetId: 'ds-1',
+ evalConfig: null,
+ evalMode: null,
+ id: 'tc-1',
+ metadata: null,
+ sortOrder: 1,
+ updatedAt: now,
+ userId: 'user-1',
+ workspaceId: null,
+ },
+ ],
+ });
+
+ const result = await service().getDataset('ds-1');
+
+ expect(result).not.toHaveProperty('userId');
+ expect(result).not.toHaveProperty('workspaceId');
+ expect(result.testCases).toHaveLength(1);
+ expect(result.testCases[0]).not.toHaveProperty('userId');
+ expect(result.testCases[0]).not.toHaveProperty('workspaceId');
+ expect(result.testCases[0]).toMatchObject({ content: { input: 'q1' }, id: 'tc-1' });
+ });
+});
+
+describe('EvalService.getRunTopics', () => {
+ it('throws NotFoundError for a run owned by someone else, before touching topics', async () => {
+ runFindByIdMock.mockResolvedValue(undefined);
+
+ await expect(service().getRunTopics('run-other', {})).rejects.toMatchObject({
+ message: 'Eval run not found',
+ name: 'NotFoundError',
+ });
+ expect(runTopicFindByRunIdMock).not.toHaveBeenCalled();
+ });
+
+ it('paginates and projects run topics without internal columns', async () => {
+ runFindByIdMock.mockResolvedValue(runRow);
+ runTopicFindByRunIdMock.mockResolvedValue([
+ {
+ createdAt: now,
+ evalResult: { passAtK: true },
+ passed: true,
+ runId: 'run-1',
+ score: 0.9,
+ status: 'passed',
+ testCase: { content: { input: 'q1' }, id: 'tc-1' },
+ testCaseId: 'tc-1',
+ topic: { id: 'topic-1' },
+ topicId: 'topic-1',
+ userId: 'user-1',
+ workspaceId: 'ws-1',
+ },
+ ]);
+ runTopicCountByRunIdMock.mockResolvedValue(7);
+
+ const result = await service().getRunTopics('run-1', { page: 2, pageSize: 3 });
+
+ expect(runTopicFindByRunIdMock).toHaveBeenCalledWith('run-1', { limit: 3, offset: 3 });
+ expect(result.runId).toBe('run-1');
+ expect(result.total).toBe(7);
+ expect(result.topics).toHaveLength(1);
+ expect(result.topics[0]).not.toHaveProperty('userId');
+ expect(result.topics[0]).not.toHaveProperty('workspaceId');
+ expect(result.topics[0]).not.toHaveProperty('testCase');
+ expect(result.topics[0]).not.toHaveProperty('topic');
+ expect(result.topics[0]).toMatchObject({
+ input: 'q1',
+ passed: true,
+ testCaseId: 'tc-1',
+ topicId: 'topic-1',
+ });
+ });
+});
diff --git a/packages/openapi/src/services/eval.service.ts b/packages/openapi/src/services/eval.service.ts
index 8e29cfd02b6..3f9ec70e5a0 100644
--- a/packages/openapi/src/services/eval.service.ts
+++ b/packages/openapi/src/services/eval.service.ts
@@ -1,16 +1,34 @@
import type { EvalRunTopicResult } from '@lobechat/types';
-import { AgentEvalRunModel, AgentEvalRunTopicModel } from '@/database/models/agentEval';
+import {
+ AgentEvalDatasetModel,
+ AgentEvalRunModel,
+ AgentEvalRunTopicModel,
+} from '@/database/models/agentEval';
import type { AgentEvalRunItem } from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
import { AgentEvalRunService, RUN_CREATE_ID_CONFLICT } from '@/server/services/agentEvalRun';
import { AgentEvalRunWorkflow } from '@/server/workflows/agentEvalRun';
import { BaseService } from '../common/base.service';
+import { processPaginationConditions } from '../helpers/pagination';
+import {
+ projectPublicEvalDataset,
+ projectPublicEvalRun,
+ projectPublicEvalRunTopic,
+ projectPublicEvalTestCase,
+} from '../helpers/public-fields';
import type {
CreateEvalRunRequest,
+ EvalDatasetDetailResponse,
+ EvalDatasetListQuery,
+ EvalDatasetListResponse,
+ EvalRunListQuery,
+ EvalRunListResponse,
EvalRunResponse,
EvalRunResultsResponse,
+ EvalRunTopicListQuery,
+ EvalRunTopicListResponse,
} from '../types/eval.type';
const projectRun = (run: AgentEvalRunItem): EvalRunResponse => ({
@@ -63,12 +81,14 @@ const projectResult = (value: EvalRunTopicResult | null): EvalRunTopicResult | n
};
export class EvalService extends BaseService {
+ private datasetModel: AgentEvalDatasetModel;
private runModel: AgentEvalRunModel;
private runService: AgentEvalRunService;
private runTopicModel: AgentEvalRunTopicModel;
constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
super(db, userId, workspaceId);
+ this.datasetModel = new AgentEvalDatasetModel(db, userId, workspaceId);
this.runModel = new AgentEvalRunModel(db, userId, workspaceId);
this.runService = new AgentEvalRunService(db, userId, workspaceId);
this.runTopicModel = new AgentEvalRunTopicModel(db, userId, workspaceId);
@@ -105,6 +125,64 @@ export class EvalService extends BaseService {
return projectRun(run);
}
+ async listRuns(query: EvalRunListQuery): Promise<EvalRunListResponse> {
+ const { limit, offset } = processPaginationConditions(query);
+ const filter = { datasetId: query.datasetId, status: query.status };
+
+ const [runs, total] = await Promise.all([
+ this.runModel.query({ ...filter, limit, offset }),
+ this.runModel.count(filter),
+ ]);
+
+ return { runs: runs.map(projectPublicEvalRun), total };
+ }
+
+ async listDatasets(query: EvalDatasetListQuery): Promise<EvalDatasetListResponse> {
+ const { limit, offset } = processPaginationConditions(query);
+ const filter = { benchmarkId: query.benchmarkId };
+
+ const [datasets, total] = await Promise.all([
+ this.datasetModel.queryList({ ...filter, limit, offset }),
+ this.datasetModel.count(filter),
+ ]);
+
+ return { datasets: datasets.map(projectPublicEvalDataset), total };
+ }
+
+ async getDataset(id: string): Promise<EvalDatasetDetailResponse> {
+ const dataset = await this.datasetModel.findById(id);
+ if (!dataset) throw this.createNotFoundError('Eval dataset not found');
+
+ const { testCases, ...rest } = dataset;
+
+ return {
+ ...projectPublicEvalDataset(rest),
+ testCases: testCases.map(projectPublicEvalTestCase),
+ };
+ }
+
+ async getRunTopics(id: string, query: EvalRunTopicListQuery): Promise<EvalRunTopicListResponse> {
+ // Ownership check first: a run owned by someone else is a plain 404.
+ const run = await this.runModel.findById(id);
+ if (!run) throw this.createNotFoundError('Eval run not found');
+
+ const { limit, offset } = processPaginationConditions(query);
+
+ const [rows, total] = await Promise.all([
+ this.runTopicModel.findByRunId(id, { limit, offset }),
+ this.runTopicModel.countByRunId(id),
+ ]);
+
+ return {
+ runId: id,
+ topics: rows.map((row) => ({
+ ...projectPublicEvalRunTopic(row),
+ input: row.testCase?.content.input ?? '',
+ })),
+ total,
+ };
+ }
+
async getRun(id: string): Promise<EvalRunResponse> {
// getRunDetails also applies the existing timeout reconciliation logic.
const detail = await this.runService.getRunDetails(id);
diff --git a/packages/openapi/src/types/eval.type.ts b/packages/openapi/src/types/eval.type.ts
index a34c120c98c..f84834c4963 100644
--- a/packages/openapi/src/types/eval.type.ts
+++ b/packages/openapi/src/types/eval.type.ts
@@ -1,6 +1,15 @@
import type { EvalRunMetrics, EvalRunTopicResult } from '@lobechat/types';
import { z } from 'zod';
+import type {
+ PublicEvalDataset,
+ PublicEvalRun,
+ PublicEvalRunTopic,
+ PublicEvalTestCase,
+} from '../helpers/public-fields';
+import type { PaginationQueryResponse } from './common.type';
+import { PaginationQuerySchema } from './common.type';
+
export const CreateEvalRunRequestSchema = z
.object({
config: z
@@ -25,7 +34,27 @@ export const CreateEvalRunRequestSchema = z
export const EvalRunIdParamSchema = z.object({ id: z.string().min(1).max(128) });
+export const EvalDatasetIdParamSchema = z.object({ id: z.string().min(1).max(128) });
+
+const EvalPaginationQuerySchema = PaginationQuerySchema.pick({ page: true, pageSize: true });
+
+export const EvalRunListQuerySchema = EvalPaginationQuerySchema.extend({
+ datasetId: z.string().min(1).max(128).optional(),
+ status: z
+ .enum(['idle', 'pending', 'running', 'completed', 'failed', 'aborted', 'external'])
+ .optional(),
+});
+
+export const EvalDatasetListQuerySchema = EvalPaginationQuerySchema.extend({
+ benchmarkId: z.string().min(1).max(128).optional(),
+});
+
+export const EvalRunTopicListQuerySchema = EvalPaginationQuerySchema;
+
export type CreateEvalRunRequest = z.infer<typeof CreateEvalRunRequestSchema>;
+export type EvalRunListQuery = z.infer<typeof EvalRunListQuerySchema>;
+export type EvalDatasetListQuery = z.infer<typeof EvalDatasetListQuerySchema>;
+export type EvalRunTopicListQuery = z.infer<typeof EvalRunTopicListQuerySchema>;
export interface EvalRunResponse {
createdAt: Date;
@@ -55,3 +84,20 @@ export interface EvalRunResultsResponse {
runId: string;
total: number;
}
+
+export type EvalRunListResponse = PaginationQueryResponse<{ runs: PublicEvalRun[] }>;
+
+export type EvalDatasetListResponse = PaginationQueryResponse<{ datasets: PublicEvalDataset[] }>;
+
+export interface EvalDatasetDetailResponse extends PublicEvalDataset {
+ testCases: PublicEvalTestCase[];
+}
+
+export interface EvalRunTopicResponse extends PublicEvalRunTopic {
+ input: string;
+}
+
+export type EvalRunTopicListResponse = PaginationQueryResponse<{
+ runId: string;
+ topics: EvalRunTopicResponse[];
+}>;