Guide · Amazon Bedrock · Model Distillation · Training Data
Bedrock Model Distillation Training Data — JSONL prompt format, synthetic completions, S3 upload
Amazon Bedrock Model Distillation accepts training data as a JSONL file in S3 where each line is a JSON object with a prompt field — completions are optional because Bedrock calls the teacher model to generate them during the distillation job. Four data constraints catch MCP server builders off-guard: the JSONL encoding must be UTF-8 without BOM — a BOM causes the entire job to fail with a confusing parse error; each prompt is limited to 32,000 characters — prompts exceeding this are silently dropped from training (the job succeeds, but the dropped examples are listed in the job's output statistics); the minimum training dataset is 1,000 prompts for distillation to begin — submitting fewer returns a ValidationException before the job starts; and when you pre-generate teacher completions yourself and include them in the JSONL, Bedrock uses those provided completions directly without calling the teacher model again, which saves cost but means your pre-generated outputs must match the teacher model's quality. For the job creation API see distillation overview; for hyperparameter tuning see customization job parameters.
TL;DR
Write a UTF-8 JSONL file where each line is {"prompt": "..."}. Upload to S3. Pass the S3 URI to trainingDataConfig.s3Uri. Bedrock invokes the teacher for each prompt-only line during the job. If you include a completion field, that completion is used as-is and the teacher is not called for that line. Minimum 1,000 lines. Prompts over 32,000 characters are silently dropped.
JSONL file format
The training file is newline-delimited JSON (JSONL): one JSON object per line, no commas between lines, no wrapping array. Each line must be a valid JSON object with at least a prompt key:
// prompts.jsonl — prompt-only lines (teacher generates completions)
{"prompt": "Classify the following support ticket: I cannot log into my account after the password reset."}
{"prompt": "Classify the following support ticket: My invoice shows charges I did not authorize."}
{"prompt": "Classify the following support ticket: The API returns 503 errors when I call the embeddings endpoint."}
{"prompt": "Classify the following support ticket: How do I add a team member to my organization?"}
When you need fine-grained control over what the student model learns — for example, to inject a specific output format the teacher model might phrase differently on different calls — provide both prompt and completion:
// mixed.jsonl — prompt+completion lines (completion used as-is; no teacher call)
{"prompt": "Classify: cannot log in after password reset", "completion": "account"}
{"prompt": "Classify: unauthorized charges on invoice", "completion": "billing"}
{"prompt": "Classify: API returns 503 on embeddings", "completion": "technical"}
// You can mix prompt-only and prompt+completion lines in the same file
{"prompt": "Classify: how to remove a team member"}
{"prompt": "Classify: request a refund for last month", "completion": "billing"}
Three format requirements that cause silent data loss or hard failures: (1) each line must be complete valid JSON — a trailing comma, unquoted key, or truncated object causes the job to fail at the parse phase before any training begins; (2) the file must be UTF-8 encoded without BOM — a UTF-8 BOM (EF BB BF) on the first byte makes the first JSON object unparseable; (3) blank lines are not allowed — an empty line in the middle of the file causes a parse error at that position and aborts the job.
Generating prompts from MCP server production logs
The highest-quality training prompts come from real production traffic through your MCP server. If you log the input to each tool call, those inputs are already the representative distribution you want the distilled model to handle. This script reads CloudWatch Logs entries for a given tool name and extracts the prompts:
import {
CloudWatchLogsClient,
FilterLogEventsCommand,
} from "@aws-sdk/client-cloudwatch-logs";
import { createWriteStream } from "fs";
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import { createReadStream } from "fs";
const logsClient = new CloudWatchLogsClient({ region: "us-east-1" });
const s3Client = new S3Client({ region: "us-east-1" });
async function extractPromptsFromLogs(params: {
logGroupName: string;
toolName: string;
startTime: number; // epoch ms
endTime: number;
outputPath: string;
}): Promise<number> {
const writer = createWriteStream(params.outputPath, { encoding: "utf8" });
let count = 0;
let nextToken: string | undefined;
do {
const response = await logsClient.send(
new FilterLogEventsCommand({
logGroupName: params.logGroupName,
filterPattern: `{ $.tool = "${params.toolName}" }`,
startTime: params.startTime,
endTime: params.endTime,
nextToken,
})
);
for (const event of response.events ?? []) {
try {
const parsed = JSON.parse(event.message ?? "");
const prompt = parsed.input?.ticket ?? parsed.input?.query ?? parsed.input?.text;
if (typeof prompt === "string" && prompt.length > 10 && prompt.length < 32000) {
writer.write(
JSON.stringify({
prompt: `Classify the following support ticket: ${prompt}`,
}) + "\n"
);
count++;
}
} catch {
// skip malformed log entries
}
}
nextToken = response.nextToken;
} while (nextToken);
await new Promise<void>((r) => writer.end(r));
return count;
}
// Upload to S3 after extraction
async function uploadToS3(localPath: string, s3Uri: string): Promise<void> {
const [, bucket, ...keyParts] = s3Uri.replace("s3://", "").split("/");
const key = keyParts.join("/");
await s3Client.send(
new PutObjectCommand({
Bucket: bucket,
Key: key,
Body: createReadStream(localPath),
ContentType: "application/x-ndjson",
})
);
}
// Extract 30 days of tool calls
const count = await extractPromptsFromLogs({
logGroupName: "/mcp-server/support-classifier",
toolName: "classify_support_ticket",
startTime: Date.now() - 30 * 24 * 60 * 60 * 1000,
endTime: Date.now(),
outputPath: "/tmp/prompts.jsonl",
});
console.log(`Extracted ${count} prompts`);
if (count < 1000) {
console.warn("Fewer than 1000 prompts — distillation will fail. Augment dataset.");
}
await uploadToS3("/tmp/prompts.jsonl", "s3://my-bucket/distill-training/prompts.jsonl");
Pre-generating teacher completions to control quality
When you need deterministic training targets — for a classification task with a fixed label set, or when you want to review and edit teacher outputs before training — pre-generate the teacher's completions yourself using ConverseCommand, review them, and include the completion field in the JSONL. Bedrock uses your provided completions and skips the teacher calls during the job:
import {
BedrockRuntimeClient,
ConverseCommand,
} from "@aws-sdk/client-bedrock-runtime";
import { createWriteStream } from "fs";
const runtimeClient = new BedrockRuntimeClient({ region: "us-east-1" });
const TEACHER_MODEL_ID =
"anthropic.claude-3-sonnet-20240229-v1:0";
const SYSTEM_PROMPT = `You are a support ticket classifier.
Respond with exactly ONE word from this list: billing, technical, account, general.
No explanation, no punctuation — just the category word.`;
async function generateTeacherCompletion(prompt: string): Promise<string> {
const response = await runtimeClient.send(
new ConverseCommand({
modelId: TEACHER_MODEL_ID,
system: [{ text: SYSTEM_PROMPT }],
messages: [{ role: "user", content: [{ text: prompt }] }],
inferenceConfig: {
maxTokens: 10,
temperature: 0, // deterministic output for labels
},
})
);
return (
response.output?.message?.content
?.filter((b) => b.text)
.map((b) => b.text)
.join("")
.trim() ?? ""
);
}
async function buildDistillationDataset(
prompts: string[],
outputPath: string
): Promise<void> {
const writer = createWriteStream(outputPath, { encoding: "utf8" });
const CONCURRENCY = 10; // parallel teacher calls
for (let i = 0; i < prompts.length; i += CONCURRENCY) {
const batch = prompts.slice(i, i + CONCURRENCY);
const completions = await Promise.all(
batch.map((p) => generateTeacherCompletion(p))
);
for (let j = 0; j < batch.length; j++) {
const completion = completions[j];
if (!completion) continue; // skip empty completions
writer.write(
JSON.stringify({ prompt: batch[j], completion }) + "\n"
);
}
if ((i / CONCURRENCY) % 10 === 0) {
console.log(`Generated ${i + batch.length} / ${prompts.length}`);
}
}
await new Promise<void>((r) => writer.end(r));
}
// Build the dataset with pre-generated completions
const prompts = [
"Classify this support ticket: I cannot log in after password reset.",
"Classify this support ticket: My invoice has an incorrect charge.",
// ... load from logs
];
await buildDistillationDataset(prompts, "/tmp/labeled-dataset.jsonl");
Pre-generating teacher completions has three advantages: you can review and correct borderline cases before they enter training; you pay for teacher invocations during data preparation rather than during the distillation job, which makes the job cost easier to predict; and for classification tasks, temperature-0 teacher calls produce consistent labels that are easier to audit. The main disadvantage is that it requires you to call the teacher model at scale before job submission — at 10 concurrent calls per batch and 1,000 prompts, that is roughly 100 serial batches at ~200 ms per batch, or about 20 seconds plus API rate limits.
Dataset size guidelines
Bedrock Model Distillation enforces a 1,000-prompt minimum but the right size depends on task complexity:
| Task type | Minimum useful | Good quality | Diminishing returns |
|---|---|---|---|
| Classification (5–10 classes) | 1,000 | 5,000–10,000 | >50,000 |
| Extraction (structured fields from text) | 2,000 | 10,000–20,000 | >100,000 |
| Summarization (domain-specific style) | 5,000 | 20,000–50,000 | >200,000 |
| Open-ended generation (specialized voice) | 10,000 | 50,000+ | Rarely reached |
Diversity matters as much as volume. 10,000 prompts covering only one input pattern teaches the student nothing about the other patterns it will see at runtime. When extracting from production logs, stratify by user segment, query type, or time window to ensure the dataset reflects the full distribution of real traffic.
Validating the JSONL before upload
Running a local validation pass before uploading to S3 catches format errors that would cause the distillation job to fail hours after submission:
import { createReadStream } from "fs";
import { createInterface } from "readline";
interface ValidationResult {
valid: number;
invalid: number;
tooLong: number;
errors: Array<{ line: number; reason: string }>;
}
async function validateDistillationDataset(filePath: string): Promise<ValidationResult> {
const result: ValidationResult = {
valid: 0, invalid: 0, tooLong: 0, errors: [],
};
const rl = createInterface({
input: createReadStream(filePath),
crlfDelay: Infinity,
});
let lineNum = 0;
for await (const line of rl) {
lineNum++;
// Blank lines
if (line.trim() === "") {
result.invalid++;
result.errors.push({ line: lineNum, reason: "blank line" });
continue;
}
// Parse JSON
let obj: unknown;
try {
obj = JSON.parse(line);
} catch (err) {
result.invalid++;
result.errors.push({ line: lineNum, reason: `JSON parse error: ${err}` });
continue;
}
// Must be an object with a prompt field
if (
typeof obj !== "object" ||
obj === null ||
!("prompt" in obj) ||
typeof (obj as Record<string, unknown>).prompt !== "string"
) {
result.invalid++;
result.errors.push({ line: lineNum, reason: "missing or non-string 'prompt' field" });
continue;
}
const record = obj as { prompt: string; completion?: string };
// Check prompt length (32,000 char limit)
if (record.prompt.length > 32000) {
result.tooLong++;
result.errors.push({ line: lineNum, reason: `prompt too long: ${record.prompt.length} chars` });
continue;
}
// Completion field, if present, must be a non-empty string
if (
"completion" in record &&
(typeof record.completion !== "string" || record.completion.length === 0)
) {
result.invalid++;
result.errors.push({ line: lineNum, reason: "completion field present but empty or non-string" });
continue;
}
result.valid++;
}
return result;
}
// Run before uploading
const validation = await validateDistillationDataset("/tmp/prompts.jsonl");
console.log(`Valid: ${validation.valid}, Invalid: ${validation.invalid}, Too long: ${validation.tooLong}`);
if (validation.valid < 1000) {
throw new Error(`Need at least 1000 valid prompts, got ${validation.valid}`);
}
if (validation.errors.length > 0) {
console.warn("First 10 errors:");
validation.errors.slice(0, 10).forEach(e => console.warn(` line ${e.line}: ${e.reason}`));
}
S3 bucket requirements for training data
The S3 bucket holding your training data must be in the same AWS region as the distillation job. Cross-region S3 access is blocked by default for Bedrock customization jobs — if the bucket is in us-west-2 and your job is in us-east-1, the job fails at startup with an AccessDeniedException that looks like a permissions problem but is actually a region mismatch.
// Upload training data with correct content type
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import { readFileSync } from "fs";
const s3 = new S3Client({ region: "us-east-1" });
await s3.send(new PutObjectCommand({
Bucket: "my-distill-bucket",
Key: "training/prompts.jsonl",
Body: readFileSync("/tmp/prompts.jsonl"),
// Use NDJSON content type — Bedrock validates this
ContentType: "application/x-ndjson",
// Server-side encryption is supported and recommended
ServerSideEncryption: "aws:kms",
}));
// Training data S3 URI format for CreateModelCustomizationJob
const trainingS3Uri = "s3://my-distill-bucket/training/prompts.jsonl";
Server-side encryption with KMS is supported and recommended. If you use a customer-managed KMS key, add kms:Decrypt and kms:GenerateDataKey permissions to the Bedrock customization role so it can decrypt the training data at job runtime. Using the default AWS-managed key (aws/s3) requires no extra IAM permissions.
Using invocation logs as training data
Amazon Bedrock can automatically log every model invocation to S3 or CloudWatch Logs via Model Invocation Logging. If you enable invocation logging for your teacher model, the logs contain both the input prompt and the model's output in a structured format that you can convert to distillation training data:
// Bedrock invocation log entry shape (from S3 invocation log bucket)
interface BedrockInvocationLog {
schemaType: "ModelInvocationLog";
accountId: string;
region: string;
requestId: string;
operation: "Converse" | "InvokeModel";
modelId: string;
input: {
inputContentType: string;
inputTokenCount: number;
inputBodyJson: string; // serialized request body
};
output: {
outputContentType: string;
outputTokenCount: number;
outputBodyJson: string; // serialized response body
};
timestamp: string;
}
// Convert Converse invocation logs to distillation JSONL
function convertConverseLogToDistillationRecord(
log: BedrockInvocationLog
): { prompt: string; completion: string } | null {
try {
const inputBody = JSON.parse(log.input.inputBodyJson);
const outputBody = JSON.parse(log.output.outputBodyJson);
// Extract the last user message as the prompt
const userMessages: Array<{ role: string; content: Array<{ text?: string }> }> =
inputBody.messages ?? [];
const lastUser = [...userMessages].reverse().find((m) => m.role === "user");
if (!lastUser) return null;
const prompt = lastUser.content
.filter((b) => b.text)
.map((b) => b.text)
.join(" ")
.trim();
// Extract the assistant response as the completion
const outputText =
outputBody.output?.message?.content
?.filter((b: { text?: string }) => b.text)
.map((b: { text?: string }) => b.text)
.join("") ?? "";
if (!prompt || !outputText) return null;
return { prompt, completion: outputText };
} catch {
return null;
}
}
Invocation logs as training data gives you real-world teacher outputs without additional API cost — the teacher was already invoked in production. The main concern is privacy: production invocation logs may contain user PII that you should redact before using them as training data for a custom model. Run a PII detection pass (via Amazon Comprehend's DetectPiiEntities) on the prompts before including them in the training file.
Monitor your MCP server through training and beyond
Building a distillation pipeline means your MCP server goes through a multi-phase lifecycle: initial deployment with the teacher model, then cutover to the distilled student. AliveMCP tracks uptime and response latency continuously, so you can verify the student model's performance matches the teacher's in production — and get alerted immediately if the cutover degrades tool call quality.