Guide · Amazon Bedrock · Model Customization
Amazon Bedrock Model Evaluation for MCP Servers — CreateEvaluationJob, Automatic Eval, and Metrics
Amazon Bedrock Model Evaluation lets you run automated, reproducible comparisons between foundation models before you commit one to a production MCP server. Instead of guessing which model handles your specific task best — structured data extraction, PDF summarization, intent classification — you upload a labeled JSONL dataset to S3, create an evaluation job pointing at one or more model ARNs, and Bedrock invokes each model against every example, then scores responses using built-in metrics or a separate judge model (LLM-as-judge). Results land in S3 as structured JSON: aggregate scores per metric and a per-example breakdown you can audit. This guide covers the complete workflow: dataset format, CreateEvaluationJobCommand with full TypeScript, LLM-as-judge configuration, job polling, reading and parsing S3 results, CI/CD gate integration, and six production gotchas that will save you hours of debugging.
TL;DR
Upload a JSONL evaluation dataset to S3 (each line: {"prompt": "...", "referenceResponse": "..."}). Call CreateEvaluationJobCommand with an IAM role, the dataset S3 URI, task type (QuestionAndAnswer, Summarization, TextGeneration, Classification), metric names (BERTScore, Accuracy, Toxicity), one or more model identifiers, an evaluator model for LLM-as-judge scoring, and an output S3 URI. Poll GetEvaluationJobCommand until Completed. Read aggregate + per-example results from the S3 output prefix. For CI/CD, compare the winning metric against a threshold and reject the model deploy if it falls below. Use at least 100 labeled examples for statistically meaningful scores.
Why model evaluation matters for MCP servers
An MCP server is a constrained service: it exposes a fixed set of tools, operates on predictable input shapes, and is expected to produce consistent, correct outputs. The model selection decision — Claude 3 Haiku vs. Claude 3.5 Sonnet vs. a fine-tuned variant — has a direct, measurable impact on tool call quality. But "which model is better for my use case?" is not a question you can answer by reading benchmarks.
Consider a concrete scenario: an MCP server that extracts structured data from PDF invoices. The tool accepts raw OCR text and must output a JSON object with vendor name, invoice number, line items, and total. Claude 3.5 Sonnet will likely score higher on general benchmarks, but Claude 3 Haiku may achieve equivalent accuracy on your specific invoice schema at one-tenth the token cost. The only way to know is to run your dataset through both models and compare Accuracy scores.
There are three common evaluation triggers in MCP server development:
- Initial model selection. Before going to production, you want to know which foundation model gives the highest accuracy on your task with an acceptable cost-to-quality tradeoff. Create an evaluation job comparing two or three candidates on your labeled dataset.
- Fine-tune validation. After fine-tuning a model (via Bedrock's Custom Model training or importing a fine-tuned weight via Custom Model Import), you must verify the fine-tuned model outperforms its base model on your target task before promoting it to production. Evaluation provides a quantitative pass/fail gate for this decision.
- Regression testing after prompt changes. When you update the system prompt or tool description in your MCP server, running an evaluation job against your golden dataset ensures the change did not degrade task accuracy — the same role automated tests play in software engineering.
| Trigger | Models to compare | Key metric |
|---|---|---|
| Initial model selection | 2–3 foundation model candidates | Accuracy or BERTScore |
| Fine-tune validation | Fine-tuned model vs base model | Accuracy delta |
| Prompt regression test | Same model, before/after prompt | BERTScore or custom LLM judge |
| Cost optimization | Large model vs smaller model | Accuracy parity + cost per 1k tokens |
Automatic evaluation vs human evaluation
Bedrock Model Evaluation supports two evaluation modes, controlled by the shape of the evaluationConfig field in CreateEvaluationJobCommand.
Automatic evaluation uses one of two scoring mechanisms: built-in algorithmic metrics (BERTScore, BUGSScore, Toxicity, Accuracy) computed deterministically against a referenceResponse field in your dataset, or an LLM-as-judge where a foundation model you designate reads the prompt, the model's response, and optionally the reference response, then scores quality on dimensions like coherence, correctness, and fluency. Automatic evaluation completes in minutes to hours, integrates with CI/CD pipelines, requires no human workforce, and is reproducible. It is the right choice for the vast majority of MCP server evaluation use cases.
Human evaluation routes your prompts and model responses to real annotators via Amazon Mechanical Turk or a private workforce (SageMaker Ground Truth labeling portal). Human annotators score along dimensions that are genuinely hard to automate: brand voice, cultural appropriateness, nuanced reasoning quality. Human jobs take days to weeks and cost significantly more. For MCP server CI/CD gates, human evaluation is not practical — use it only for one-time model selection decisions where you have budget and time, or for validating that your LLM judge is itself calibrated correctly (run both and compare).
| Automatic (algorithmic) | Automatic (LLM-as-judge) | Human | |
|---|---|---|---|
| Turnaround | Minutes | Minutes to hours | Days to weeks |
| CI/CD compatible | Yes | Yes | No |
| Requires reference answers | Yes (for most metrics) | Optional | No |
| Scores open-ended quality | No | Yes | Yes |
| Cost | Model inference only | Model + judge inference | Model + annotator labor |
The rest of this guide focuses exclusively on automatic evaluation, as it is the only mode practical for MCP server development workflows.
Evaluation dataset format
The evaluation dataset is a JSONL file (newline-delimited JSON) stored in an S3 bucket readable by your Bedrock evaluation IAM role. Each line is a self-contained JSON object. At minimum, every record must contain a prompt field. For metrics that require reference answers — particularly BERTScore and Accuracy — every record must also include a referenceResponse field. Missing referenceResponse when using BERTScore causes null scores without failing the job, making it appear the model performed poorly (see the gotchas section).
// Single-turn evaluation record — most common format
// Each line in the JSONL file is one of these
{"prompt": "Extract the company name from this invoice: Vendor: Acme Corp, Invoice #12345, Total: $1,200.00", "referenceResponse": "Acme Corp"}
{"prompt": "Extract the company name from this invoice: Bill From: Globex Corporation, PO-9988, Amount Due: $450.00", "referenceResponse": "Globex Corporation"}
{"prompt": "Extract the company name from this invoice: Supplier: TechParts LLC, Ref: INV-77231, Grand Total: $8,750.00", "referenceResponse": "TechParts LLC"}
// Multi-turn conversation format — use when your MCP tool sends multi-message context
// The "prompt" field can be a serialized messages array
{"prompt": "{\"messages\": [{\"role\": \"user\", \"content\": \"What is the status of ticket TKT-4421?\"}, {\"role\": \"assistant\", \"content\": \"Ticket TKT-4421 is currently open.\"}, {\"role\": \"user\", \"content\": \"When was it last updated?\"}]}", "referenceResponse": "Ticket TKT-4421 was last updated on 2026-11-10 at 14:32 UTC."}
// Summarization task format — referenceResponse is the ideal summary
{"prompt": "Summarize the following MCP server error log in one sentence: [ERROR] 2026-11-20T08:12:03Z tool_call failed: timeout after 30s waiting for upstream API /v1/items response. Retried 3 times. Last status: 503 Service Unavailable.", "referenceResponse": "The MCP server tool call failed due to repeated 503 timeouts from the upstream /v1/items API after three retry attempts."}
Dataset size recommendations: For statistically meaningful aggregate scores, use at least 100 examples. With fewer than 50 examples, metric variance is high enough that two models may appear to have different accuracy simply due to dataset sampling — not genuine capability differences. For classification tasks, include examples balanced across classes. For regression testing (prompt change validation), 100–200 examples covering your edge cases and representative inputs gives reliable signal. For initial model selection, 200–500 examples representative of real production traffic is ideal.
// TypeScript helper to build an evaluation JSONL dataset from labeled examples
// and upload it to S3
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
interface EvalExample {
prompt: string;
referenceResponse: string;
}
function buildEvalDataset(examples: EvalExample[]): string {
return examples
.map(ex => JSON.stringify({ prompt: ex.prompt, referenceResponse: ex.referenceResponse }))
.join('\n');
}
const s3 = new S3Client({ region: 'us-east-1' });
async function uploadEvalDataset(
bucket: string,
key: string,
examples: EvalExample[],
): Promise {
const content = buildEvalDataset(examples);
await s3.send(new PutObjectCommand({
Bucket: bucket,
Key: key,
Body: content,
ContentType: 'application/jsonlines',
}));
const s3Uri = `s3://${bucket}/${key}`;
console.log(`Uploaded ${examples.length} evaluation examples to ${s3Uri}`);
return s3Uri;
}
CreateEvaluationJobCommand — full TypeScript
The CreateEvaluationJobCommand from @aws-sdk/client-bedrock creates the evaluation job. The two important top-level structures are evaluationConfig.automated (which models to evaluate, which datasets, which metrics, and which judge model to use) and inferenceConfig.models (which model(s) to invoke against each prompt). To compare two models in one job, include both in inferenceConfig.models — Bedrock samples each model against the same prompts, ensuring apples-to-apples comparison.
import {
BedrockClient,
CreateEvaluationJobCommand,
type CreateEvaluationJobCommandInput,
} from '@aws-sdk/client-bedrock';
const bedrock = new BedrockClient({ region: 'us-east-1' });
async function createModelEvaluationJob(params: {
jobName: string;
roleArn: string;
datasetS3Uri: string; // s3://bucket/path/eval-dataset.jsonl
outputS3Uri: string; // s3://bucket/path/eval-output/ (prefix)
modelIds: string[]; // one or more model identifiers
judgeModelId: string; // model used as LLM-as-judge
taskType?: 'QuestionAndAnswer' | 'Summarization' | 'TextGeneration' | 'Classification';
}): Promise {
const {
jobName,
roleArn,
datasetS3Uri,
outputS3Uri,
modelIds,
judgeModelId,
taskType = 'QuestionAndAnswer',
} = params;
// Metric names depend on taskType.
// QuestionAndAnswer / TextGeneration: BERTScore, BUGSScore, Toxicity, Accuracy
// Summarization: BERTScore, BUGSScore
// Classification: Accuracy
const metricNames = taskType === 'Classification'
? ['Accuracy']
: taskType === 'Summarization'
? ['BERTScore', 'BUGSScore']
: ['BERTScore', 'Accuracy', 'Toxicity'];
const input: CreateEvaluationJobCommandInput = {
jobName,
roleArn,
evaluationConfig: {
automated: {
datasetMetricConfigs: [
{
taskType,
dataset: {
name: 'eval-dataset',
datasetLocation: { s3Uri: datasetS3Uri },
},
metricNames,
},
],
// LLM-as-judge: Bedrock invokes this model to score each response
// on quality dimensions beyond surface-level token overlap
evaluatorModelConfig: {
bedrockEvaluatorModels: [
{ modelIdentifier: judgeModelId },
],
},
},
},
inferenceConfig: {
models: modelIds.map(modelIdentifier => ({
bedrockModel: {
modelIdentifier,
// Optional: pass inference parameters per model
inferenceParams: JSON.stringify({
temperature: 0, // deterministic — important for reproducibility
maxTokens: 512,
}),
},
})),
},
outputDataConfig: {
s3Uri: outputS3Uri,
},
};
const response = await bedrock.send(new CreateEvaluationJobCommand(input));
const jobArn = response.jobArn;
if (!jobArn) throw new Error('CreateEvaluationJobCommand returned no jobArn');
console.log(`Evaluation job created: ${jobArn}`);
return jobArn;
}
// Example usage: compare Claude 3 Haiku vs Claude 3.5 Sonnet on invoice extraction
const jobArn = await createModelEvaluationJob({
jobName: `invoice-eval-${Date.now()}`,
roleArn: process.env.BEDROCK_EVAL_ROLE_ARN!,
datasetS3Uri: 's3://my-eval-bucket/datasets/invoice-extraction-100.jsonl',
outputS3Uri: 's3://my-eval-bucket/results/invoice-eval/',
modelIds: [
'anthropic.claude-3-haiku-20240307-v1:0',
'anthropic.claude-3-5-sonnet-20241022-v2:0',
],
judgeModelId: 'anthropic.claude-3-5-sonnet-20241022-v2:0',
taskType: 'QuestionAndAnswer',
});
The jobName must be unique within the account and region. A timestamp suffix avoids collisions across pipeline runs. The IAM role passed as roleArn must trust bedrock.amazonaws.com and have bedrock:InvokeModel on both the evaluated models and the judge model, plus s3:GetObject on the input bucket and s3:PutObject on the output bucket.
Task types and compatible metrics:
| taskType | Compatible metric names | Requires referenceResponse |
|---|---|---|
QuestionAndAnswer | BERTScore, BUGSScore, Accuracy, Toxicity | Yes (for BERTScore, Accuracy) |
Summarization | BERTScore, BUGSScore | Yes |
TextGeneration | BERTScore, BUGSScore, Toxicity | Yes (for BERTScore) |
Classification | Accuracy | Yes |
Note: OpenEndedTextGeneration is not available in automatic evaluation mode — it requires a human evaluation job. Attempting to use it in automated config results in a ValidationException at job creation time.
LLM-as-judge configuration
The LLM-as-judge mechanism uses a foundation model (typically Claude) to evaluate model responses along subjective quality dimensions: coherence, relevance, correctness, and fluency. For each example, the judge model receives a prompt containing the original question, the evaluated model's response, and optionally the reference response. It returns a score and brief rationale. This is especially useful for tasks like summarization and open-ended text generation, where token-overlap metrics like BERTScore do not fully capture human-perceived quality.
Important constraints for the judge model:
- The judge model must be a supported Bedrock foundation model in the same AWS region as the evaluation job. Cross-region judge models are not supported.
- Model access must be explicitly enabled for the judge model in your account via the Bedrock console's "Model access" page. If access is not enabled,
CreateEvaluationJobCommandthrows aValidationExceptionimmediately — not a runtime error mid-job. Enable access before job creation. - The judge model is billed separately from the evaluated models. For a 100-example dataset with Claude 3.5 Sonnet as judge, expect roughly 200 additional input tokens per example for the judge prompt scaffold, plus the judge's output tokens for the rationale.
- Using the same model as both the evaluated model and the judge model introduces self-serving bias — the model may rate its own responses higher than an independent judge would. When evaluating Claude 3.5 Sonnet, consider using Claude 3 Opus or a different provider as judge.
// Judge model configuration within evaluationConfig.automated
// The evaluatorModelConfig field is optional — omit it to use only algorithmic metrics
// Include it when you want LLM-based quality scoring (coherence, relevance, etc.)
const evaluatorModelConfig = {
bedrockEvaluatorModels: [
{
// Claude 3.5 Sonnet as judge — good balance of scoring quality and cost
// Must have model access enabled in the same region as the eval job
modelIdentifier: 'anthropic.claude-3-5-sonnet-20241022-v2:0',
},
],
};
// When using LLM-as-judge alongside BERTScore, results include both:
// 1. Algorithmic scores: BERTScore (token overlap), Accuracy (exact match)
// 2. LLM judge scores: Coherence, Correctness, Completeness, Fluency
// Each LLM judge dimension is scored 1–5; aggregate is the mean across examples
Polling job status with GetEvaluationJobCommand
Evaluation jobs are asynchronous. After calling CreateEvaluationJobCommand, the job enters InProgress and runs until completion or failure. For a 100-example dataset with one model, expect 5–20 minutes depending on queue depth. For 1000 examples comparing two models with LLM-as-judge, 1–3 hours is typical.
import {
BedrockClient,
GetEvaluationJobCommand,
} from '@aws-sdk/client-bedrock';
type EvalJobStatus =
| 'InProgress'
| 'Completed'
| 'Failed'
| 'Stopping'
| 'Stopped'
| 'Deleting';
interface EvalJobResult {
status: EvalJobStatus;
outputS3Uri?: string;
failureMessages?: string[];
}
async function getEvaluationJobStatus(
jobArn: string,
): Promise {
const response = await bedrock.send(new GetEvaluationJobCommand({
jobIdentifier: jobArn,
}));
return {
status: response.status as EvalJobStatus,
outputS3Uri: response.outputDataConfig?.s3Uri,
failureMessages: response.failureMessages,
};
}
async function pollEvaluationJob(
jobArn: string,
pollIntervalMs = 60_000, // poll every 60s — eval jobs are slow
timeoutMs = 4 * 60 * 60 * 1000, // 4 hour timeout
): Promise {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
const result = await getEvaluationJobStatus(jobArn);
console.log(`Evaluation job ${jobArn.split('/').pop()}: ${result.status}`);
switch (result.status) {
case 'Completed':
return result;
case 'Failed':
throw new Error(
`Evaluation job failed: ${result.failureMessages?.join('; ') ?? 'unknown error'}`
);
case 'Stopped':
throw new Error('Evaluation job was stopped before completing');
case 'InProgress':
case 'Stopping':
case 'Deleting':
// Continue polling
await new Promise(r => setTimeout(r, pollIntervalMs));
break;
default:
throw new Error(`Unknown eval job status: ${result.status}`);
}
}
throw new Error(`Evaluation job did not complete within ${timeoutMs / 3600000}h timeout`);
}
For long-running pipelines, prefer using EventBridge instead of a polling loop. Bedrock emits a "Bedrock Model Evaluation Job State Change" event on the default event bus whenever a job transitions state. Configure an EventBridge rule targeting a Lambda function that reads and processes the results, eliminating the need for a continuously running poller process.
Reading evaluation results from S3
When the job status transitions to Completed, Bedrock writes results to the outputDataConfig.s3Uri prefix. The output directory contains two categories of files: an aggregate summary JSON with rolled-up scores per metric per model, and per-example detail files (JSONL) with individual scores and judge rationales. Allow 60–120 seconds after the job status reaches Completed before fetching — results are written asynchronously and may not be immediately visible in S3 even though the status has transitioned.
import {
S3Client,
ListObjectsV2Command,
GetObjectCommand,
} from '@aws-sdk/client-s3';
const s3 = new S3Client({ region: 'us-east-1' });
// Aggregate results shape returned by Bedrock
interface AggregateScore {
metricName: string;
score: number; // 0–1 for BERTScore/Accuracy; 1–5 for LLM judge dimensions
stddev?: number;
}
interface ModelEvalResults {
modelId: string;
aggregateScores: AggregateScore[];
}
interface PerExampleRecord {
prompt: string;
referenceResponse?: string;
modelResponse: string;
scores: Record;
judgeRationale?: string;
}
async function readEvalResults(
outputS3Uri: string, // e.g. s3://bucket/results/invoice-eval/
): Promise<{ models: ModelEvalResults[]; perExample: PerExampleRecord[] }> {
const withoutScheme = outputS3Uri.replace('s3://', '');
const slashIndex = withoutScheme.indexOf('/');
const bucket = withoutScheme.slice(0, slashIndex);
const prefix = withoutScheme.slice(slashIndex + 1);
const { Contents } = await s3.send(new ListObjectsV2Command({
Bucket: bucket,
Prefix: prefix,
}));
const models: ModelEvalResults[] = [];
const perExample: PerExampleRecord[] = [];
for (const obj of Contents ?? []) {
if (!obj.Key) continue;
const { Body } = await s3.send(new GetObjectCommand({
Bucket: bucket,
Key: obj.Key,
}));
const text = await Body?.transformToString('utf-8') ?? '';
// Aggregate summary file
if (obj.Key.endsWith('aggregate_results.json')) {
const data = JSON.parse(text);
// data.models is an array of { modelIdentifier, scores: [{metricName, score, stddev}] }
for (const m of data.models ?? []) {
models.push({
modelId: m.modelIdentifier,
aggregateScores: m.scores ?? [],
});
}
}
// Per-example detail file
if (obj.Key.endsWith('.jsonl')) {
for (const line of text.split('\n').filter(Boolean)) {
const record = JSON.parse(line);
perExample.push({
prompt: record.prompt,
referenceResponse: record.referenceResponse,
modelResponse: record.modelResponse,
scores: record.scores ?? {},
judgeRationale: record.judgeRationale,
});
}
}
}
return { models, perExample };
}
// Pretty-print a comparison between two models
function summarizeComparison(models: ModelEvalResults[]): void {
console.log('\n=== Evaluation Results ===');
for (const model of models) {
console.log(`\nModel: ${model.modelId}`);
for (const score of model.aggregateScores) {
console.log(` ${score.metricName}: ${score.score.toFixed(4)}${score.stddev ? ` ± ${score.stddev.toFixed(4)}` : ''}`);
}
}
}
The aggregate_results.json file is the primary artifact for CI/CD gate decisions. Per-example JSONL files are most useful for debugging: when a model scores poorly on Accuracy, browsing the per-example file reveals which prompt types caused failures, letting you improve the prompts or fine-tune on the failing cases.
Production gotchas
1. Judge model access must be enabled before job creation, not at runtime
If the judge model (specified in evaluatorModelConfig.bedrockEvaluatorModels) does not have model access enabled in your account for the job's region, CreateEvaluationJobCommand throws a ValidationException synchronously — the job is never created. This catches many teams by surprise because the error message says "Invalid model identifier" rather than "model access not enabled." Check the Bedrock console's Model access page and confirm the judge model shows "Access granted" before submitting a job. Enabling access is immediate; no waiting required after clicking "Save changes."
2. S3 results are not immediately visible after status reaches Completed
The job status transitions to Completed before all result files have been written to S3. If you call ListObjectsV2 on the output prefix immediately after the status changes, you may see zero or incomplete files. Wait 60–120 seconds after detecting Completed status before reading results. In CI/CD pipelines, add an explicit delay or implement a retry loop that retries ListObjectsV2 until the expected files are present.
// Robust result-fetch helper: waits for the aggregate file to appear
async function waitForResults(
outputS3Uri: string,
maxWaitMs = 180_000,
): Promise {
const withoutScheme = outputS3Uri.replace('s3://', '');
const slashIndex = withoutScheme.indexOf('/');
const bucket = withoutScheme.slice(0, slashIndex);
const prefix = withoutScheme.slice(slashIndex + 1);
const deadline = Date.now() + maxWaitMs;
while (Date.now() < deadline) {
const { Contents } = await s3.send(new ListObjectsV2Command({
Bucket: bucket,
Prefix: prefix,
}));
const hasAggregate = (Contents ?? []).some(o => o.Key?.endsWith('aggregate_results.json'));
if (hasAggregate) return;
await new Promise(r => setTimeout(r, 15_000)); // check every 15s
}
throw new Error('Timed out waiting for evaluation results to appear in S3');
}
3. BERTScore silently returns null when referenceResponse is missing
If any record in your dataset is missing the referenceResponse field and you have requested BERTScore as a metric, Bedrock does not fail the job. Instead, those records receive a null score, which pulls the aggregate BERTScore down — sometimes dramatically. The job summary still shows a numeric aggregate (the mean of non-null values), but the sample size is smaller than expected, inflating variance. Always validate your dataset before submitting: every record must have a non-empty referenceResponse when using reference-based metrics.
4. Multi-model comparison requires a single job, not separate jobs
If you create job A for Model X and job B for Model Y and compare their scores, the comparison is unreliable: Bedrock samples prompts with temperature 0 but job scheduling, regional queue state, and model versioning can produce different effective conditions across jobs. Always put both models in the inferenceConfig.models array of a single job. Results for each model appear in separate subdirectories under the output prefix — Bedrock names them by model identifier. Comparing scores within a single job is the only statistically valid approach.
5. OpenEndedTextGeneration is not supported in automatic evaluation
The taskType value "OpenEndedTextGeneration" is valid in the Bedrock API but is only supported for human evaluation jobs (using evaluationConfig.human). Passing it in evaluationConfig.automated.datasetMetricConfigs results in an immediate ValidationException: "Task type OpenEndedTextGeneration is not supported for automated evaluation." Use TextGeneration for automatic evaluation of free-form generation tasks — it supports BERTScore, BUGSScore, and Toxicity.
6. Cost scales with examples × models × judge — budget before submitting large jobs
Each example is invoked once per model in inferenceConfig.models (inference cost), plus once per example by the judge model (additional inference cost). For 1000 examples comparing two models with Claude 3.5 Sonnet as judge: 1000 × 2 evaluated model invocations + 1000 judge invocations = 3000 inference calls. At roughly $0.003/1k input tokens and 500 tokens per prompt average, that is ~$4.50 in model cost plus the judge's output tokens for rationales (~150 tokens × 1000 = $0.45). Total: $5–15 for a 1000-example, 2-model job. For 10,000 examples, multiply by 10. Set up cost alerts in AWS Budgets before running large evaluation jobs in production.
CI/CD pipeline gate — promote fine-tuned model only on passing score
The practical value of Bedrock Model Evaluation is using it as an automated gate in your model promotion pipeline. After fine-tuning a model, the pipeline creates an evaluation job comparing the fine-tuned model against the current production model, reads the aggregate scores, and either promotes the fine-tuned model (if it exceeds the production model on the target metric by at least a configured threshold) or rejects the deployment.
// Full CI/CD evaluation gate: create job, poll, read results, return pass/fail
// Use this in your GitHub Actions, AWS CodePipeline, or any CI runner
interface EvalGateConfig {
jobName: string;
roleArn: string;
datasetS3Uri: string;
outputS3Uri: string;
candidateModelId: string; // The fine-tuned / new model to validate
baselineModelId: string; // Current production model
judgeModelId: string;
taskType: 'QuestionAndAnswer' | 'Summarization' | 'TextGeneration' | 'Classification';
gateMetric: string; // e.g. 'Accuracy' or 'BERTScore'
minAbsoluteScore: number; // Candidate must score at least this value
minDeltaVsBaseline: number; // Candidate must beat baseline by at least this much (can be 0)
}
interface GateResult {
passed: boolean;
candidateScore: number;
baselineScore: number;
delta: number;
jobArn: string;
details: string;
}
async function runEvaluationGate(config: EvalGateConfig): Promise {
const {
jobName,
roleArn,
datasetS3Uri,
outputS3Uri,
candidateModelId,
baselineModelId,
judgeModelId,
taskType,
gateMetric,
minAbsoluteScore,
minDeltaVsBaseline,
} = config;
// 1. Create the evaluation job comparing both models
console.log(`Creating evaluation job: ${jobName}`);
const jobArn = await createModelEvaluationJob({
jobName,
roleArn,
datasetS3Uri,
outputS3Uri,
modelIds: [candidateModelId, baselineModelId],
judgeModelId,
taskType,
});
// 2. Poll until completion (may take 10 min to several hours)
console.log('Polling for job completion...');
const result = await pollEvaluationJob(jobArn);
const resolvedOutputUri = result.outputS3Uri ?? outputS3Uri;
// 3. Wait for results to be fully written to S3
console.log('Waiting for results to appear in S3...');
await waitForResults(resolvedOutputUri);
await new Promise(r => setTimeout(r, 10_000)); // extra buffer
// 4. Read and parse results
const { models } = await readEvalResults(resolvedOutputUri);
// 5. Find target metric scores for each model
function getScore(modelId: string): number {
const model = models.find(m => m.modelId === modelId);
if (!model) throw new Error(`No results found for model: ${modelId}`);
const score = model.aggregateScores.find(s => s.metricName === gateMetric);
if (score === undefined) throw new Error(`Metric ${gateMetric} not found for ${modelId}`);
return score.score;
}
const candidateScore = getScore(candidateModelId);
const baselineScore = getScore(baselineModelId);
const delta = candidateScore - baselineScore;
// 6. Apply gate conditions
const meetsAbsoluteThreshold = candidateScore >= minAbsoluteScore;
const beatsDelta = delta >= minDeltaVsBaseline;
const passed = meetsAbsoluteThreshold && beatsDelta;
const details = [
`Metric: ${gateMetric}`,
`Candidate (${candidateModelId}): ${candidateScore.toFixed(4)}`,
`Baseline (${baselineModelId}): ${baselineScore.toFixed(4)}`,
`Delta: ${delta >= 0 ? '+' : ''}${delta.toFixed(4)}`,
`Absolute threshold: ${minAbsoluteScore} → ${meetsAbsoluteThreshold ? 'PASS' : 'FAIL'}`,
`Delta threshold: +${minDeltaVsBaseline} → ${beatsDelta ? 'PASS' : 'FAIL'}`,
`Overall: ${passed ? 'PASSED — promote candidate' : 'FAILED — keep baseline'}`,
].join('\n');
console.log(details);
return { passed, candidateScore, baselineScore, delta, jobArn, details };
}
// Example: validate a fine-tuned Claude model before promoting to production
async function validateFineTunedModel(): Promise {
const gate = await runEvaluationGate({
jobName: `finetuned-gate-${Date.now()}`,
roleArn: process.env.BEDROCK_EVAL_ROLE_ARN!,
datasetS3Uri: 's3://my-eval-bucket/datasets/invoice-extraction-200.jsonl',
outputS3Uri: 's3://my-eval-bucket/results/finetuned-gate/',
candidateModelId: 'arn:aws:bedrock:us-east-1::foundation-model/my-fine-tuned-model',
baselineModelId: 'anthropic.claude-3-haiku-20240307-v1:0',
judgeModelId: 'anthropic.claude-3-5-sonnet-20241022-v2:0',
taskType: 'QuestionAndAnswer',
gateMetric: 'Accuracy',
minAbsoluteScore: 0.85, // Candidate must achieve at least 85% accuracy
minDeltaVsBaseline: 0.0, // Candidate must not regress vs baseline (can match or beat)
});
if (!gate.passed) {
console.error('Model evaluation gate FAILED — aborting deployment');
process.exit(1); // Non-zero exit fails the CI step
}
console.log('Model evaluation gate PASSED — proceeding with deployment');
}
In a GitHub Actions workflow, call validateFineTunedModel() as a step between "train fine-tuned model" and "deploy to production Lambda." A non-zero exit code from the step halts the pipeline automatically. Store the jobArn and scores as step outputs or artifacts for the deployment audit trail.
Track production model quality with AliveMCP
Offline evaluation shows how a model performs on a benchmark dataset, but production MCP servers need runtime monitoring. AliveMCP tracks error rates, response latencies, and tool call success rates — giving you the runtime signal that complements Bedrock's offline evaluation scores.
Start free monitoring