Files
cp1-agents/docs/source-material/agent-shapes/subagent-pattern/app/tools.py
Jonathan Boniface 416c66ced4
All checks were successful
check agents / check (push) Successful in 10s
Add CP1 Discovery agents in both patterns
ALZ-F01 Discovery as a sub-agent orchestrator (sub-agents/) and as eight
individual declarative agents (individual-agents/), with their KAB workflow
exports. Shared check, render and import scripts, the alz-discovery-sample
MCP server, the crucible-kab-dev deploy profile, deployment docs, platform
issue reports and the source material. Agent steps time out at 20 minutes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 18:25:57 +00:00

147 lines
5.8 KiB
Python

"""The agent's own tools: plain functions the model may call.
A tool no skill names -- get_policy_rule here -- is offered on every request,
with or without a skill. A skill can name tools in its SKILL.md (`agent.tools`
in its metadata) to keep them until it is loaded, as both skills do with the
other three. The framework builds each tool's description from its signature
and docstring, so both are part of what the model reads.
Results are small and bounded on purpose: a tool that returned the whole policy
for every call would fill the context and teach the model to stop looking.
"""
from __future__ import annotations
from functools import lru_cache
from pathlib import Path
from typing import Any, Dict, List
import yaml
_POLICY_FILE = Path(__file__).resolve().parent / "policy.yaml"
@lru_cache(maxsize=1)
def _policy() -> Dict[str, Any]:
return yaml.safe_load(_POLICY_FILE.read_text(encoding="utf-8"))
def _public(rule: Dict[str, Any]) -> Dict[str, Any]:
return {k: v for k, v in rule.items() if k != "category" or v != "all"}
def lookup_policy_rule(category: str) -> dict:
"""The policy rules that apply to one expense category.
Always includes the rules that apply to every claim (such as the receipt
rule). Use the rule ids and texts exactly as returned.
Args:
category: one of travel, meals, lodging, software, other.
Returns:
{"category": ..., "rules": [{"id", "text", "limit_eur"?, "receipt_over_eur"?,
"approval_over_eur"?}]}, or {"error": ...} for an unknown category.
"""
rules = _policy()["rules"]
categories = sorted({r["category"] for r in rules if r["category"] != "all"})
category = (category or "").strip().lower()
if category not in categories:
return {"error": f"unknown category {category!r}; one of {categories}"}
return {
"category": category,
"rules": [_public(r) for r in rules if r["category"] in (category, "all")],
}
def _convert(amount: float, source: str, target: str) -> dict:
rates = _policy()["rates_to_eur"]
source, target = (source or "").upper(), (target or "").upper()
for code in (source, target):
if code not in rates:
return {"error": f"unknown currency {code!r}; one of {sorted(rates)}"}
rate = rates[source] / rates[target]
return {"amount": round(float(amount) * rate, 2), "rate": round(rate, 6),
"from": source, "to": target}
def convert_currency(amount: float, from_currency: str, to_currency: str) -> dict:
"""Convert an amount between USD, EUR, GBP and INR using the company's fixed rates.
Only needed when the claim is not already in the currency you want.
Args:
amount: the amount to convert.
from_currency: ISO code of the amount, e.g. "USD".
to_currency: ISO code wanted, e.g. "EUR".
Returns:
{"amount": converted, rounded to 2 decimals, "rate": ..., "from": ..., "to": ...},
or {"error": ...} for an unknown currency.
"""
return _convert(amount, from_currency, to_currency)
def request_approval(amount: float, currency: str, policy_flags: List[str]) -> dict:
"""Who must sign this claim, from the company's delegation of authority.
Call it for every claim you have not rejected. It converts the amount to
USD itself -- the delegation of authority is set in USD -- so pass the
claim's own amount and currency. The answer is final: report it, do not
change it.
Args:
amount: the claim's amount, in its own currency.
currency: the claim's currency, e.g. "EUR".
policy_flags: rules that ask for approval, e.g. ["needs_approval:SOFTWARE-1"];
[] if none. A flag means at least a manager signs.
Returns:
{"decision": approve|escalate|reject, "approver_level": auto|manager|director|none,
"why": a plain explanation of who signs and why}, or {"error": ...}.
"""
usd = _convert(amount, currency, "USD")
if "error" in usd:
return usd
amount_usd = usd["amount"]
flags = list(policy_flags or [])
bands = _policy()["delegation_of_authority"]
index = next(i for i, b in enumerate(bands) if amount_usd < b["under_usd"])
band, lower = bands[index], (bands[index - 1]["under_usd"] if index else 0)
level = band["level"]
if flags and level == "auto":
level = "manager"
decision = {"auto": "approve", "none": "reject"}.get(level, "escalate")
size = (f"over {lower:,.0f} USD" if band["under_usd"] == float("inf")
else f"under {band['under_usd']:,.0f} USD" if not lower
else f"between {lower:,.0f} and {band['under_usd']:,.0f} USD")
who = {"auto": "no approver is needed", "manager": "a manager must sign",
"director": "a director must sign", "none": "it cannot be approved"}[level]
because = f"the policy asks for approval ({', '.join(f.split(':')[-1] for f in flags)})" if flags else "no rule asks for approval"
return {"decision": decision, "approver_level": level,
"why": f"The claim is {size} and {because}, so {who}."}
def get_policy_rule(rule_id: str) -> dict:
"""The exact text of one policy rule, by its id.
Use it to quote the rule a decision rests on, word for word.
Args:
rule_id: the rule's id, e.g. MEALS-1 or RECEIPT-1.
Returns:
{"id": ..., "text": ...}, or {"error": ...} for an unknown id.
"""
wanted = (rule_id or "").strip().upper()
for rule in _policy()["rules"]:
if rule["id"] == wanted:
return {"id": rule["id"], "text": rule["text"]}
return {"error": f"unknown rule {rule_id!r}; ids: {[r['id'] for r in _policy()['rules']]}"}
# agent.yaml lists each of these under `functions:`. TOOLS is for the LangGraph
# template, whose graph in app/agent.py binds its tools from this list.
TOOLS = [lookup_policy_rule, convert_currency, request_approval, get_policy_rule]