The Complete Production SOP: How to Deploy and Run Synthetic Training Data & Instruction Generator in Autonomous AI Agents
Production SOP to install and run the Synthetic Data Generation Pipeline in Codex, Claude Code, & Cursor. Includes Self-Instruct filters and deduplication.
Technical Overview & Architectural Context
Without a deterministic instruction-tuning pipeline, autonomous coding agents generating synthetic datasets inevitably succumb to circular semantic drift, recursive hallucination, and reward hacking. When tasked with synthesizing diverse fine-tuning corpora, unrestricted frontier LLMs default to superficial prompt restatements or near-verbatim clones of seed tasks. This leads to collapsed instruction variance, skewed token distributions, and degraded downstream model performance. Furthermore, agents often overlook syntactic or unit-test verification, resulting in invalid code-completion records that poison fine-tuning runs. The Synthetic Training Data & Instruction Generator (synthetic-data-generation-pipeline) skill establishes rigorous procedural boundaries grounded in proven Self-Instruct and Evol-Instruct principles. It enforces strict mutation heuristics (adding concrete constraints, deepening reasoning steps, requiring specific JSON schemas), sets hard deduplication thresholds using sentence-embedding cosine similarity (< 0.85), and mandates automated test execution before any synthetic pair is committed to the workspace JSONL corpus. Operating deterministically without root execution permissions, the skill ensures clean, production-ready instruction datasets.
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Environment Setup & SKILL.md Mounting
Mount the skill manifest into your project's local agent configuration directory.
Agent runtimes such as Claude Code, Codex, Cursor, and Windsurf parse skills located in workspace-level metadata directories (`.claude/skills/`, `.cursor/rules/`, or `.agents/skills/`). Mounting this SKILL.md file guarantees the agent reads frontmatter triggers ('generate synthetic instruction dataset', 'evolve prompts self-instruct') and activates procedural guardrails whenever synthetic dataset tasks are initiated.
mkdir -p .agents/skills/synthetic-data-generation-pipeline && curl -fsSL https://askills.dev/api/skills/synthetic-data-generation-pipeline/raw -o .agents/skills/synthetic-data-generation-pipeline/SKILL.md---
name: "synthetic-data-generation-pipeline"
description: "Generate diverse, high-quality instruction tuning datasets using frontier LLMs."
metadata:
author: "Stanford CRFM"
version: "1.0.0"
runtime_compatibility:
- "codex"
- "claude-code"
- "cursor"
- "windsurf"
triggers:
- "generate synthetic instruction dataset"
- "evolve prompts self-instruct"
- "filter low quality synthetic data"
permissions:
fs_read: true
fs_write: "workspace"
shell_exec: false
net_access: false
---
# Synthetic Training Data & Instruction Generator
Builds synthetic data pipelines (Self-Instruct, Evol-Instruct): generating complex instructions, applying constraint mutations, filtering low-quality samples, and formatting JSONL datasets.
## Execution SOP & Rules
1. Seed the generation pipeline with 100+ diverse, human-verified example tasks.
2. Apply prompt mutations: increase reasoning depth, add domain constraints, or require specific schemas.
3. Filter generated pairs: remove near-duplicate items with sentence embedding cosine similarity > 0.85.
4. Validate code outputs by running automated unit test execution before accepting samples.Place the SKILL.md inside `.agents/skills/` to allow seamless multi-runtime portability across Cursor, Windsurf, and Claude Code without duplicating configuration files.
The skill enforces `shell_exec: false` and `net_access: false`. The agent must generate code or execution scripts within the workspace rather than trying to spawn out-of-band external network processes directly.
Pipeline Scaffold & Seed Ingestion
Scaffold the dataset generator architecture and ingest human-verified seed tasks.
Configure the core mutation and validation pipeline. The agent constructs a deterministic generation script that loads verified seed examples, applies Evol-Instruct transformations (in-depth reasoning, constraint addition, concretization), and sets up strict JSON schema outputs adhering to OpenAI/Anthropic instruction-tuning format.
python -m venv .venv && source .venv/bin/activate && pip install pydantic sentence-transformers numpyfrom pydantic import BaseModel, Field
from typing import List, Optional
import json
class InstructionSample(BaseModel):
instruction: str = Field(..., min_length=20)
input_context: Optional[str] = None
expected_output: str = Field(..., min_length=10)
mutation_type: str
complexity_score: int = Field(ge=1, le=5)
def format_jsonl_record(sample: InstructionSample) -> str:
return json.dumps({
"messages": [
{"role": "system", "content": "You are an expert autonomous assistant."},
{"role": "user", "content": f"{sample.instruction}\n{sample.input_context or ''}".strip()},
{"role": "assistant", "content": sample.expected_output}
]
})Ensure seed prompts cover orthogonal task categories (e.g., algorithmic logic, refactoring, API integration, security reviews) to maximize dataset variance.
Do not hardcode API tokens inside `generator.py`. Environment variables should be managed via external execution runners, leaving the workspace clean for version control.
Intent Matching & Trigger Invocation
Trigger deterministic agent execution using verified prompt patterns.
Invoke the skill using explicit trigger phrases found in the frontmatter. When the prompt contains triggers like 'evolve prompts self-instruct' or 'generate synthetic instruction dataset', the runtime activates the SOP to produce mutated candidate instructions, compute embeddings, and eliminate semantic redundancy.
claude 'generate synthetic instruction dataset: evolve prompts self-instruct from data/seeds.json and write filtered outputs to data/train.jsonl'import numpy as np
from sentence_transformers import SentenceTransformer
model = SentenceTransformer('all-MiniLM-L6-v2')
def deduplicate_instructions(instructions: list[str], threshold: float = 0.85) -> list[str]:
embeddings = model.encode(instructions, normalize_embeddings=True)
unique_indices = []
for i, emb in enumerate(embeddings):
if not unique_indices:
unique_indices.append(i)
continue
similarities = np.dot(embeddings[unique_indices], emb)
if np.max(similarities) < threshold:
unique_indices.append(i)
return [instructions[idx] for idx in unique_indices]Reference precise input/output file paths in your prompt to prevent the agent from dumping raw JSON directly into the conversational context window.
Cosine similarity filtering with threshold > 0.85 requires normalized vectors. Always verify vector normalization before dot product comparisons.
Verification, Linting & Output Quality Gate
Run deterministic linting, JSON schema validation, and embedding checks.
Before completing execution, the agent must run validation scripts verifying all generated JSONL records parse cleanly, no near-duplicates remain, and code snippets within responses execute or lint without syntax errors.
python -m pytest tests/test_dataset_quality.py --disable-warningsimport json
import pytest
from pathlib import Path
def test_train_jsonl_schema():
dataset_path = Path('data/train.jsonl')
assert dataset_path.exists(), 'train.jsonl does not exist'
with open(dataset_path, 'r', encoding='utf-8') as f:
for line_num, line in enumerate(f, 1):
record = json.loads(line)
assert 'messages' in record, f'Line {line_num} missing messages key'
assert len(record['messages']) == 3, f'Line {line_num} invalid message count'Automate a git diff inspection command before confirming completion to verify that seed records were not accidentally mutated or overwritten.
Malformed escape sequences in generated code instructions frequently break JSON decoding. Ensure raw strings and escaped control characters are handled by standard JSON serializers.
Real-World Scenario: Bootstrapping an Agentic Code Refactoring Dataset with Self-Instruct
“Generate synthetic instruction dataset for Python refactoring: evolve prompts self-instruct from data/refactoring_seeds.json, apply complexity and schema constraints, filter low quality synthetic data with cosine similarity > 0.85, and output 250 validated samples to data/refactor_train.jsonl.”
Runtime Troubleshooting & Failure Modes
Root Cause: The deduplication filter attempted matrix multiplication against an empty initial reference array or un-flattened embedding vectors.
Ensure candidate embeddings are shaped as 2D arrays: `np.atleast_2d(model.encode(instructions, normalize_embeddings=True))` before computing dot products.Root Cause: The agent attempted to write cache files outside the authorized workspace boundaries or invoke unpermitted network calls, violating SKILL.md permissions (fs_write: workspace, net_access: false).
Set the model cache directory within the workspace: `export HF_HOME=./.cache/huggingface` and ensure local model checkpoints are used without remote downloads.Frequently Asked Questions (Synthetic Training Data & Instruction Generator SOP)
Q:Can I use Synthetic Training Data & Instruction Generator across Codex, Claude Code, and Cursor simultaneously?
Yes. The skill conforms to the universal SKILL.md specification. By placing the file in `.agents/skills/synthetic-data-generation-pipeline/SKILL.md` or linking it to `.cursor/rules/`, any supported runtime reads the identical procedural SOP and trigger definitions.
Q:How does Synthetic Training Data & Instruction Generator prevent context window overflow during long agent sessions?
The skill enforces modular processing: instructions are mutated, batched, and immediately streamed to disk in JSONL format, using local embedding scripts for deduplication rather than retaining large conversational histories in LLM context.
Q:Does this skill require escalated root or container permissions?
No. The skill is audited with a security score of 98/100. It requires zero shell privileges (`shell_exec: false`), restricts write permissions solely to the current workspace (`fs_write: workspace`), and prohibits external network requests (`net_access: false`).
Ready to equip your autonomous agent with Synthetic Training Data & Instruction Generator?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.