shantomathew's picture
ToolTune code, article and training notebook (Lexsi Track 3)
1a7314a verified
Raw History Blame Contribute Delete
13.8 kB
"""Tool definitions + deterministic task suite for the Lexsi Track 3 pipeline.
Tools (5): search, calculator, calendar_lookup, price_lookup, weather_lookup.
Tasks are generated from shared template families but with ENTITY/VALUE-DISJOINT
train/test pools: no city, symbol, person, topic, date, or arithmetic operand
combination in the test split appears in the train split. Template *wording*
families are shared (same task distribution) -- this is disclosed in ARTICLE.md.
Every task has exactly one gold tool call with fully specified arguments, so
scoring is deterministic and verifiable.
"""
from __future__ import annotations
import hashlib
import json
import re
# ---------------------------------------------------------------- tool schemas
# OpenAI function-calling format -- the format auditkit.Sample.tools expects.
TOOL_SCHEMAS = [
{
"type": "function",
"function": {
"name": "search",
"description": "Search the web / knowledge base for a topic.",
"parameters": {
"type": "object",
"properties": {"query": {"type": "string"}},
"required": ["query"],
},
},
},
{
"type": "function",
"function": {
"name": "calculator",
"description": "Evaluate an arithmetic expression.",
"parameters": {
"type": "object",
"properties": {"expression": {"type": "string"}},
"required": ["expression"],
},
},
},
{
"type": "function",
"function": {
"name": "calendar_lookup",
"description": "Look up a person's calendar events on a date.",
"parameters": {
"type": "object",
"properties": {
"date": {"type": "string"},
"person": {"type": "string"},
},
"required": ["date", "person"],
},
},
},
{
"type": "function",
"function": {
"name": "price_lookup",
"description": "Look up the current price of a ticker symbol.",
"parameters": {
"type": "object",
"properties": {"symbol": {"type": "string"}},
"required": ["symbol"],
},
},
},
{
"type": "function",
"function": {
"name": "weather_lookup",
"description": "Look up the weather forecast for a city on a date.",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string"},
"date": {"type": "string"},
},
"required": ["city", "date"],
},
},
},
]
TOOL_NAMES = [t["function"]["name"] for t in TOOL_SCHEMAS]
REQUIRED_ARGS = {
t["function"]["name"]: t["function"]["parameters"]["required"] for t in TOOL_SCHEMAS
}
# ------------------------------------------------------- deterministic tools
def _h(s: str) -> int:
return int(hashlib.sha256(s.encode()).hexdigest()[:8], 16)
def run_tool(name: str, arguments: dict) -> str:
"""Execute a tool deterministically (no network, no randomness)."""
if name == "search":
q = arguments.get("query", "")
return f"3 results for '{q}': [1] Overview of {q} [2] Latest news on {q} [3] Reference: {q}"
if name == "calculator":
expr = arguments.get("expression", "")
if not re.fullmatch(r"[0-9+\-*/(). ]+", expr or ""):
return f"ERROR: invalid expression {expr!r}"
try:
return str(eval(expr, {"__builtins__": {}}, {})) # safe: charset-checked above
except Exception as e: # noqa: BLE001
return f"ERROR: {e}"
if name == "calendar_lookup":
person, date = arguments.get("person", ""), arguments.get("date", "")
slot = ["09:00 standup", "13:00 design review", "16:30 focus block"][_h(person + date) % 3]
return f"{person} on {date}: {slot}"
if name == "price_lookup":
sym = arguments.get("symbol", "")
price = 10 + (_h(sym) % 40000) / 100.0
return f"{sym}: ${price:.2f}"
if name == "weather_lookup":
city, date = arguments.get("city", ""), arguments.get("date", "")
cond = ["sunny", "cloudy", "rain", "windy"][_h(city + date) % 4]
temp = 40 + _h(city) % 55
return f"{city} on {date}: {cond}, {temp}F"
return f"ERROR: unknown tool {name!r}"
# ------------------------------------------------------------------- entities
# TRAIN pools
TRAIN_TOPICS = [
"quantum error correction", "vertical farming techniques", "ocean tidal energy",
"medieval trade routes", "bonsai tree care", "deep sea hydrothermal vents",
"history of jazz music", "glacier retreat studies", "urban beekeeping guide",
"ancient roman aqueducts", "volcanic island formation", "desert dune migration",
"coral reef restoration", "viking navigation methods", "solar flare prediction",
"wetland bird migration", "antique clock restoration", "permafrost carbon storage",
"submarine cable networks", "alpine plant adaptation", "early photography methods",
"tidal wetland ecology", "nomadic herding cultures", "crystal cave geology",
"monsoon rainfall patterns", "seed vault preservation",
]
TRAIN_EXPRS = [
"17 * 6", "144 / 12", "23 + 58", "91 - 37", "8 * 14", "256 / 16", "45 + 129",
"300 - 87", "12 * 12", "99 / 9", "64 + 36", "150 - 44", "7 * 19", "420 / 20",
"88 + 47", "512 - 128", "15 * 9", "180 / 15", "73 + 28", "240 - 96", "11 * 11",
"625 / 25", "56 + 84", "310 - 155", "9 * 16", "432 / 18",
]
TRAIN_PEOPLE = ["Alice", "Bruno", "Carmen", "Devon", "Elena", "Farid", "Greta", "Hiro"]
TRAIN_DATES_CAL = [
"2026-12-01", "2026-12-03", "2026-12-05", "2026-12-08", "2026-12-10",
"2026-12-12", "2026-12-15", "2026-12-17",
]
TRAIN_SYMBOLS = ["AAPL", "MSFT", "NVDA", "AMZN", "GOOG", "META", "TSLA", "NFLX",
"AMD", "INTC", "CRM", "ORCL", "UBER", "SHOP", "SQ", "PYPL", "ADBE",
"AVGO", "QCOM", "TXN", "AMGN", "COST", "SBUX", "GILD", "MDLZ", "ADI"]
TRAIN_CITIES = ["Denver", "Austin", "Portland", "Chicago", "Miami", "Seattle",
"Boston", "Phoenix"]
TRAIN_DATES_WX = [
"2026-12-02", "2026-12-04", "2026-12-06", "2026-12-09", "2026-12-11",
"2026-12-13", "2026-12-16", "2026-12-18",
]
# TEST pools -- disjoint from train pools above (verified in build_tasks()).
TEST_TOPICS = [
"mangrove forest ecosystems", "byzantine mosaic art", "high altitude railways",
"fermentation food science", "aurora borealis forecasting", "sandstone canyon trails",
"historic lighthouse keepers", "rice terrace irrigation",
]
TEST_EXPRS = ["19 * 7", "169 / 13", "67 + 85", "420 - 138", "13 * 13", "288 / 24",
"95 + 106", "700 - 245"]
TEST_PEOPLE = ["Ingrid", "Jasper", "Keiko", "Liam"]
TEST_DATES_CAL = ["2027-01-05", "2027-01-07", "2027-01-12", "2027-01-14"]
TEST_SYMBOLS = ["COIN", "HOOD", "PLTR", "RIVN", "SNOW", "NET", "DDOG", "CRWD"]
TEST_CITIES = ["Nashville", "San Diego", "Atlanta", "Dallas"]
TEST_DATES_WX = ["2027-01-06", "2027-01-08", "2027-01-13", "2027-01-15"]
def _task(tid, prompt, tool, args):
return {"id": tid, "prompt": prompt, "tool": tool, "arguments": args}
def build_tasks():
"""Return (train_tasks, test_tasks). Deterministic ordering, no RNG."""
train, test = [], []
# ---- search: 3 template families; family C carries a distractor verb ----
for i, topic in enumerate(TRAIN_TOPICS):
fam = i % 3
if fam == 0:
p = f"Search for {topic}"
elif fam == 1:
p = f"Look up information about {topic}"
else:
p = f"Find articles on {topic}"
train.append(_task(f"train-search-{i:02d}", p, "search", {"query": topic}))
for i, topic in enumerate(TEST_TOPICS):
fam = i % 3
if fam == 0:
p = f"Search for {topic}"
elif fam == 1:
p = f"Look up information about {topic}"
else:
p = f"Find articles on {topic}"
test.append(_task(f"test-search-{i:02d}", p, "search", {"query": topic}))
# ---- calculator: family C prefixes a search distractor verb ----
for i, expr in enumerate(TRAIN_EXPRS):
fam = i % 3
if fam == 0:
p = f"Calculate {expr}"
elif fam == 1:
p = f"What is {expr}?"
else:
p = f"Search your memory and calculate {expr}"
train.append(_task(f"train-calc-{i:02d}", p, "calculator", {"expression": expr}))
for i, expr in enumerate(TEST_EXPRS):
fam = i % 3
if fam == 0:
p = f"Calculate {expr}"
elif fam == 1:
p = f"What is {expr}?"
else:
p = f"Search your memory and calculate {expr}"
test.append(_task(f"test-calc-{i:02d}", p, "calculator", {"expression": expr}))
# ---- calendar_lookup: person x date grid; family B starts with 'Find' ----
k = 0
for i, person in enumerate(TRAIN_PEOPLE):
for j in range(3 if i < 2 else 2): # 2*3 + 6*2 = 18... pad below to 26
date = TRAIN_DATES_CAL[(i + j) % len(TRAIN_DATES_CAL)]
fam = k % 2
if fam == 0:
p = f"Check the calendar for {person} on {date}"
else:
p = f"Find what is on the schedule for {person} on {date}"
train.append(_task(f"train-cal-{k:02d}", p, "calendar_lookup",
{"date": date, "person": person}))
k += 1
# pad calendar train to 26 with extra person/date combos (still train pools)
extra = [("Alice", "2026-12-19"), ("Bruno", "2026-12-20"), ("Carmen", "2026-12-21"),
("Devon", "2026-12-22"), ("Elena", "2026-12-23"), ("Farid", "2026-12-24"),
("Greta", "2026-12-27"), ("Hiro", "2026-12-28")]
for person, date in extra:
fam = k % 2
if fam == 0:
p = f"Check the calendar for {person} on {date}"
else:
p = f"Find what is on the schedule for {person} on {date}"
train.append(_task(f"train-cal-{k:02d}", p, "calendar_lookup",
{"date": date, "person": person}))
k += 1
k = 0
for i, person in enumerate(TEST_PEOPLE):
for j, date in enumerate(TEST_DATES_CAL):
if (i + j) % 2 == 0:
fam = k % 2
if fam == 0:
p = f"Check the calendar for {person} on {date}"
else:
p = f"Find what is on the schedule for {person} on {date}"
test.append(_task(f"test-cal-{k:02d}", p, "calendar_lookup",
{"date": date, "person": person}))
k += 1
if k >= 8:
break
if k >= 8:
break
# ---- price_lookup: family B prefixes 'Search ...' (distractor) ----
for i, sym in enumerate(TRAIN_SYMBOLS):
fam = i % 2
if fam == 0:
p = f"What is the price of {sym}?"
else:
p = f"Search the market data for the price of {sym}"
train.append(_task(f"train-price-{i:02d}", p, "price_lookup", {"symbol": sym}))
for i, sym in enumerate(TEST_SYMBOLS):
fam = i % 2
if fam == 0:
p = f"What is the price of {sym}?"
else:
p = f"Search the market data for the price of {sym}"
test.append(_task(f"test-price-{i:02d}", p, "price_lookup", {"symbol": sym}))
# ---- weather_lookup: city x date grid ----
k = 0
combos = []
for i, city in enumerate(TRAIN_CITIES):
for j in range(3):
combos.append((city, TRAIN_DATES_WX[(i + j) % len(TRAIN_DATES_WX)]))
combos += [("Denver", "2026-12-19"), ("Austin", "2026-12-20")]
for city, date in combos[:26]:
fam = k % 2
if fam == 0:
p = f"What is the weather in {city} on {date}?"
else:
p = f"Weather forecast for {city} on {date}"
train.append(_task(f"train-wx-{k:02d}", p, "weather_lookup",
{"city": city, "date": date}))
k += 1
k = 0
for i, city in enumerate(TEST_CITIES):
for j, date in enumerate(TEST_DATES_WX):
if (i + j) % 2 == 0:
fam = k % 2
if fam == 0:
p = f"What is the weather in {city} on {date}?"
else:
p = f"Weather forecast for {city} on {date}"
test.append(_task(f"test-wx-{k:02d}", p, "weather_lookup",
{"city": city, "date": date}))
k += 1
if k >= 8:
break
if k >= 8:
break
# ---- disjointness assertions (entities/values, not wording) ----
def vals(tasks, key):
return {t["arguments"][key] for t in tasks if key in t["arguments"]}
for key in ["query", "expression", "person", "symbol", "city"]:
overlap = vals(train, key) & vals(test, key)
assert not overlap, f"train/test overlap on {key}: {overlap}"
train_prompts = {t["prompt"] for t in train}
test_prompts = {t["prompt"] for t in test}
assert not (train_prompts & test_prompts), "identical prompt in both splits"
return train, test
if __name__ == "__main__":
tr, te = build_tasks()
print(f"train={len(tr)} test={len(te)}")
from collections import Counter
print("train tools:", Counter(t["tool"] for t in tr))
print("test tools:", Counter(t["tool"] for t in te))
print(json.dumps(te[:3], indent=2))