Add CP1 Discovery agents in both patterns
All checks were successful
check agents / check (push) Successful in 10s
All checks were successful
check agents / check (push) Successful in 10s
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>
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""The agent's own code: hooks (business_logic.py) and tools (tools.py)."""
|
||||
@@ -0,0 +1,193 @@
|
||||
"""Where your business logic goes.
|
||||
|
||||
All four functions below are wired up already and do nothing yet. Fill in the
|
||||
one you need — the wiring is already correct, so you only edit this file.
|
||||
|
||||
request ─▶ pre_process(payload) ONCE per request, on the parsed JSON
|
||||
│
|
||||
▼
|
||||
before_model() once per MODEL CALL
|
||||
│
|
||||
▼
|
||||
the model ◀── tools ──┐
|
||||
│ │
|
||||
▼ │
|
||||
after_model() ────────┘ once per model call
|
||||
│
|
||||
▼
|
||||
post_process(result) ONCE per request, on the final JSON
|
||||
│
|
||||
▼
|
||||
response
|
||||
|
||||
Which pair you want comes down to one question: does the work belong to the
|
||||
*request*, or to each *model turn*?
|
||||
|
||||
`pre_process` and `post_process` belong to the request. They receive a parsed
|
||||
dict — the shape your input and output schemas describe — and run exactly once,
|
||||
however many times the model is called in between. Normalising an identifier,
|
||||
enriching from a lookup, stamping a field onto the result: all request work.
|
||||
|
||||
`before_model` and `after_model` belong to the turn. They receive the
|
||||
runtime's ModelCall -- the same on every framework -- and run on every model
|
||||
call, which in a tool loop is several times.
|
||||
|
||||
Putting request work in the per-call pair is the usual bug. A lookup in
|
||||
`before_model` runs four times in a four-step tool loop, and you pay for it
|
||||
four times; the same lookup in `pre_process` runs once.
|
||||
|
||||
Use these when the work is *deterministic* — something that should happen on
|
||||
every request, whether or not the model decides it is a good idea. Reading a
|
||||
config file, redacting an identifier, enforcing a house style, validating the
|
||||
shape of a reply.
|
||||
|
||||
Use a **tool** instead (`functions:` in agent.yaml) when the model should decide
|
||||
whether and when to do the thing, and can use the result to choose what to do
|
||||
next. Tools are what create the agent loop; these hooks do not.
|
||||
|
||||
Two things worth knowing before you start:
|
||||
|
||||
* The loop bounds in kubernetes/configmap.yaml are enforced by the runtime
|
||||
alongside these hooks. Nothing you return here switches them off.
|
||||
|
||||
* Anything you read at runtime must be COPYed in the Dockerfile. It works
|
||||
locally without that, because ./run-local.sh bind-mounts the project into
|
||||
the container — but there is no such mount in Kubernetes, and the file will
|
||||
simply not be there. This is the most common way an agent passes locally
|
||||
and fails on deploy.
|
||||
|
||||
You do not set up logging, tracing or correlation headers here. The runtime has
|
||||
already wrapped those around this agent.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
import structlog
|
||||
|
||||
from kyndryl_agent_runtime import agent_manifest
|
||||
|
||||
# The agent's logger. Use this one.
|
||||
#
|
||||
# Every agent on the platform logs through structlog, so every agent's output
|
||||
# is parsed the same way, searchable by the same fields, and shipped by the
|
||||
# same pipeline. An agent that reaches for `print()` or its own `logging`
|
||||
# config is the one nobody can query when it misbehaves at 2am.
|
||||
#
|
||||
# Bound with the agent's name so a line is attributable once the logs of forty
|
||||
# agents are in one place. Add your own permanent context the same way:
|
||||
#
|
||||
# logger = logger.bind(region=os.getenv("REGION", "unknown"))
|
||||
#
|
||||
# House style, and it is worth following:
|
||||
#
|
||||
# * an event name, then key=value -- `logger.info("rate_applied",
|
||||
# currency="EUR", rate=1.09)`, not a sentence with the values glued in.
|
||||
# The first is searchable; the second is prose that happens to contain
|
||||
# numbers.
|
||||
# * INFO for what happened, DEBUG for the data it happened to. A claim, a
|
||||
# ticket, a patient note -- these belong at DEBUG, because a log that is
|
||||
# unsafe to keep is a log somebody turns off, taking everything else with
|
||||
# it.
|
||||
# * never a secret, a token or a full payment detail, at any level. There is
|
||||
# no log level that makes an API key safe to store.
|
||||
# * no need to log that a request arrived, that pre_process ran, or what the
|
||||
# model replied -- the runtime already does all of that around you. Log
|
||||
# what is yours: the decision you made and why.
|
||||
logger = structlog.get_logger(__name__).bind(
|
||||
agent=agent_manifest().name or "agent",
|
||||
)
|
||||
|
||||
|
||||
def before_model(call: Any) -> None:
|
||||
"""Runs immediately before each call to the model, on any framework.
|
||||
|
||||
`call` is the runtime's ModelCall, the same object on Google ADK, LangChain,
|
||||
LangGraph, Strands and Microsoft Agent Framework, so this file runs
|
||||
unchanged on all of them. Add to the system instructions for this one call:
|
||||
|
||||
call.add_instruction("The customer's region is EMEA.")
|
||||
|
||||
Prefer the system instructions over the user's message: anything placed
|
||||
inside a user turn is markedly easier for a crafted prompt to talk the
|
||||
model out of. `call.native` holds the framework's own arguments, for what
|
||||
add_instruction does not cover. The return value is ignored.
|
||||
|
||||
Called once per model call, so this runs several times in a tool loop, not
|
||||
once per request. Keep it cheap; cache anything you read from disk.
|
||||
"""
|
||||
return None
|
||||
|
||||
|
||||
def after_model(call: Any) -> None:
|
||||
"""Runs immediately after each reply from the model, on any framework.
|
||||
|
||||
`call.reply_text` is the reply's text -- empty for a reply that only calls
|
||||
a tool or loads a skill. Good uses: record a domain metric, check the
|
||||
shape of a structured reply. The return value is ignored; to change the
|
||||
final answer use post_process, which runs once on it.
|
||||
"""
|
||||
return None
|
||||
|
||||
|
||||
def pre_process(payload: dict) -> Optional[dict]:
|
||||
"""Runs once per request, on the incoming payload, before any model call.
|
||||
|
||||
`payload` is the request parsed as JSON. When this agent declares an input
|
||||
schema it has already been validated against it, so you can read the fields
|
||||
you declared without defensive checks — a payload that did not match never
|
||||
reaches here; the caller received a structured error naming the JSON path
|
||||
that was wrong.
|
||||
|
||||
Return a modified dict to change what the model is asked, or None to leave
|
||||
the payload alone. Returning a dict that is equal to what you were given is
|
||||
the same as returning None.
|
||||
|
||||
def pre_process(payload):
|
||||
payload["account_id"] = payload["account_id"].strip().upper()
|
||||
return payload
|
||||
|
||||
An agent with no input schema, or one called with prose rather than JSON,
|
||||
does not call this at all — there is no payload to hand you.
|
||||
|
||||
Raising here fails the request. That is the right move for something you
|
||||
genuinely cannot proceed without; prefer returning a corrected payload for
|
||||
anything you can repair.
|
||||
"""
|
||||
# An example of the house style, left here on purpose: delete it or keep it,
|
||||
# but log like it. An event name and fields, at a level that matches what
|
||||
# the line carries.
|
||||
#
|
||||
# logger.info("claim_received", category=payload.get("category"))
|
||||
# logger.debug("claim_payload", payload=payload)
|
||||
#
|
||||
# The first is safe anywhere and answers "what kind of work is this agent
|
||||
# doing?". The second answers "what exactly did it get?" and is DEBUG
|
||||
# because it is the caller's data.
|
||||
logger.debug("pre_process_input", fields=sorted(payload))
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def post_process(result: dict) -> Optional[dict]:
|
||||
"""Runs once per request, on the final reply, after the model is done.
|
||||
|
||||
`result` is the model's reply parsed as JSON. Return a modified dict to
|
||||
change what the caller receives, or None to leave it as it is.
|
||||
|
||||
def post_process(result):
|
||||
result["reviewed_at"] = datetime.now(timezone.utc).isoformat()
|
||||
return result
|
||||
|
||||
Two things to know. First, the output contract is checked *after* this
|
||||
runs, on what you return -- so the caller never receives a reply that
|
||||
breaks it. A dict that does not conform sends the model round once more,
|
||||
and if it still fails the caller gets an `output_contract_violation`. The
|
||||
runtime logs `post_process_broke_output_contract` with the offending paths
|
||||
when it was your edit that broke it, which is the fastest way to find it.
|
||||
|
||||
Second, a reply that is not JSON never reaches here. If your agent answers
|
||||
in prose, this hook simply does not run.
|
||||
"""
|
||||
return None
|
||||
@@ -0,0 +1,48 @@
|
||||
# The travel and expense policy, as data. The skills look rules up here through
|
||||
# tools rather than recalling them from the prompt, so a policy change is an
|
||||
# edit to this file, not to any instructions.
|
||||
#
|
||||
# Amounts are in EUR. `limit_eur` caps a claim; `receipt_over_eur` requires a
|
||||
# receipt above that amount; `approval_over_eur` means the claim needs approval.
|
||||
# WHO approves is never in a rule: every claim that is not rejected goes through
|
||||
# the delegation of authority below (request_approval), by its amount in USD.
|
||||
rules:
|
||||
- id: MEALS-1
|
||||
category: meals
|
||||
text: "Meals: up to 40 EUR per claim."
|
||||
limit_eur: 40
|
||||
- id: LODGING-1
|
||||
category: lodging
|
||||
text: "Lodging: up to 200 EUR per night."
|
||||
limit_eur: 200
|
||||
- id: TRAVEL-1
|
||||
category: travel
|
||||
text: "Travel is reimbursed at cost; there is no per-claim cap. Who signs follows the delegation of authority."
|
||||
- id: SOFTWARE-1
|
||||
category: software
|
||||
text: "Software is allowed; a purchase over 500 EUR needs approval. Who signs follows the delegation of authority."
|
||||
approval_over_eur: 500
|
||||
- id: OTHER-1
|
||||
category: other
|
||||
text: "Any other expense needs approval, whatever the amount. Who signs follows the delegation of authority."
|
||||
approval_over_eur: 0
|
||||
- id: RECEIPT-1
|
||||
category: all
|
||||
text: "Any claim over 25 EUR needs a receipt."
|
||||
receipt_over_eur: 25
|
||||
|
||||
# Fixed conversion rates to EUR, for the demonstration. A real agent would call
|
||||
# a rates service here; the skills would not change.
|
||||
rates_to_eur:
|
||||
EUR: 1.0
|
||||
USD: 0.92
|
||||
GBP: 1.17
|
||||
INR: 0.011
|
||||
|
||||
# Who must sign a claim, by its amount in USD: the first band the amount is
|
||||
# under. A claim a rule asks approval for always needs at least a manager.
|
||||
delegation_of_authority:
|
||||
- {under_usd: 500, level: auto}
|
||||
- {under_usd: 5000, level: manager}
|
||||
- {under_usd: 25000, level: director}
|
||||
- {under_usd: .inf, level: none}
|
||||
146
docs/source-material/agent-shapes/agent-pattern/app/tools.py
Normal file
146
docs/source-material/agent-shapes/agent-pattern/app/tools.py
Normal file
@@ -0,0 +1,146 @@
|
||||
"""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]
|
||||
Reference in New Issue
Block a user