"""Lordevo tools for the OpenAI Agents SDK (openai-agents, Python). One FunctionTool per Lordevo tool, built from the lordevo-x402 tool table, paid per call with x402 (USDC on Base), free trial first when the client was made with trial=True: from agents import Agent from lordevo_x402 import LordevoSync from lordevo_agents import lordevo_function_tools agent = Agent(name="Web analyst", tools=lordevo_function_tools(LordevoSync.from_private_key(key, trial=True))) """ from __future__ import annotations import asyncio import json from typing import Any from agents import FunctionTool from lordevo_x402 import TOOLS, LordevoError, price_label # The 5 tools this drop-in exposes by default (all $0.003 per call). Pass your own list to change it. DEFAULT_TOOLS = ["page-markdown", "can-fetch", "tech-stack", "dns-lookup", "email-validate"] def strict_schema(t: dict) -> dict: """The SDK's strict mode wants every property required: optional inputs are nullable (null = not given).""" props: dict[str, Any] = {t["param"]: {"type": "string", "description": t.get("param_description", t["param"])}} optional = list((t.get("alt") or {}).items()) + [(k, o.get("description", k)) for k, o in (t.get("options") or {}).items() if not o.get("required")] for k, o in (t.get("options") or {}).items(): if o.get("required"): props[k] = {"type": "string", "description": o.get("description", k)} for k, d in optional: o = (t.get("options") or {}).get(k) or {} props[k] = {"type": ["string", "null"], "description": d, **({"enum": [*o["enum"], None]} if "enum" in o else {})} if t.get("alt"): props[t["param"]]["type"] = ["string", "null"] return {"type": "object", "properties": props, "required": list(props), "additionalProperties": False} def error_json(e: Exception) -> str: """Errors reach the model as JSON it can read (error, message, charged), instead of an exception.""" if isinstance(e, LordevoError): out = {"error": e.code or f"http_{e.status}", "message": str(e), "charged": bool(e.charged)} if e.trial: out["free_trial"] = e.trial return json.dumps(out) return json.dumps({"error": "client_error", "message": str(e), "charged": False}) def lordevo_function_tools(client: Any, only: list[str] | None = None) -> list[FunctionTool]: """client: a LordevoSync (from lordevo_x402). only: tool slugs (default DEFAULT_TOOLS).""" def make(slug: str, t: dict) -> FunctionTool: async def invoke(ctx: Any, args_json: str) -> str: try: args = {k: v for k, v in json.loads(args_json or "{}").items() if v is not None} return json.dumps(await asyncio.to_thread(client.call, slug, **args)) except Exception as e: # noqa: BLE001 - the model gets every error as JSON return error_json(e) return FunctionTool(name=t["mcp_tool"], description=f"{t['title']}. Costs {price_label(t['price_usd'])} per call (x402, USDC on Base); failed calls are not charged.", params_json_schema=strict_schema(t), on_invoke_tool=invoke, strict_json_schema=True) return [make(s, TOOLS[s]) for s in (only or DEFAULT_TOOLS)]