Verified SOP & TutorialAudited Score 98/100

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.

Target Runtimes:codexclaude-codecursorwindsurf
5 min read • Updated for 2026

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

Codex Desktop, Claude Code CLI, Cursor, or Windsurf installed with active workspace access
Python 3.10+ with uv or virtualenv in workspace sandbox
Sentence-transformers or fast local embedding dependencies installed (e.g., pip install sentence-transformers numpy pydantic)
Git 2.40+ initialized in target repository

Verified Search Intents & Long-Tail Queries Solved

SEO Audit Score: 98/100

This operational tutorial is engineered to provide deterministic solutions for these developer search queries:

#install synthetic-data-generation-pipeline in cursor ide#claude code synthetic-data-generation-pipeline rules#codex desktop synthetic-data-generation-pipeline setup tutorial#evolve prompts self-instruct synthetic dataset generator#filter low quality synthetic data cosine similarity pipeline#synthetic-data-generation-pipeline sandbox permissions and security score#generate synthetic instruction dataset for llm fine tuning

Step-by-Step Execution Playbook

1

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.

Terminal Command
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
.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.
Production Pro-Tip

Place the SKILL.md inside `.agents/skills/` to allow seamless multi-runtime portability across Cursor, Windsurf, and Claude Code without duplicating configuration files.

Sandbox Gotcha

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.

2

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.

Terminal Command
python -m venv .venv && source .venv/bin/activate && pip install pydantic sentence-transformers numpy
pipeline/generator.py
from 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}
        ]
    })
Production Pro-Tip

Ensure seed prompts cover orthogonal task categories (e.g., algorithmic logic, refactoring, API integration, security reviews) to maximize dataset variance.

Sandbox Gotcha

Do not hardcode API tokens inside `generator.py`. Environment variables should be managed via external execution runners, leaving the workspace clean for version control.

3

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.

Terminal Command
claude 'generate synthetic instruction dataset: evolve prompts self-instruct from data/seeds.json and write filtered outputs to data/train.jsonl'
pipeline/dedup_filter.py
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]
Production Pro-Tip

Reference precise input/output file paths in your prompt to prevent the agent from dumping raw JSON directly into the conversational context window.

Sandbox Gotcha

Cosine similarity filtering with threshold > 0.85 requires normalized vectors. Always verify vector normalization before dot product comparisons.

4

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.

Terminal Command
python -m pytest tests/test_dataset_quality.py --disable-warnings
tests/test_dataset_quality.py
import 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'
Production Pro-Tip

Automate a git diff inspection command before confirming completion to verify that seed records were not accidentally mutated or overwritten.

Sandbox Gotcha

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

Tested Trigger Prompt (Feed directly into Codex, Claude, or Cursor):

“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.”

Deterministic Agent Verification Pipeline:
Parsed .agents/skills/synthetic-data-generation-pipeline/SKILL.md and detected active triggers: 'generate synthetic instruction dataset' and 'filter low quality synthetic data'.
Loaded 25 human-authored seed refactoring scenarios from data/refactoring_seeds.json.
Applied Evol-Instruct mutations across three axes: adding nested constraints (memory limits), demanding explicit typing, and requiring unit tests.
Executed local sentence-transformers deduplication script, eliminating 42 candidates exhibiting cosine similarity > 0.85 against existing instruction embeddings.
Ran Python AST verification (`ast.parse`) across all assistant response code blocks to ensure 100% syntactically valid code.
Committed 250 verified and formatted samples into data/refactor_train.jsonl and validated JSONL schema adherence.

Runtime Troubleshooting & Failure Modes

Error: ValueError: Cosine similarity matrix computation failed: shapes (N, 384) and (M, 384) not aligned

Root Cause: The deduplication filter attempted matrix multiplication against an empty initial reference array or un-flattened embedding vectors.

Resolution Command / Fix:
Ensure candidate embeddings are shaped as 2D arrays: `np.atleast_2d(model.encode(instructions, normalize_embeddings=True))` before computing dot products.
Error: PermissionError: [Errno 13] Permission denied: '/etc/dataset_cache' or unauthorized network outbound call

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).

Resolution Command / Fix:
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.

Get 1-Click Install Spec