Token Classification
Transformers
ONNX
Safetensors
Transformers.js
modernbert
pii
pii-detection
secret-detection
dlp
ai-agents
security
guardrails
presidio
llm-guard
litellm
nemo-guardrails
open-webui
data-loss-prevention
Instructions to use Tamarillo/pii-secrets-guard-small with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Tamarillo/pii-secrets-guard-small with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("token-classification", model="Tamarillo/pii-secrets-guard-small")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForTokenClassification tokenizer = AutoTokenizer.from_pretrained("Tamarillo/pii-secrets-guard-small") model = AutoModelForTokenClassification.from_pretrained("Tamarillo/pii-secrets-guard-small", device_map="auto") - Transformers.js
How to use Tamarillo/pii-secrets-guard-small with Transformers.js:
// npm i @huggingface/transformers import { pipeline } from '@huggingface/transformers'; // Allocate pipeline const pipe = await pipeline('token-classification', 'Tamarillo/pii-secrets-guard-small'); - Notebooks
- Google Colab
- Kaggle
Download scripts/synth_secrets.py from Tamarillo/pii-secrets-guard-small: direct link, hf CLI and curl.
- Browser
- Download file 23.6 kB
-
https://huggingface.co/Tamarillo/pii-secrets-guard-small/resolve/main/scripts/synth_secrets.py
- Command line
-
hf download hf://Tamarillo/pii-secrets-guard-small/scripts/synth_secrets.py
-
curl -L -o synth_secrets.py https://huggingface.co/Tamarillo/pii-secrets-guard-small/resolve/main/scripts/synth_secrets.py
23.6 kB
| """Deterministic Apache-2.0 synthetic generator for Agent Secrets, Hard Negatives, and Long-Context Needles. | |
| Generates exact character-offset spans by construction (zero alignment noise) with strict | |
| template-family separation between train, validation, and test splits. | |
| """ | |
| from __future__ import annotations | |
| import base64 | |
| import json | |
| import random | |
| import string | |
| from typing import Any | |
| from taxonomy import normalize_and_merge_spans | |
| ALNUM = string.ascii_letters + string.digits | |
| HEX_LOWER = "0123456789abcdef" | |
| HEX_UPPER = "0123456789ABCDEF" | |
| B64_URL = string.ascii_letters + string.digits + "-_" | |
| def _rand_str(rng: random.Random, chars: str, length: int) -> str: | |
| return "".join(rng.choice(chars) for _ in range(length)) | |
| def gen_api_key(rng: random.Random) -> str: | |
| kind = rng.choice([ | |
| "openai", "anthropic", "aws_akid", "github_pat", "github_fine", | |
| "stripe", "slack", "huggingface", "google", "sendgrid", "generic", | |
| ]) | |
| if kind == "openai": | |
| return "sk-proj-" + _rand_str(rng, B64_URL, rng.randint(42, 56)) | |
| if kind == "anthropic": | |
| return "sk-ant-api03-" + _rand_str(rng, B64_URL, rng.randint(40, 52)) | |
| if kind == "aws_akid": | |
| return "AKIA" + _rand_str(rng, string.ascii_uppercase + string.digits, 16) | |
| if kind == "github_pat": | |
| return rng.choice(["ghp_", "gho_", "ghs_"]) + _rand_str(rng, ALNUM, 36) | |
| if kind == "github_fine": | |
| return "github_pat_" + _rand_str(rng, ALNUM, 22) + "_" + _rand_str(rng, ALNUM, 40) | |
| if kind == "stripe": | |
| return rng.choice(["sk_live_", "rk_live_", "whsec_"]) + _rand_str(rng, ALNUM, 24) | |
| if kind == "slack": | |
| return f"xoxb-{rng.randint(1000000000,9999999999)}-{rng.randint(1000000000,9999999999)}-{_rand_str(rng, ALNUM, 24)}" | |
| if kind == "huggingface": | |
| return "hf_" + _rand_str(rng, ALNUM, 34) | |
| if kind == "google": | |
| return "AIzaSy" + _rand_str(rng, B64_URL, 33) | |
| if kind == "sendgrid": | |
| return "SG." + _rand_str(rng, B64_URL, 22) + "." + _rand_str(rng, B64_URL, 43) | |
| # Realistic prefixed mixed-entropy service key (never ambiguous bare hex like git SHAs/MD5/SHA256) | |
| prefix = rng.choice(["api_", "key_", "live_", "pk_live_", "tmr_", "sec_"]) | |
| return prefix + _rand_str(rng, ALNUM, rng.choice([28, 32, 40])) | |
| def gen_auth_token(rng: random.Random) -> str: | |
| kind = rng.choice(["jwt", "bearer_opaque", "oauth_refresh", "cookie_session"]) | |
| if kind == "jwt": | |
| hdr = base64.urlsafe_b64encode(b'{"alg":"RS256","typ":"JWT"}').decode().rstrip("=") | |
| sub = f"usr_{_rand_str(rng, ALNUM, 10)}" | |
| exp = rng.randint(1760000000, 1890000000) | |
| pay = base64.urlsafe_b64encode( | |
| json.dumps({"sub": sub, "role": "admin", "exp": exp}).encode() | |
| ).decode().rstrip("=") | |
| sig = _rand_str(rng, B64_URL, 43) | |
| return f"{hdr}.{pay}.{sig}" | |
| if kind == "bearer_opaque": | |
| return "tok_" + _rand_str(rng, B64_URL, rng.randint(32, 48)) | |
| if kind == "oauth_refresh": | |
| return "ya29." + _rand_str(rng, B64_URL, rng.randint(44, 60)) | |
| return f"session_id={_rand_str(rng, HEX_LOWER, 32)}" | |
| def gen_password(rng: random.Random) -> str: | |
| specials = "!@#$%^&*-_+=" | |
| parts = [ | |
| _rand_str(rng, string.ascii_uppercase, rng.randint(2, 4)), | |
| _rand_str(rng, string.ascii_lowercase, rng.randint(4, 7)), | |
| _rand_str(rng, string.digits, rng.randint(2, 4)), | |
| _rand_str(rng, specials, rng.randint(1, 2)), | |
| ] | |
| rng.shuffle(parts) | |
| return "".join(parts) | |
| def gen_database_uri(rng: random.Random) -> str: | |
| scheme = rng.choice(["postgresql", "postgres", "mysql", "mongodb+srv", "redis", "amqp"]) | |
| user = rng.choice(["app_prod", "svc_billing", "admin", "analytics_ro", "agent_worker", "dbuser"]) | |
| pwd = _rand_str(rng, ALNUM, rng.randint(12, 20)) | |
| host = rng.choice([ | |
| f"db-{rng.randint(1,9)}.internal.corp.net", | |
| f"prod-cluster-{rng.randint(10,99)}.us-east-1.rds.amazonaws.com", | |
| f"10.{rng.randint(0,255)}.{rng.randint(0,255)}.{rng.randint(2,254)}", | |
| "cache.prod.svc.cluster.local", | |
| ]) | |
| port = {"postgresql": 5432, "postgres": 5432, "mysql": 3306, "redis": 6379, "amqp": 5672}.get(scheme) | |
| db = rng.choice(["customers", "payments", "telemetry", "agent_state", "prod"]) | |
| if scheme == "mongodb+srv": | |
| return f"{scheme}://{user}:{pwd}@{host}/{db}?retryWrites=true" | |
| if scheme == "redis": | |
| return f"redis://:{pwd}@{host}:{port}/0" | |
| return f"{scheme}://{user}:{pwd}@{host}:{port}/{db}" | |
| def gen_private_key(rng: random.Random) -> str: | |
| ktype = rng.choice(["RSA PRIVATE KEY", "EC PRIVATE KEY", "OPENSSH PRIVATE KEY", "PRIVATE KEY"]) | |
| lines = [_rand_str(rng, ALNUM + "+/", 64) for _ in range(rng.randint(2, 4))] | |
| body = "\n".join(lines) | |
| return f"-----BEGIN {ktype}-----\n{body}\n-----END {ktype}-----" | |
| def gen_ip(rng: random.Random) -> str: | |
| return f"{rng.randint(11, 223)}.{rng.randint(0, 255)}.{rng.randint(0, 255)}.{rng.randint(1, 254)}" | |
| def gen_email(rng: random.Random) -> str: | |
| first = rng.choice(["elena", "marcus", "kenji", "sofia", "lukas", "priya", "nadia", "omar", "claire", "mateo", "hanna", "david"]) | |
| last = rng.choice(["vargas", "chen", "kowalski", "dubois", "sato", "patel", "fischer", "rossi", "lindqvist", "kim", "silva", "novak"]) | |
| dom = rng.choice(["acme-fin.io", "northstar-health.org", "meridian-ops.com", "kestrel.de", "solaris-bank.fr", "veritas.co.uk"]) | |
| return f"{first}.{last}{rng.randint(1,99)}@{dom}" | |
| def gen_person(rng: random.Random) -> str: | |
| first = rng.choice(["Elena", "Marcus", "Kenji", "Sofia", "Lukas", "Priya", "Nadia", "Omar", "Claire", "Mateo", "Hanna", "Jane", "John", "Amina", "Tomasz", "Mei"]) | |
| last = rng.choice(["Vargas", "Chen", "Kowalski", "Dubois", "Sato", "Patel", "Fischer", "Rossi", "Lindqvist", "Kim", "Doe", "Smith", "Al-Mansoor", "Bianchi", "Nakamura"]) | |
| return f"{first} {last}" | |
| class SpanBuilder: | |
| """Incrementally constructs text + exact character spans.""" | |
| def __init__(self) -> None: | |
| self.parts: list[str] = [] | |
| self.spans: list[dict[str, Any]] = [] | |
| self.cursor: int = 0 | |
| def add(self, text: str, label: str | None = None) -> "SpanBuilder": | |
| start = self.cursor | |
| self.parts.append(text) | |
| self.cursor += len(text) | |
| if label is not None: | |
| self.spans.append({"start": start, "end": self.cursor, "label": label}) | |
| return self | |
| def build(self, source: str, language: str = "en", category: str = "agent_secrets") -> dict[str, Any]: | |
| full_text = "".join(self.parts) | |
| return { | |
| "text": full_text, | |
| "spans": normalize_and_merge_spans(full_text, self.spans), | |
| "source": source, | |
| "language": language, | |
| "category": category, | |
| } | |
| # Template builders partitioned strictly by split so test templates are never seen in train. | |
| def _build_secret_example(rng: random.Random, split: str) -> dict[str, Any]: | |
| b = SpanBuilder() | |
| if split == "train": | |
| tmpl = rng.choice(["env", "json_tool", "http_log", "yaml_k8s", "python_code", "bash_trace", "mcp_resp", "db_err", "chat_multi", "pem_block"]) | |
| elif split == "validation": | |
| tmpl = rng.choice(["val_toml", "val_curl", "val_slack_incident", "val_ts_config", "val_pem_json"]) | |
| else: | |
| tmpl = rng.choice(["test_dockerfile", "test_gh_action", "test_mcp_audit", "test_terraform", "test_incident_ticket", "test_pem_log"]) | |
| if tmpl == "env": | |
| b.add("# Production agent environment\nAPP_ENV=production\n") | |
| b.add("OPENAI_API_KEY=").add(gen_api_key(rng), "API_KEY").add("\n") | |
| b.add("DATABASE_URL=").add(gen_database_uri(rng), "DATABASE_URI").add("\n") | |
| if rng.random() < 0.6: | |
| b.add("SMTP_PASSWORD=").add(gen_password(rng), "PASSWORD").add("\n") | |
| b.add("ADMIN_EMAIL=").add(gen_email(rng), "EMAIL_ADDRESS").add("\n") | |
| b.add("LOG_LEVEL=info\n") | |
| elif tmpl == "json_tool": | |
| b.add('{"tool":"fetch_workspace_config","status":200,"result":{"owner":"') | |
| b.add(gen_person(rng), "PERSON").add('","contact":"') | |
| b.add(gen_email(rng), "EMAIL_ADDRESS").add('","api_key":"') | |
| b.add(gen_api_key(rng), "API_KEY").add('","token":"') | |
| b.add(gen_auth_token(rng), "AUTH_TOKEN").add('","client_ip":"') | |
| b.add(gen_ip(rng), "IP_ADDRESS").add('"}}') | |
| elif tmpl == "http_log": | |
| b.add(f"[2026-09-14T11:22:08Z] INFO proxy: POST /v1/agents/run from ") | |
| b.add(gen_ip(rng), "IP_ADDRESS").add("\nAuthorization: Bearer ") | |
| b.add(gen_auth_token(rng), "AUTH_TOKEN").add("\nX-API-Key: ") | |
| b.add(gen_api_key(rng), "API_KEY").add("\nContent-Type: application/json\n") | |
| elif tmpl == "yaml_k8s": | |
| b.add("apiVersion: v1\nkind: Secret\nmetadata:\n name: agent-runtime\nstringData:\n db_uri: \"") | |
| b.add(gen_database_uri(rng), "DATABASE_URI").add("\"\n service_password: \"") | |
| b.add(gen_password(rng), "PASSWORD").add("\"\n provider_key: \"") | |
| b.add(gen_api_key(rng), "API_KEY").add("\"\n") | |
| elif tmpl == "python_code": | |
| b.add("import requests\nCLIENT_KEY = '").add(gen_api_key(rng), "API_KEY") | |
| b.add("'\nHEADERS = {'Authorization': 'Bearer ").add(gen_auth_token(rng), "AUTH_TOKEN") | |
| b.add("'}\nDB_CONN = '").add(gen_database_uri(rng), "DATABASE_URI") | |
| b.add("'\nresp = requests.get('https://api.internal/v2/status', headers=HEADERS)\n") | |
| elif tmpl == "bash_trace": | |
| b.add("$ export HF_TOKEN=").add(gen_api_key(rng), "API_KEY") | |
| b.add("\n$ psql '").add(gen_database_uri(rng), "DATABASE_URI") | |
| b.add("' -c 'SELECT count(*) FROM events;'\nConnected as operator ").add(gen_person(rng), "PERSON").add("\n") | |
| elif tmpl == "mcp_resp": | |
| b.add("[MCP tool: read_secret_store] Returned credentials for ") | |
| b.add(gen_email(rng), "EMAIL_ADDRESS").add(":\n- api_key: ") | |
| b.add(gen_api_key(rng), "API_KEY").add("\n- bearer: ") | |
| b.add(gen_auth_token(rng), "AUTH_TOKEN").add("\n- db_pass: ") | |
| b.add(gen_password(rng), "PASSWORD").add("\n") | |
| elif tmpl == "db_err": | |
| b.add("ERROR 2026-10-03 connection pool exhausted for ") | |
| b.add(gen_database_uri(rng), "DATABASE_URI") | |
| b.add(" (origin host ").add(gen_ip(rng), "IP_ADDRESS").add("); notify ") | |
| b.add(gen_email(rng), "EMAIL_ADDRESS").add(".") | |
| elif tmpl == "chat_multi": | |
| lang, intro, lbl_key, lbl_pwd = rng.choice([ | |
| ("de", "Hallo Team, hier sind die Zugangsdaten für ", "API-Schlüssel: ", "Passwort: "), | |
| ("fr", "Bonjour, voici les identifiants de déploiement pour ", "Clé API : ", "Mot de passe : "), | |
| ("es", "Hola equipo, comparto las credenciales de ", "Clave API: ", "Contraseña: "), | |
| ("ja", "お疲れ様です。担当者の", "APIキー: ", "パスワード: "), | |
| ("zh", "你好,这是负责人的测试凭证:", "API密钥:", "密码:"), | |
| ]) | |
| b.add(intro).add(gen_person(rng), "PERSON").add(" (").add(gen_email(rng), "EMAIL_ADDRESS").add(")\n") | |
| b.add(lbl_key).add(gen_api_key(rng), "API_KEY").add("\n") | |
| b.add(lbl_pwd).add(gen_password(rng), "PASSWORD").add("\n") | |
| return b.build(source="tamarillo_synth_secrets", language=lang) | |
| elif tmpl == "pem_block": | |
| b.add("# SSH deploy key for ").add(gen_email(rng), "EMAIL_ADDRESS").add("\n") | |
| b.add(gen_private_key(rng), "PRIVATE_KEY").add("\n") | |
| elif tmpl == "val_toml": | |
| b.add("[runtime.credentials]\nowner = \"").add(gen_person(rng), "PERSON") | |
| b.add("\"\napi_token = \"").add(gen_api_key(rng), "API_KEY") | |
| b.add("\"\nauth_header = \"").add(gen_auth_token(rng), "AUTH_TOKEN") | |
| b.add("\"\npostgres = \"").add(gen_database_uri(rng), "DATABASE_URI").add("\"\n") | |
| elif tmpl == "val_curl": | |
| b.add("curl -sS https://gateway.prod.internal/jobs \\\n -H 'Authorization: Bearer ") | |
| b.add(gen_auth_token(rng), "AUTH_TOKEN").add("' \\\n -H 'X-Service-Key: ") | |
| b.add(gen_api_key(rng), "API_KEY").add("' \\\n --user deploy:") | |
| b.add(gen_password(rng), "PASSWORD").add("\n") | |
| elif tmpl == "val_slack_incident": | |
| b.add("@oncall ").add(gen_person(rng), "PERSON").add(" reported token leak from IP ") | |
| b.add(gen_ip(rng), "IP_ADDRESS").add(". Please revoke ").add(gen_api_key(rng), "API_KEY") | |
| b.add(" and rotate ").add(gen_database_uri(rng), "DATABASE_URI").add(" ASAP.") | |
| elif tmpl == "val_ts_config": | |
| b.add("export const cfg = {\n adminEmail: '").add(gen_email(rng), "EMAIL_ADDRESS") | |
| b.add("',\n secretKey: '").add(gen_api_key(rng), "API_KEY") | |
| b.add("',\n adminPass: '").add(gen_password(rng), "PASSWORD").add("',\n};\n") | |
| elif tmpl == "val_pem_json": | |
| b.add('{"event":"key_export","user":"').add(gen_person(rng), "PERSON") | |
| b.add('","private_key":"').add(gen_private_key(rng).replace("\n", "\\n"), "PRIVATE_KEY").add('"}') | |
| elif tmpl == "test_dockerfile": | |
| b.add("FROM python:3.11-slim\nENV STRIPE_KEY=").add(gen_api_key(rng), "API_KEY") | |
| b.add("\nENV DB_DSN=").add(gen_database_uri(rng), "DATABASE_URI") | |
| b.add("\nENV ROOT_PASS=").add(gen_password(rng), "PASSWORD").add("\nCMD [\"python\", \"app.py\"]\n") | |
| elif tmpl == "test_gh_action": | |
| b.add("steps:\n - name: Deploy agent\n env:\n TOKEN: ").add(gen_auth_token(rng), "AUTH_TOKEN") | |
| b.add("\n PROVIDER_KEY: ").add(gen_api_key(rng), "API_KEY") | |
| b.add("\n run: ./deploy.sh --notify ").add(gen_email(rng), "EMAIL_ADDRESS").add("\n") | |
| elif tmpl == "test_mcp_audit": | |
| b.add("TRACE span_id=9f3a2c tool=shell_exec actor=").add(gen_person(rng), "PERSON") | |
| b.add(" src_ip=").add(gen_ip(rng), "IP_ADDRESS") | |
| b.add(" stdout=\"Connected to ").add(gen_database_uri(rng), "DATABASE_URI") | |
| b.add(" using bearer ").add(gen_auth_token(rng), "AUTH_TOKEN").add("\"") | |
| elif tmpl == "test_terraform": | |
| b.add('resource "vault_secret" "prod" {\n api_key = "').add(gen_api_key(rng), "API_KEY") | |
| b.add('"\n db_password = "').add(gen_password(rng), "PASSWORD") | |
| b.add('"\n owner_email = "').add(gen_email(rng), "EMAIL_ADDRESS").add('"\n}\n') | |
| elif tmpl == "test_incident_ticket": | |
| b.add("INC-4821: Agent inadvertently logged credentials of ").add(gen_person(rng), "PERSON") | |
| b.add(" (").add(gen_email(rng), "EMAIL_ADDRESS").add("). Exposed secret: ") | |
| b.add(gen_api_key(rng), "API_KEY").add(" and session cookie ") | |
| b.add(gen_auth_token(rng), "AUTH_TOKEN").add(".") | |
| else: # test_pem_log | |
| b.add("WARN key-loader: loaded unencrypted key from /etc/agent/id_ed25519:\n") | |
| b.add(gen_private_key(rng), "PRIVATE_KEY").add("\nOperator: ").add(gen_person(rng), "PERSON") | |
| return b.build(source="tamarillo_synth_secrets", language="en") | |
| def _build_hard_negative(rng: random.Random, split: str) -> dict[str, Any]: | |
| """Generate realistic ZERO-entity hard negatives that break regexes and over-sensitive PII models.""" | |
| git_sha = _rand_str(rng, HEX_LOWER, 40) | |
| sha256 = _rand_str(rng, HEX_LOWER, 64) | |
| md5 = _rand_str(rng, HEX_LOWER, 32) | |
| uuid4 = f"{_rand_str(rng, HEX_LOWER, 8)}-{_rand_str(rng, HEX_LOWER, 4)}-4{_rand_str(rng, HEX_LOWER, 3)}-a{_rand_str(rng, HEX_LOWER, 3)}-{_rand_str(rng, HEX_LOWER, 12)}" | |
| ver = f"{rng.randint(1,9)}.{rng.randint(0,25)}.{rng.randint(0,40)}.{rng.randint(0,99)}" | |
| x_rep = "x" * rng.randint(12, 28) | |
| star_rep = "*" * rng.randint(12, 24) | |
| svc = rng.choice(["gateway", "scheduler", "indexer", "worker", "telemetry", "router", "billing-svc"]) | |
| region = rng.choice(["us-east-1", "eu-central-1", "ap-northeast-1", "us-west-2"]) | |
| train_pool = [ | |
| f"# Example .env template (replace placeholders before running)\nOPENAI_API_KEY=sk-proj-{x_rep}\nANTHROPIC_API_KEY=sk-ant-{x_rep}\nDATABASE_URL=postgresql://USER:PASSWORD@localhost:5432/dbname\nJWT_SECRET=<REPLACE_WITH_SECRET>\n", | |
| f"import os\napi_key = os.environ['OPENAI_API_KEY']\ntoken = os.getenv('GITHUB_TOKEN', 'ghp_{x_rep}')\npassword = config.get('db_password', '{star_rep}')\n", | |
| f"commit {git_sha}\nAuthor: Release Bot\nDate: 2026-10-12\n\nUpgrade {svc} to v{ver}. Checksum sha256:{sha256} md5:{md5}.\n", | |
| f'{{"request_id":"{uuid4}","status":"ok","service":"{svc}","region":"{region}","latency_ms":14.2,"tokens":512,"version":"{ver}","etag":"{md5}"}}', | |
| f"Please configure your client with `Authorization: Bearer <YOUR_ACCESS_TOKEN>` or `sk-your-key-here` and send a POST request to https://api.example.com/v1/health.", | |
| f"In Q4 2026, p95 latency dropped by {rng.randint(15,65)}% across Germany, France, Japan, and the United States after migrating {svc} to ONNX Runtime.", | |
| f"docker pull ghcr.io/org/{svc}@sha256:{sha256}\nkubectl get pods -n prod-{region}-v{rng.randint(1,9)} --selector=app={svc}\n", | |
| "Example placeholder email: user@example.com, support@example.org, test@localhost. Documentation phone: 555-0100 (RFC 2606 / NANPA fictional).", | |
| f"The software engineer updated the PostgreSQL schema on Tuesday at 14:30 UTC (migration {git_sha[:12]}) to improve query throughput.", | |
| "const token = process.env.AUTH_TOKEN ?? '';\nconst dsn = `postgres://${DB_USER}:${DB_PASS}@${DB_HOST}:5432/app`;\nconst key = 'YOUR_STRIPE_KEY_HERE';\n", | |
| f"export HF_TOKEN=\"hf_{x_rep}\"\nexport AWS_ACCESS_KEY_ID=\"AKIAIOSFODNN7EXAMPLE\"\nexport STRIPE_KEY=\"sk_test_{x_rep}\"\n", | |
| f"INFO {svc}: checkpoint hash={sha256[:32]} build_id={uuid4} rev={git_sha} schema_version={ver} status=healthy", | |
| f"Das Update {ver} für den Dienst {svc} reduzierte den Speicherverbrauch in Frankfurt um {rng.randint(10,45)} Prozent (Commit {git_sha[:10]}).", | |
| f"La mise à jour {ver} du module {svc} améliore la latence moyenne de {rng.randint(12,40)} ms sans changer l'API publique.", | |
| f"バージョン {ver} のリリースノート: サービス {svc} のメモリ使用量を削減し、チェックサム {md5} を検証しました。", | |
| ] | |
| val_pool = [ | |
| f"Build artifact verified: sha256={sha256} | git_rev={git_sha} | trace_id={uuid4} | semver={ver} | md5={md5}", | |
| f"Set `export ANTHROPIC_API_KEY=\"sk-ant-{x_rep}\"` or `OPENAI_API_KEY=YOUR_API_KEY` in your shell profile before invoking {svc}.", | |
| "RFC 2606 reserves example.com and example.net for documentation. Never hardcode passwords; read `os.environ.get('DB_PASSWORD')` instead.", | |
| f"Quarterly engineering review: TypeScript, Rust, and Python microservices ({svc}) maintained 99.98% uptime in Frankfurt and Tokyo regions.", | |
| f"curl -H 'Authorization: Bearer <TOKEN>' -H 'X-Request-Id: {uuid4}' https://docs.example.org/api/v2/metrics", | |
| ] | |
| test_pool = [ | |
| f"Helm release rev={rng.randint(10,99)} digest=sha256:{sha256} correlation_id={uuid4} commit={git_sha} app_version={ver}", | |
| f"To authenticate, pass `-H 'Authorization: Bearer YOUR_TOKEN_HERE'` or set `STRIPE_API_KEY=sk_test_placeholder_{x_rep[:8]}` in CI.", | |
| "def connect(env):\n return psycopg2.connect(host=env['PGHOST'], user=env['PGUSER'], password=env['PGPASSWORD'])\n", | |
| f"API reference: HTTP 401 Unauthorized is returned when the X-API-Key header is missing. Trace {uuid4}. See https://docs.example.org/auth.", | |
| f"Die neue Version {ver} reduziert den Speicherbedarf um 35 Prozent und unterstützt UTF-8-Kodierung (SHA {git_sha[:16]}).", | |
| f"La actualización del servidor {svc} en marzo de 2026 mejoró la latencia de red en un 28 por ciento para todos los contenedores.", | |
| f"CI pipeline passed: artifact_md5={md5} image_digest=sha256:{sha256} target={region} service={svc}.", | |
| ] | |
| pool = train_pool if split == "train" else (val_pool if split == "validation" else test_pool) | |
| text = rng.choice(pool) | |
| return { | |
| "text": text, | |
| "spans": [], | |
| "source": "tamarillo_hard_negatives", | |
| "language": "en", | |
| "category": "hard_negative", | |
| } | |
| def generate_secrets_and_negatives( | |
| split: str, | |
| n_secrets: int, | |
| n_hard_negatives: int, | |
| seed: int, | |
| ) -> list[dict[str, Any]]: | |
| rng = random.Random(seed) | |
| rows: list[dict[str, Any]] = [] | |
| for _ in range(n_secrets): | |
| rows.append(_build_secret_example(rng, split)) | |
| for _ in range(n_hard_negatives): | |
| rows.append(_build_hard_negative(rng, split)) | |
| rng.shuffle(rows) | |
| return rows | |
| def build_long_context_needle_suite( | |
| needle_examples: list[dict[str, Any]], | |
| target_char_depths: list[int] | None = None, | |
| seed: int = 202611, | |
| ) -> list[dict[str, Any]]: | |
| """ | |
| Embed labeled PII/secret examples at controlled character depths (~256..5120 tokens) | |
| inside benign realistic log/documentation haystacks. | |
| Note: 1 token ~ 4 chars, so char depths [1000, 3200, 6400, 12800, 20000] correspond | |
| roughly to token depths [250, 800, 1600, 3200, 5000]. | |
| """ | |
| if target_char_depths is None: | |
| target_char_depths = [1000, 3200, 6400, 12800, 20000] | |
| rng = random.Random(seed) | |
| filler_lines = [ | |
| "INFO worker.pool: heartbeat ok queue_depth=12 active_workers=8 mem_mb=412 cpu_pct=18.4", | |
| "DEBUG router.http: GET /v1/healthz status=200 latency_ms=2.1 cache_hit=true region=eu-central", | |
| "INFO metrics.flush: exported 240 telemetry spans to collector batch_bytes=48192 retries=0", | |
| "DEBUG scheduler.tick: evaluated 16 cron triggers next_run_sec=45 lock_acquired=true", | |
| "INFO compiler.cache: reused 94 intermediate artifacts build_time_ms=812 target=linux-amd64", | |
| "INFO storage.gc: compacted 3 segment files reclaimed_mb=128 remaining_segments=41", | |
| ] | |
| out: list[dict[str, Any]] = [] | |
| for depth in target_char_depths: | |
| for ex in needle_examples: | |
| if not ex.get("spans"): | |
| continue | |
| prefix_parts: list[str] = [] | |
| cur_len = 0 | |
| while cur_len < depth: | |
| line = f"[step={rng.randint(1000,9999)}] " + rng.choice(filler_lines) + "\n" | |
| prefix_parts.append(line) | |
| cur_len += len(line) | |
| prefix = "".join(prefix_parts) | |
| suffix = "\n" + "\n".join(rng.choice(filler_lines) for _ in range(4)) | |
| offset = len(prefix) | |
| shifted_spans = [ | |
| {"start": sp["start"] + offset, "end": sp["end"] + offset, "label": sp["label"]} | |
| for sp in ex["spans"] | |
| ] | |
| out.append({ | |
| "text": prefix + ex["text"] + suffix, | |
| "spans": shifted_spans, | |
| "source": "long_context_needle", | |
| "target_char_depth": depth, | |
| "approx_token_depth": depth // 4, | |
| }) | |
| return out | |
| if __name__ == "__main__": | |
| # Quick local sanity verification | |
| for sp in ("train", "validation", "test"): | |
| rows = generate_secrets_and_negatives(sp, n_secrets=10, n_hard_negatives=10, seed=42) | |
| for r in rows: | |
| for s in r["spans"]: | |
| assert 0 <= s["start"] < s["end"] <= len(r["text"]), f"Bad span: {s}" | |
| assert r["text"][s["start"]:s["end"]].strip() != "", "Empty span" | |
| print(f"{sp}: {len(rows)} rows OK, total spans={sum(len(r['spans']) for r in rows)}") | |
| needles = generate_secrets_and_negatives("test", n_secrets=5, n_hard_negatives=0, seed=99) | |
| lc = build_long_context_needle_suite(needles, target_char_depths=[1000, 6400]) | |
| for r in lc: | |
| for s in r["spans"]: | |
| assert 0 <= s["start"] < s["end"] <= len(r["text"]) | |
| print(f"long_context_needle: {len(lc)} rows OK") | |