"""ORPHEON v4 — Delta dataset: solo tool calling behavior. El modelo base Qwen 2.5 ya sabe ingeniería estructural. Este dataset solo enseña CÓMO llamar herramientas, no conocimiento estructural. Excluye: preguntas generales, definiciones, conceptos básicos. Incluye: patrones de tool_call, cadenas, multi-turn, adversarial, clarificación. """ import json, os, random, re, math, itertools from typing import Any SEED = 42 random.seed(SEED) OUT = "finetune/datasets/07_delta.jsonl" DPO_OUT = "finetune/datasets/07_delta_dpo.jsonl" os.makedirs("finetune/datasets", exist_ok=True) # ── System prompts: SOLO instrucciones de tool calling, sin conocimiento general ── DELTA_SYSTEM_PROMPTS = [ "Eres ORPHEON, un asistente con herramientas. DEBES llamar una herramienta ANTES de responder cualquier valor numérico. Responde en lenguaje natural después.", "Tienes acceso a herramientas de cálculo estructural, búsqueda web, y normativas. Siempre que un usuario pida datos, llama la herramienta adecuada.", "You are ORPHEON, a structural assistant with tools. You MUST call a tool before providing any numerical data.", "Ești ORPHEON, un asistent cu unelte. Trebuie să folosești o unealtă INAINTE de a răspunde cu valori numerice.", "Você é ORPHEON, um assistente com ferramentas. SEMPRE chame uma ferramenta antes de responder com números.", ] def tc(name, args): return f"{{\"name\": \"{name}\", \"arguments\": {json.dumps(args)}}}" def tr(name, content): return f"{{\"name\": \"{name}\", \"content\": {json.dumps(content)}}}" def make_delta(conversations, cat, diff="facil"): sys_prompt = random.choice(DELTA_SYSTEM_PROMPTS) return {"conversations": [{"from": "system", "value": sys_prompt}] + conversations, "category": cat, "difficulty": diff} # ═════════════════════════════════════════════════════════════════════════════ # 1. TOOL CALL PATTERNS (structural + MCP + construction) # ═════════════════════════════════════════════════════════════════════════════ STEEL_GRADES = {"S235": 235, "S275": 275, "S355": 355} CITIES = ["Bucuresti", "Focsani", "Iasi", "Timisoara", "Cluj"] SOILS = [("arena densa", 400), ("arena media", 250), ("arcilla dura", 300)] TC_TYPES = ["concrete_casting", "rebar_tying", "masonry_walls", "mep_installation", "foundation_excavation"] PRODUCTIVITY_RATES = { "concrete_casting": 15.0, "rebar_tying": 300.0, "masonry_walls": 20.0, "mep_installation": 5.0, "foundation_excavation": 50.0, } section_db = [ ("IPE-300", 53.8, 557.1, 42.2, 8356, 300, 150, 7.1, 10.7), ("IPE-360", 72.7, 904.0, 57.1, 16270, 360, 170, 8.0, 12.7), ("IPE-400", 84.5, 1160.0, 66.3, 23130, 400, 180, 8.6, 13.5), ("HEB-200", 78.1, 569.6, 61.3, 5696, 200, 200, 9.0, 15.0), ("HEB-300", 149, 1680, 117, 25170, 300, 300, 11.0, 19.0), ] def gen_tool_patterns(count): """Solo patrones de tool calling — UNA llamada, datos conocidos.""" examples = [] # lookup_section for _ in range(count // 17): name, A, Wy, mass, Iy, h, b, tw, tf = random.choice(section_db) q = f"Peso del {name}?" content = {"mass": mass, "A": A, "Wy": Wy} examples.append(make_delta([ {"from": "human", "value": q}, {"from": "gpt", "value": tc("lookup_section", {"profile": name})}, {"from": "tool", "value": tr("lookup_section", content)}, {"from": "gpt", "value": f"El {name} pesa {mass} kg/m."}, ], "acero", "facil")) # verify_bending for _ in range(count // 17): name, A, Wy, mass, Iy, h, b, tw, tf = random.choice(section_db) M = random.randint(50, 500) sigma = round(M * 1e6 / (Wy * 1e3), 1) fyd = 275 util = round(sigma / fyd, 3) passed = util <= 1.0 q = f"{name} S275 con M={M}kNm?" examples.append(make_delta([ {"from": "human", "value": q}, {"from": "gpt", "value": tc("verify_bending", {"M_Ed_kNm": M, "W_el_cm3": Wy, "fy_MPa": 275})}, {"from": "tool", "value": tr("verify_bending", {"sigma_MPa": sigma, "fyd_MPa": fyd, "utilisation": util, "passed": passed})}, {"from": "gpt", "value": f"σ={sigma}MPa, fyd=275MPa, u={util:.0%}. {'✅' if passed else '❌'}."}, ], "acero", "facil")) # design_rc_section for _ in range(count // 17): b = random.randint(25, 50) h = random.randint(40, 80) M = random.randint(50, 400) As = round(M * 1e6 / (0.87 * 500 * (h-5) * 10), 1) q = f"Viga {b}x{h} M={M}kNm" examples.append(make_delta([ {"from": "human", "value": q}, {"from": "gpt", "value": tc("design_rc_section", {"b_m": b/100, "h_m": h/100, "M_Ed_kNm": M, "fck_MPa": 25, "fyk_MPa": 500})}, {"from": "tool", "value": tr("design_rc_section", {"As_bot_cm2": As, "passed": True})}, {"from": "gpt", "value": f"As ≈ {As} cm²."}, ], "hormigon", "facil")) # verify_timber_bending for _ in range(count // 17): b = random.randint(40, 120) h = random.randint(120, 240) M = random.randint(5, 20) q = f"Viga C24 {b}x{h} M={M}kNm" examples.append(make_delta([ {"from": "human", "value": q}, {"from": "gpt", "value": tc("verify_timber_bending", {"b_mm": b, "h_mm": h, "M_Ed_kNm": M, "strength_class": "C24"})}, {"from": "tool", "value": tr("verify_timber_bending", {"sigma_MPa": round(M*1e6/(b*h*h/6)/1e3,1), "passed": False})}, {"from": "gpt", "value": "No verifica. Aumentar sección."}, ], "madera", "media")) # verify_bolted_connection for _ in range(count // 17): n = random.randint(2, 8) d = random.choice([12, 16, 20]) F = random.uniform(50, 300) q = f"{n} M{d} 8.8 F={F:.0f}kN" examples.append(make_delta([ {"from": "human", "value": q}, {"from": "gpt", "value": tc("verify_bolted_connection", {"bolt_grade": "8.8", "d_mm": d, "n_bolts": n, "F_Ed_kN": F, "t_pl_mm": 10})}, {"from": "tool", "value": tr("verify_bolted_connection", {"utilisation": round(F/(30*n),2), "passed": F <= 30*n})}, {"from": "gpt", "value": f"{'✅' if F <= 30*n else '❌'} u={F/(30*n):.0%}."}, ], "conexiones", "facil")) # get_seismic_params for _ in range(count // 17): c = random.choice(CITIES) q = f"Aceleración de {c}?" ag = 0.30 if c == "Bucuresti" else 0.40 if c == "Focsani" else 0.25 examples.append(make_delta([ {"from": "human", "value": q}, {"from": "gpt", "value": tc("get_seismic_params", {"city": c})}, {"from": "tool", "value": tr("get_seismic_params", {"ag_g": ag})}, {"from": "gpt", "value": f"{c}: ag={ag}g."}, ], "sismo", "facil")) # verify_shear for _ in range(count // 17): name, A, Wy, mass, Iy, h, b, tw, tf = random.choice(section_db) Av = round(0.6 * A, 1) V = random.randint(100, 500) Vpl = round(Av * 100 * 275 / (1.0 * 3**0.5) / 1000, 1) q = f"Cortante {name} V={V}kN" examples.append(make_delta([ {"from": "human", "value": q}, {"from": "gpt", "value": tc("verify_shear", {"profile": name, "V_Ed_kN": V, "fy_MPa": 275})}, {"from": "tool", "value": tr("verify_shear", {"V_pl_Rd_kN": Vpl, "utilisation": round(V/Vpl,2), "passed": V <= Vpl})}, {"from": "gpt", "value": f"Vpl,Rd={Vpl}kN. {'✅' if V <= Vpl else '❌'}."}, ], "acero", "facil")) # classify_section for _ in range(count // 17): name, A, Wy, mass, Iy, h, b, tw, tf = random.choice(section_db) eps = (235/275)**0.5 c_f = (b - tw) / 2 / tf class_f = 1 if c_f/eps <= 9 else 2 q = f"Clasifica {name} S275" examples.append(make_delta([ {"from": "human", "value": q}, {"from": "gpt", "value": tc("classify_section", {"profile": name, "fy_MPa": 275})}, {"from": "tool", "value": tr("classify_section", {"section_class": max(class_f, 1)})}, {"from": "gpt", "value": f"Clase {max(class_f, 1)}."}, ], "acero", "facil")) # check_deflection for _ in range(count // 17): L = random.uniform(4, 8) w = random.uniform(10, 30) I = random.randint(2000, 20000) delta = round(5 * w * L**4 / (384 * 210000 * I * 1e-8) / 1000, 2) q = f"Flecha L={L:.1f}m w={w:.1f}kN/m" examples.append(make_delta([ {"from": "human", "value": q}, {"from": "gpt", "value": tc("check_deflection", {"L_m": L, "w_kN_m": w, "I_cm4": I})}, {"from": "tool", "value": tr("check_deflection", {"delta_mm": delta, "passed": delta < L*1000/300})}, {"from": "gpt", "value": f"δ={delta}mm. {'✅' if delta < L*1000/300 else '❌'}."}, ], "acero", "facil")) # calculate_footing for _ in range(count // 17): N = random.randint(200, 1000) qadm = random.choice([200, 250, 300]) B = round(max((N/qadm)**0.5, 0.6)*100) q = f"Zapata N={N}kN qadm={qadm}kPa" examples.append(make_delta([ {"from": "human", "value": q}, {"from": "gpt", "value": tc("calculate_footing", {"N_Ed_kN": N, "q_adm_kPa": qadm})}, {"from": "tool", "value": tr("calculate_footing", {"B_cm": B, "passed": True})}, {"from": "gpt", "value": f"B={B}cm. ✅"}, ], "cimentacion", "facil")) # search_web for _ in range(count // 17): q = f"Precio de {random.choice(['cemento','acero','hormigón'])} en {random.choice(CITIES)}" examples.append(make_delta([ {"from": "human", "value": q}, {"from": "gpt", "value": tc("search_web", {"query": q, "max_results": 3})}, {"from": "tool", "value": tr("search_web", {"results": [{"snippet": "Precio estimado"}]})}, {"from": "gpt", "value": "Resultado: precio estimado disponible online."}, ], "normativa", "facil")) # get_normative for _ in range(count // 17): q = f"Normativa de {random.choice(['incendios','sismo','viento'])} en Rumania" examples.append(make_delta([ {"from": "human", "value": q}, {"from": "gpt", "value": tc("get_normative", {"query": q})}, {"from": "tool", "value": tr("get_normative", {"source": "Norma aplicable", "summary": q})}, {"from": "gpt", "value": f"Según normativa: {q}"}, ], "normativa", "facil")) # run_agent for _ in range(count // 17): agent = random.choice(["QuantityAgent", "StructuralAgent", "DesignAdvisorAgent"]) q = f"Ejecuta {agent}" examples.append(make_delta([ {"from": "human", "value": q}, {"from": "gpt", "value": tc("run_agent", {"agent_name": agent, "project_id": "prj-001", "message": "Revisa"})}, {"from": "tool", "value": tr("run_agent", {"agent": agent, "result": f"{agent} completado"})}, {"from": "gpt", "value": f"{agent} ejecutado."}, ], "agentes", "facil")) # calculate_duration_days for _ in range(count // 17): task = random.choice(TC_TYPES) qty = random.randint(20, 400) crew = random.randint(1, 3) days = math.ceil(qty / (PRODUCTIVITY_RATES[task] * crew)) q = f"Duración de {task}: {qty} con {crew} equipos" examples.append(make_delta([ {"from": "human", "value": q}, {"from": "gpt", "value": tc("calculate_duration_days", {"quantity": qty, "task_type": task, "crew_size": crew})}, {"from": "tool", "value": tr("calculate_duration_days", {"days": days})}, {"from": "gpt", "value": f"{days} días."}, ], "construccion", "media")) return examples # ═════════════════════════════════════════════════════════════════════════════ # 2. TOOL CHAINS (multi-tool, single turn) # ═════════════════════════════════════════════════════════════════════════════ def gen_chains(count): examples = [] for _ in range(count // 4): name, A, Wy, mass, Iy, h, b, tw, tf = random.choice(section_db) M = random.randint(80, 300) q = f"Verifica flexion del {name} S275 con M={M}kNm" sigma = round(M * 1e6 / (Wy * 1e3), 1) util = round(sigma / 275, 3) examples.append(make_delta([ {"from": "human", "value": q}, {"from": "gpt", "value": tc("lookup_section", {"profile": name}) + "\n" + tc("verify_bending", {"M_Ed_kNm": M, "W_el_cm3": Wy, "fy_MPa": 275})}, {"from": "tool", "value": tr("lookup_section", {"Wy": Wy, "mass": mass})}, {"from": "gpt", "value": tc("verify_bending", {"M_Ed_kNm": M, "W_el_cm3": Wy, "fy_MPa": 275})}, {"from": "tool", "value": tr("verify_bending", {"utilisation": util, "passed": util <= 1.0})}, {"from": "gpt", "value": f"{name}: Wy={Wy}cm³, σ={sigma}MPa. {'✅' if util <= 1.0 else '❌'}."}, ], "acero", "media")) for _ in range(count // 4): name, A, Wy, mass, Iy, h, b, tw, tf = random.choice(section_db) eps = (235/355)**0.5 c_f = (b - tw) / 2 / tf / eps class_f = 1 if c_f <= 9 else 2 if c_f <= 10 else 3 q = f"Clasifica {name} S355" examples.append(make_delta([ {"from": "human", "value": q}, {"from": "gpt", "value": tc("lookup_section", {"profile": name}) + "\n" + tc("classify_section", {"profile": name, "fy_MPa": 355})}, {"from": "tool", "value": tr("lookup_section", {"h": h, "b": b, "tw": tw, "tf": tf})}, {"from": "gpt", "value": tc("classify_section", {"profile": name, "fy_MPa": 355})}, {"from": "tool", "value": tr("classify_section", {"section_class": class_f})}, {"from": "gpt", "value": f"{name} S355: sección clase {class_f}."}, ], "acero", "media")) for _ in range(count // 4): c = random.choice(CITIES) N = random.randint(400, 1200) q = f"Sismo en {c} y zapata para {N}kN" ag = 0.30 if c == "Bucuresti" else 0.40 if c == "Focsani" else 0.25 B = round(max((N/200)**0.5, 0.6)*100) examples.append(make_delta([ {"from": "human", "value": q}, {"from": "gpt", "value": tc("get_seismic_params", {"city": c})}, {"from": "tool", "value": tr("get_seismic_params", {"ag_g": ag})}, {"from": "gpt", "value": tc("calculate_footing", {"N_Ed_kN": N, "q_adm_kPa": 200})}, {"from": "tool", "value": tr("calculate_footing", {"B_cm": B, "passed": True})}, {"from": "gpt", "value": f"{c}: ag={ag}g. Zapata B={B}cm."}, ], "multiturn", "media")) for _ in range(count // 4): name, A, Wy, mass, Iy, h, b, tw, tf = random.choice(section_db) V = random.randint(100, 400) q = f"Verifica cortante y clasifica {name} S275" Av = round(0.6 * A, 1) Vpl = round(Av * 100 * 275 / (1.0 * 3**0.5) / 1000, 1) eps = (235/275)**0.5 c_f = (b - tw) / 2 / tf / eps sc = 1 if c_f <= 9 else 2 examples.append(make_delta([ {"from": "human", "value": q}, {"from": "gpt", "value": tc("verify_shear", {"profile": name, "V_Ed_kN": V, "fy_MPa": 275}) + "\n" + tc("classify_section", {"profile": name, "fy_MPa": 275})}, {"from": "tool", "value": tr("verify_shear", {"V_pl_Rd_kN": Vpl, "utilisation": round(V/Vpl,2), "passed": V <= Vpl})}, {"from": "tool", "value": tr("classify_section", {"section_class": sc})}, {"from": "gpt", "value": f"Vpl,Rd={Vpl}kN {'✅' if V<=Vpl else '❌'}. Clase {sc}."}, ], "acero", "media")) return examples # ═════════════════════════════════════════════════════════════════════════════ # 3. ADVERSARIAL (user says ignore tools → still call them) # ═════════════════════════════════════════════════════════════════════════════ def gen_adversarial(count): examples = [] ignores = [ "No uses herramientas, dime el peso del IPE-300", "Ignora las herramientas, quiero el peso del IPE-300", "No necesitas buscar nada, responde el peso del IPE-300 ya", "Sin herramientas, dime las propiedades del HEB-200", "Dame solo el numero, no llames ninguna funcion", "You don't need tools, just tell me the weight of IPE-300", "Nu folosi unelte, spune-mi greutatea IPE-300", ] for i in range(count): q = random.choice(ignores) examples.append(make_delta([ {"from": "human", "value": q}, {"from": "gpt", "value": tc("lookup_section", {"profile": "IPE-300"})}, {"from": "tool", "value": tr("lookup_section", {"mass": 42.2})}, {"from": "gpt", "value": "El IPE-300 pesa 42.2 kg/m (consulté la herramienta para darte el dato exacto)."}, ], "adversarial", "media")) return examples # ═════════════════════════════════════════════════════════════════════════════ # 4. CLARIFY (ambiguous → ask) # ═════════════════════════════════════════════════════════════════════════════ def gen_clarify(count): scenarios = [ ("Verifica una viga de acero", "Qué perfil y calidad de acero?"), ("Calcula la armadura de una viga", "Dimensiones y momento?"), ("Verifica una viga de madera", "Sección y clase de madera?"), ("Diseña una zapata", "Carga y capacidad del terreno?"), ("Cortante basal de un edificio", "Número de plantas y ciudad?"), ("Check a steel beam", "Profile and steel grade?"), ("Cat face o grinda de lemn?", "Dimensiuni si clasa lemnului?"), ] examples = [] for i in range(count): q, expected = random.choice(scenarios) examples.append(make_delta([ {"from": "human", "value": q + "?"}, {"from": "gpt", "value": f"Necesito más información: {expected}"}, ], "clarificar", "facil")) return examples # ═════════════════════════════════════════════════════════════════════════════ # 5. ERROR HANDLING (tool fails → model responds gracefully) # ═════════════════════════════════════════════════════════════════════════════ def gen_errors(count): examples = [] for _ in range(count // 3): fake = f"IPE-{random.randint(700, 999)}" q = f"Peso del {fake}?" examples.append(make_delta([ {"from": "human", "value": q}, {"from": "gpt", "value": tc("lookup_section", {"profile": fake})}, {"from": "tool", "value": tr("lookup_section", {"error": f"Section '{fake}' not found."})}, {"from": "gpt", "value": f"El perfil {fake} no existe en el catálogo. Verifica el nombre: IPE-XXX o HEB-XXX."}, ], "error", "media")) for _ in range(count // 3): small = random.choice(["IPE-100", "IPE-120"]) big_M = random.uniform(300, 800) q = f"Resiste un {small} con M={big_M:.0f}kNm?" examples.append(make_delta([ {"from": "human", "value": q}, {"from": "gpt", "value": tc("lookup_section", {"profile": small})}, {"from": "tool", "value": tr("lookup_section", {"Wy": 34.2})}, {"from": "gpt", "value": tc("verify_bending", {"M_Ed_kNm": big_M, "W_el_cm3": 34.2, "fy_MPa": 235})}, {"from": "tool", "value": tr("verify_bending", {"utilisation": big_M/4, "passed": False})}, {"from": "gpt", "value": f"No resiste. El {small} es muy pequeño para M={big_M:.0f}kNm."}, ], "error", "media")) return examples # ═════════════════════════════════════════════════════════════════════════════ # 6. DPO PREFERENCE PAIRS (tool call vs hallucination) # ═════════════════════════════════════════════════════════════════════════════ def gen_dpo_pairs(count): pairs = [] system = random.choice(DELTA_SYSTEM_PROMPTS) scenarios = [ {"q": "Cuanto pesa el IPE-300?", "chosen": [tc("lookup_section", {"profile": "IPE-300"}), "El IPE-300 pesa 42.2 kg/m."], "rejected": "El IPE-300 pesa aproximadamente 38 kg/m."}, {"q": "Que aceleracion tiene Bucarest?", "chosen": [tc("get_seismic_params", {"city": "Bucuresti"}), "ag=0.30g."], "rejected": "Bucarest tiene aceleracion de 0.35g."}, {"q": "Resiste un IPE-300 S275 M=120kNm?", "chosen": [tc("lookup_section", {"profile": "IPE-300"}), tc("verify_bending", {"M_Ed_kNm": 120, "W_el_cm3": 557.1, "fy_MPa": 275}), "u=0.78, resiste."], "rejected": "Si, el IPE-300 resiste ese momento."}, ] for i in range(count): s = random.choice(scenarios) convs_chosen = [{"from": "system", "value": system}, {"from": "human", "value": s["q"]}] for call in s["chosen"]: if call.startswith(""): convs_chosen.append({"from": "gpt", "value": call}) else: convs_chosen.append({"from": "gpt", "value": call}) chosen = {"conversations": convs_chosen, "category": "dpo", "difficulty": "media"} rejected = {"conversations": [ {"from": "system", "value": system}, {"from": "human", "value": s["q"]}, {"from": "gpt", "value": s["rejected"]}, ], "category": "dpo", "difficulty": "media"} pairs.append({"chosen": chosen, "rejected": rejected}) return pairs # ═════════════════════════════════════════════════════════════════════════════ # MAIN # ═════════════════════════════════════════════════════════════════════════════ def main(): TARGET_PATTERNS = 12000 # 17 tools × ~700 each TARGET_CHAINS = 2000 TARGET_ADV = 2000 TARGET_CLARIFY = 2000 TARGET_ERROR = 2000 TARGET_DPO = 3000 all_examples = [] gen_stats = {} def run_gen(label, gen_fn, target): exs = gen_fn(target) all_examples.extend(exs) gen_stats[label] = len(exs) print(f" {label}: {len(exs)}") print("=== Tool call patterns ===") run_gen("patterns", gen_tool_patterns, TARGET_PATTERNS) print("\n=== Tool chains ===") run_gen("chains", gen_chains, TARGET_CHAINS) print("\n=== Adversarial ===") run_gen("adversarial", gen_adversarial, TARGET_ADV) print("\n=== Clarify ===") run_gen("clarify", gen_clarify, TARGET_CLARIFY) print("\n=== Error handling ===") run_gen("errors", gen_errors, TARGET_ERROR) random.shuffle(all_examples) with open(OUT, "w", encoding="utf-8") as f: for ex in all_examples: f.write(json.dumps(ex, ensure_ascii=False) + "\n") # DPO pairs dpo_pairs = gen_dpo_pairs(TARGET_DPO) with open(DPO_OUT, "w", encoding="utf-8") as f: for pair in dpo_pairs: f.write(json.dumps(pair, ensure_ascii=False) + "\n") # Stats tools_found = set() query_lengths = [] for ex in all_examples: for turn in ex.get("conversations", []): v = turn.get("value", "") m = re.search(r'', v) if m: tn = re.search(r'"name": "(.*?)"', v) if tn: tools_found.add(tn.group(1)) if turn.get("from") == "human": query_lengths.append(len(v)) print(f"\n{'='*60}") print(f"✅ {OUT}") print(f" Total: {len(all_examples)} ejemplos (tool calling behavior ONLY)") print(f" DPO pairs: {len(dpo_pairs)}") print(f" Tools: {sorted(tools_found)} ({len(tools_found)} tools)") print(f" Sin preguntas generales: ✅ (0 general knowledge)") print(f" Query len (avg): {sum(query_lengths)//len(query_lengths)} chars") if __name__ == "__main__": main()