Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 74 additions & 8 deletions src/core/eval.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -781,6 +781,19 @@ export class EvalClient implements CoreEvalClient {
input: StartBatchEvaluationInput,
options: CoreOptions,
): Promise<StartBatchEvaluationResponse> {
if (input.groundTruth !== undefined && !Array.isArray(input.groundTruth)) {
throw new InputValidationError(
"Invalid value for option '--ground-truth': expected a JSON array",
);
}
for (const [index, metadata] of (input.groundTruth ?? []).entries()) {
if (!isPlainObject(metadata)) {
throw new InputValidationError(
`Invalid value for option '--ground-truth': entry ${index} must be a JSON object`,
);
}
requireGroundTruthSessionId(metadata.sessionId, index, "sessionId");
}
const dataSourceConfig = await this.dataSourceConfigForSource(input.source, options);
return this.clients.data(toClientConfig(options)).send(
new StartBatchEvaluationCommand({
Expand Down Expand Up @@ -907,11 +920,34 @@ export class EvalClient implements CoreEvalClient {
return traces;
}

async evaluate(input: EvaluateInput, options: CoreOptions): Promise<EvaluateResult> {
async evaluate(
input: EvaluateInput,
options: CoreOptions,
onWarning?: (message: string) => void,
): Promise<EvaluateResult> {
const refsBySession = groupRefsBySession(input.groundTruth);
const data = this.clients.data(toClientConfig(options));
const control = this.clients.control(toClientConfig(options));
const levels = await resolveEvaluatorLevels(input.evaluatorIds, control, options);
const refsBySession = groupRefsBySession(input.groundTruth);

// A reference is useful only if some evaluator will issue an Evaluate call
// for its session. TRACE and TOOL_CALL evaluators skip sessions with no IDs
// at that level, so warn for those as well as session IDs absent from traces.
const sessionsWithTargets = new Set<string>();
for (const evaluatorId of input.evaluatorIds) {
const level = levels.get(evaluatorId) ?? "SESSION";
for (const trace of input.traces) {
if (targetBatches(level, trace).length > 0) sessionsWithTargets.add(trace.sessionId);
}
}
const unusedReferenceSessions = [...refsBySession.keys()].filter(
(sessionId) => !sessionsWithTargets.has(sessionId),
);
if (unusedReferenceSessions.length > 0) {
const warning = `ground-truth entries reference sessions not evaluated: ${unusedReferenceSessions.join(", ")}`;
this.logger.warn(warning);
onWarning?.(warning);
}

const results: EvaluationResultContent[] = [];
// Sessions that actually produced Evaluate results — distinct from the sessions
Expand Down Expand Up @@ -2024,6 +2060,10 @@ async function resolveEvaluatorLevels(
return levels;
}

function isPlainObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}

// groupRefsBySession indexes ground-truth reference inputs by the session they
// apply to (context.spanContext.sessionId), so each Evaluate call attaches only its
// own session's references — the synchronous Evaluate shape, not batch's job-level
Expand All @@ -2032,17 +2072,43 @@ function groupRefsBySession(
groundTruth: EvaluationReferenceInput[] | undefined,
): Map<string, EvaluationReferenceInput[]> {
const map = new Map<string, EvaluationReferenceInput[]>();
for (const ref of groundTruth ?? []) {
const sessionId =
ref.context && "spanContext" in ref.context ? ref.context.spanContext?.sessionId : undefined;
if (!sessionId) continue;
if (groundTruth === undefined) return map;
if (!Array.isArray(groundTruth)) {
throw new InputValidationError(
"Invalid value for option '--ground-truth': expected a JSON array",
);
}
for (const [index, ref] of groundTruth.entries()) {
if (!isPlainObject(ref)) {
throw new InputValidationError(
`Invalid value for option '--ground-truth': entry ${index} must be a JSON object`,
);
}
const context = isPlainObject(ref.context) ? ref.context : undefined;
const spanContext =
context && isPlainObject(context.spanContext) ? context.spanContext : undefined;
const rawSessionId = spanContext?.sessionId;
const sessionId = requireGroundTruthSessionId(
rawSessionId,
index,
"context.spanContext.sessionId",
);
const list = map.get(sessionId);
if (list) list.push(ref);
else map.set(sessionId, [ref]);
if (list) list.push(ref as EvaluationReferenceInput);
else map.set(sessionId, [ref as EvaluationReferenceInput]);
}
return map;
}

function requireGroundTruthSessionId(sessionId: unknown, index: number, field: string): string {
if (typeof sessionId !== "string" || sessionId.trim().length === 0) {
throw new InputValidationError(
`Invalid value for option '--ground-truth': entry ${index} is missing ${field}`,
);
}
return sessionId;
}

// targetBatches splits a session's evaluation targets into <=10-id Evaluate calls.
// SESSION evaluators make a single call with no target; TRACE/TOOL_CALL sessions
// with no ids at that level make none (the session is skipped for that evaluator).
Expand Down
215 changes: 215 additions & 0 deletions src/core/evalGroundTruth.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
import { test, expect, describe } from "bun:test";
import {
EvaluateCommand,
StartBatchEvaluationCommand,
type EvaluationReferenceInput,
type SessionMetadataShape,
} from "@aws-sdk/client-bedrock-agentcore";
import { GetEvaluatorCommand } from "@aws-sdk/client-bedrock-agentcore-control";
import { EvalClient } from "./eval";
import { InputValidationError } from "../errors";
import type { Logger } from "../logging";
import type { AwsClients } from "./types";
import type { SessionTrace, SessionSourceValue } from "../handlers/eval/types";

const OPTIONS = { region: "us-west-2" };
const TRACE: SessionTrace = {
sessionId: "session-1",
spans: [{ traceId: "trace-1", spanId: "span-1" }],
traceIds: ["trace-1"],
toolCallSpanIds: [],
};

function makeClient(evaluatorLevel: "SESSION" | "TRACE" | "TOOL_CALL" = "SESSION") {
const evaluateInputs: unknown[] = [];
const batchInputs: unknown[] = [];
const warnings: string[] = [];
const logger: Logger = {
debug: () => {},
info: () => {},
warn: (...messages) => warnings.push(messages.join(" ")),
error: () => {},
child: () => logger,
};
const clients = {
control: () => ({
send: async (command: unknown) => {
if (command instanceof GetEvaluatorCommand) {
return { evaluatorId: "evaluator-1", level: evaluatorLevel };
}
throw new Error(`unexpected control command: ${(command as object).constructor.name}`);
},
}),
data: () => ({
send: async (command: unknown) => {
if (command instanceof EvaluateCommand) {
evaluateInputs.push(command.input);
return { evaluationResults: [] };
}
if (command instanceof StartBatchEvaluationCommand) {
batchInputs.push(command.input);
return { batchEvaluationId: "batch-1" };
}
throw new Error(`unexpected data command: ${(command as object).constructor.name}`);
},
}),
} as unknown as AwsClients;
return {
client: new EvalClient(clients, undefined, logger),
evaluateInputs,
batchInputs,
warnings,
};
}

describe("on-demand evaluation ground truth", () => {
test("rejects a reference without context.spanContext.sessionId before evaluating", async () => {
const { client, evaluateInputs } = makeClient();
const reference = {
context: { spanContext: { traceId: "trace-1" } },
expectedResponse: { text: "expected" },
} as unknown as EvaluationReferenceInput;

const error = await client
.evaluate(
{ traces: [TRACE], evaluatorIds: ["evaluator-1"], groundTruth: [reference] },
OPTIONS,
)
.catch((caught: unknown) => caught);

expect(error).toBeInstanceOf(InputValidationError);
expect(error).toMatchObject({
message: expect.stringMatching(/entry 0 is missing context\.spanContext\.sessionId/),
});
expect(evaluateInputs).toHaveLength(0);
});

test("warns when a reference session does not have an evaluation target", async () => {
const { client, evaluateInputs, warnings } = makeClient();
const emittedWarnings: string[] = [];
const reference: EvaluationReferenceInput = {
context: { spanContext: { sessionId: "other-session" } },
expectedResponse: { text: "expected" },
};

await client.evaluate(
{ traces: [TRACE], evaluatorIds: ["evaluator-1"], groundTruth: [reference] },
OPTIONS,
(message) => emittedWarnings.push(message),
);

expect(evaluateInputs).toHaveLength(1);
expect(evaluateInputs[0]).toMatchObject({ evaluationReferenceInputs: undefined });
expect(warnings).toEqual([
"ground-truth entries reference sessions not evaluated: other-session",
]);
expect(emittedWarnings).toEqual(warnings);
});

test("warns and skips Evaluate when a session has no tool-call spans for a TOOL_CALL evaluator", async () => {
const { client, evaluateInputs, warnings } = makeClient("TOOL_CALL");
const emittedWarnings: string[] = [];
const reference: EvaluationReferenceInput = {
context: { spanContext: { sessionId: "session-1" } },
expectedResponse: { text: "expected" },
};

const result = await client.evaluate(
{ traces: [TRACE], evaluatorIds: ["evaluator-1"], groundTruth: [reference] },
OPTIONS,
(message) => emittedWarnings.push(message),
);

expect(evaluateInputs).toHaveLength(0);
expect(result).toEqual({ sessionsRequested: 1, sessionsEvaluated: 0, results: [] });
expect(warnings).toEqual(["ground-truth entries reference sessions not evaluated: session-1"]);
expect(emittedWarnings).toEqual(warnings);
});

test("rejects '[null]' on-demand ground-truth entry before calling Evaluate", async () => {
const { client, evaluateInputs } = makeClient();
const groundTruth = [null] as unknown as EvaluationReferenceInput[];

const error = await client
.evaluate({ traces: [TRACE], evaluatorIds: ["evaluator-1"], groundTruth }, OPTIONS)
.catch((caught: unknown) => caught);

expect(error).toBeInstanceOf(InputValidationError);
expect((error as Error).message).toMatch(/--ground-truth.*entry 0/);
expect(evaluateInputs).toHaveLength(0);
});

test("attaches matching references to their session evaluation", async () => {
const { client, evaluateInputs, warnings } = makeClient();
const reference: EvaluationReferenceInput = {
context: { spanContext: { sessionId: "session-1" } },
expectedResponse: { text: "expected" },
};

await client.evaluate(
{ traces: [TRACE], evaluatorIds: ["evaluator-1"], groundTruth: [reference] },
OPTIONS,
);

expect(evaluateInputs[0]).toMatchObject({ evaluationReferenceInputs: [reference] });
expect(warnings).toEqual([]);
});
});

describe("batch evaluation ground truth", () => {
test("rejects session metadata without sessionId before starting the job", async () => {
const { client, batchInputs } = makeClient();
const source = {
origin: "raw",
dataSourceConfig: {},
} as unknown as SessionSourceValue;
const groundTruth = [
{ groundTruth: { inline: { turns: [] } } },
] as unknown as SessionMetadataShape[];

await expect(
client.startBatchEvaluation(
{ name: "eval-1", evaluatorIds: ["evaluator-1"], source, groundTruth },
OPTIONS,
),
).rejects.toThrow(/entry 0 is missing sessionId/);
expect(batchInputs).toHaveLength(0);
});

test("rejects non-array '{}' and '[null]' batch ground-truth entries before starting the job", async () => {
const { client, batchInputs } = makeClient();
const source = {
origin: "raw",
dataSourceConfig: {},
} as unknown as SessionSourceValue;

const objectError = await client
.startBatchEvaluation(
{
name: "eval-1",
evaluatorIds: ["evaluator-1"],
source,
groundTruth: {} as unknown as SessionMetadataShape[],
},
OPTIONS,
)
.catch((caught: unknown) => caught);
expect(objectError).toBeInstanceOf(InputValidationError);
expect((objectError as Error).message).toMatch(/--ground-truth/);

const nullEntryError = await client
.startBatchEvaluation(
{
name: "eval-1",
evaluatorIds: ["evaluator-1"],
source,
groundTruth: [null] as unknown as SessionMetadataShape[],
},
OPTIONS,
)
.catch((caught: unknown) => caught);
expect(nullEntryError).toBeInstanceOf(InputValidationError);
expect((nullEntryError as Error).message).toMatch(/--ground-truth.*entry 0/);
expect(batchInputs).toHaveLength(0);
});
});
17 changes: 17 additions & 0 deletions src/handlers/eval/batch-evaluation/batch-evaluation.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,23 @@ describe("eval batch-evaluation evaluate --output-config", () => {
).rejects.toThrow(/only one option may read from stdin.*'--output-config'.*'--ground-truth'/);
expect(core.eval.calls).toEqual([]);
});

test("rejects non-array --ground-truth '{}' before any SDK call", async () => {
const core = new TestCoreClient();
const io = testIO();
const root = createRootHandler(core, {
io: io.io,
logger: createSilentLogger(),
globalConfigAccessor: new TestGlobalConfigAccessor(),
});
const error = await root
.route(["node", "agentcore", ...BASE, "--ground-truth", "{}", "--region", "us-west-2"])
.catch((caught: unknown) => caught);

expect(error).toBeInstanceOf(InputValidationError);
expect((error as Error).message).toMatch(/--ground-truth/);
expect(core.eval.calls).toEqual([]);
});
});

describe("eval batch-evaluation simulate --endpoint and --output-config", () => {
Expand Down
9 changes: 4 additions & 5 deletions src/handlers/eval/batch-evaluation/evaluate/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { JsonRendererKey } from "../../../../tui";
import { SourceResolver, type AppIO } from "../../../../io";
import type { Core } from "../../../types";
import type { SessionMetadataShape } from "@aws-sdk/client-bedrock-agentcore";
import { coreOptsFromCtx, parseJsonFlag } from "../../../utils";
import { coreOptsFromCtx, parseJsonArrayFlag } from "../../../utils";
import { SessionSource } from "../../sessionSource";
import { BatchOutputConfig } from "../outputConfig";

Expand Down Expand Up @@ -84,13 +84,12 @@ export const createEvaluateBatchEvaluationHandler = (core: Core, io: AppIO) =>
const resolver = new SourceResolver({ stdin: io.stdin });
const source = await SessionSource.resolve(flags, resolver);

const groundTruth = parseJsonFlag<SessionMetadataShape[]>(
"ground-truth",
await resolver.resolveText("ground-truth", flags["ground-truth"]),
);
const rawGroundTruth = await resolver.resolveText("ground-truth", flags["ground-truth"]);

const outputConfig = await BatchOutputConfig.resolve(flags["output-config"], resolver);

const groundTruth = parseJsonArrayFlag<SessionMetadataShape>("ground-truth", rawGroundTruth);

const response = await core.eval.startBatchEvaluation(
{
name: flags["name"],
Expand Down
Loading
Loading