"""Shared helpers for the ToolFault-Bench generator.""" from __future__ import annotations import json import random from dataclasses import dataclass, field from datetime import datetime, timedelta, timezone from typing import Any UTC = timezone.utc FIRST = [ "Aisha", "Mateo", "Priya", "Jonah", "Mei", "Oluwaseun", "Camila", "Tomasz", "Hana", "Diego", "Fatima", "Liam", "Ngozi", "Kenji", "Sofia", "Arjun", "Elena", "Kwame", "Ingrid", "Rafael", "Yara", "Declan", "Leila", "Marcus", "Anika", "Joaquin", "Thandiwe", "Sebastian", "Noor", "Viktor", "Chiara", "Emeka", "Rosa", "Hamid", "Greta", "Tariq", "Lucia", "Dmitri", "Amara", "Owen", ] LAST = [ "Okafor", "Lindqvist", "Ramanathan", "Castillo", "Whitfield", "Nakamura", "Haddad", "Kowalski", "Mensah", "Delacroix", "Fitzgerald", "Balogun", "Serrano", "Novak", "Achterberg", "Iyer", "Moreau", "Petrov", "Adeyemi", "Galloway", "Takahashi", "Brennan", "Vasquez", "Osei", "Holmberg", "Rahman", "Ferreira", "Kaminski", "Abernathy", "Quintero", "Sato", "Lindgren", ] CO_A = [ "Northwind", "Bluegate", "Cedarline", "Ironbark", "Pinecrest", "Silverleaf", "Harborview", "Redstone", "Kestrel", "Brightwater", "Summit", "Larchmont", "Copperfield", "Driftwood", "Meridian", "Halcyon", "Obsidian", "Juniper", "Wexford", "Tallgrass", ] CO_B = [ "Plumbing & Heating", "Office Supply", "Freight LLC", "Janitorial Services", "Electrical Contractors", "Staffing Group", "Packaging Co.", "IT Services", "Landscaping", "Industrial Supply", "Print & Mail", "Catering", "Security Systems", "Logistics Inc.", "Analytics LLC", ] MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] @dataclass class Call: tool: str args: dict response: Any = None @dataclass class Ctx: rng: random.Random now: datetime org: str = "" user: str = "" extra: dict = field(default_factory=dict) # ---------- time ---------- def iso(dt: datetime) -> str: return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ") def ymd(dt: datetime) -> str: return dt.strftime("%Y-%m-%d") def human_date(dt: datetime) -> str: return f"{MONTHS[dt.month - 1]} {dt.day}, {dt.year}" def month_name(dt: datetime) -> str: return f"{MONTHS[dt.month - 1]} {dt.year}" def prev_month_range(now: datetime) -> tuple[datetime, datetime]: first_this = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0) last_prev = first_this - timedelta(days=1) first_prev = last_prev.replace(day=1) return first_prev, last_prev def next_business_day(dt: datetime) -> datetime: d = dt + timedelta(days=1) while d.weekday() >= 5: d += timedelta(days=1) return d def sample_now(rng: random.Random, weekend: bool = False) -> datetime: """A timestamp in 2026 during US business hours (weekday) or on a Saturday.""" start = datetime(2026, 3, 2, tzinfo=UTC) while True: d = start + timedelta(days=rng.randint(0, 200)) if weekend and d.weekday() == 5: break if not weekend and d.weekday() < 5: break return d.replace(hour=rng.randint(14, 20), minute=rng.randint(0, 59), second=rng.randint(0, 59)) # ---------- values ---------- def money(rng: random.Random, lo: float, hi: float) -> float: return round(rng.uniform(lo, hi), 2) def usd(x: float) -> str: return f"${x:,.2f}" def rid(rng: random.Random, prefix: str, digits: int = 5) -> str: first = str(rng.randint(1, 9)) rest = "".join(str(rng.randint(0, 9)) for _ in range(digits - 1)) return prefix + first + rest def token(rng: random.Random, n: int = 16) -> str: alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" return "".join(rng.choice(alphabet) for _ in range(n)) def person(rng: random.Random) -> str: return f"{rng.choice(FIRST)} {rng.choice(LAST)}" def company(rng: random.Random) -> str: return f"{rng.choice(CO_A)} {rng.choice(CO_B)}" def transpose_digits(ident: str, rng: random.Random) -> str: """Swap two adjacent, different digits in the numeric part of an ID.""" chars = list(ident) idx = [i for i in range(len(chars) - 1) if chars[i].isdigit() and chars[i + 1].isdigit() and chars[i] != chars[i + 1]] i = rng.choice(idx) chars[i], chars[i + 1] = chars[i + 1], chars[i] out = "".join(chars) assert out != ident return out def misspell(name: str, rng: random.Random) -> str: """Drop or swap one interior letter of a word with >= 5 letters (stays recognisable).""" words = name.split() cand = [i for i, w in enumerate(words) if len(w) >= 5 and w.isalpha()] i = rng.choice(cand) w = words[i] j = rng.randint(1, len(w) - 3) if rng.random() < 0.5 or w[j] == w[j + 1]: w2 = w[:j] + w[j + 1:] else: w2 = w[:j] + w[j + 1] + w[j] + w[j + 2:] words[i] = w2 out = " ".join(words) assert out != name return out # ---------- tool specs (OpenAI function format) ---------- def S(desc: str, enum: list[str] | None = None) -> dict: d = {"type": "string", "description": desc} if enum: d["enum"] = enum return d def N(desc: str) -> dict: return {"type": "number", "description": desc} def I(desc: str) -> dict: return {"type": "integer", "description": desc} def B(desc: str) -> dict: return {"type": "boolean", "description": desc} def tool(name: str, desc: str, props: dict, required: list[str] | tuple = ()) -> dict: return { "type": "function", "function": { "name": name, "description": desc, "parameters": {"type": "object", "properties": props, "required": list(required)}, }, } def dumps(obj: Any) -> str: return obj if isinstance(obj, str) else json.dumps(obj, ensure_ascii=False)