|
| 1 | +--- |
| 2 | +title: AI Agent Guide |
| 3 | +summary: The complete authoring grammar for Python polyglot functions on one page - |
| 4 | + contract, registration, config keys, endpoints and error rules, for deterministic generation. |
| 5 | +audience: [ai-agent] |
| 6 | +keywords: [ai agent, grammar, contract, deterministic, preload, postoffice] |
| 7 | +--- |
| 8 | + |
| 9 | +# AI Agent Guide |
| 10 | + |
| 11 | +**Purpose: generate a correct Python polyglot function from this page alone.** |
| 12 | +Humans: the narrative versions live in [Function Writing Patterns](function-patterns.md) |
| 13 | +and the [join chapters](join-event-script.md). Orchestration (flows, graphs) is |
| 14 | +authored on the engine — use the |
| 15 | +[engine AI guides](https://accenture.github.io/mercury-composable/guides/ai-developer-guide/). |
| 16 | + |
| 17 | +## Pre-write checklist |
| 18 | + |
| 19 | +1. Route name: lowercase `[a-z0-9._-]`, at least one period. Example: `order.enrich`. |
| 20 | +2. Handler style: wraps blocking library (`requests`, NumPy, DB driver) → plain `def`; |
| 21 | + asyncio I/O or calls sibling functions → `async def`. |
| 22 | +3. Function is stateless. State belongs to the calling flow/graph. |
| 23 | +4. Orchestration-shaped logic (sequencing, retries, branching) → STOP; author an |
| 24 | + Event Script flow or MiniGraph graph on the engine instead. |
| 25 | + |
| 26 | +## The contract |
| 27 | + |
| 28 | +```python |
| 29 | +from mercury_composable import AppException, Body, PostOffice, annotate_trace, \ |
| 30 | + get_logger, get_trace, platform, preload |
| 31 | + |
| 32 | +log = get_logger(__name__) |
| 33 | + |
| 34 | +@preload(route="order.enrich", instances=10) # private=True -> in-app only |
| 35 | +def handler(headers: dict[str, str], body: Body): # or: async def |
| 36 | + # 1. validate; intentional errors = AppException(status, message) |
| 37 | + if not isinstance(body, dict) or not isinstance(body.get("id"), str): |
| 38 | + raise AppException(400, "missing 'id'") |
| 39 | + # 2. work (blocking is safe in plain def - executor thread) |
| 40 | + # 3. optional telemetry |
| 41 | + annotate_trace("source", "python") # rides back on the reply |
| 42 | + # 4. return the reply body (or an EventEnvelope for status/header control) |
| 43 | + return {"id": body["id"], "enriched": True} |
| 44 | + |
| 45 | +if __name__ == "__main__": |
| 46 | + platform.run() |
| 47 | +``` |
| 48 | + |
| 49 | +Rules: |
| 50 | + |
| 51 | +- `headers: dict[str, str]`; `body: Body` = `None|bool|int|float|str|bytes|list|dict`. |
| 52 | +- Return value = reply body. Return `EventEnvelope` only when setting status/headers. |
| 53 | +- `raise AppException(status, message)` → envelope status + message (portable error). |
| 54 | + Unexpected exception → 500 + message + stack. Never return HTTP-shaped dicts. |
| 55 | +- `get_trace()` → `TraceInfo(trace_id, trace_path, cid)` or `None`. |
| 56 | +- Reserved inbound header `my_correlation_id` = the caller's business correlation id |
| 57 | + (read-only). Never send headers named `my_*` or `x-event-api`. |
| 58 | + |
| 59 | +## Composition (calling other functions) |
| 60 | + |
| 61 | +```python |
| 62 | +# async handler: |
| 63 | +reply = await PostOffice().request("other.route", body={...}, timeout_ms=5000) |
| 64 | +# plain-def handler (sync bridge; blocks only this worker thread): |
| 65 | +reply = PostOffice().request_sync("other.route", body={...}, timeout_ms=5000) |
| 66 | +# drop-n-forget twins: send / send_sync -> 202 ack envelope |
| 67 | +# remote peer or engine: |
| 68 | +async with PostOffice(endpoint="http://host:8085/api/event") as po: ... |
| 69 | +``` |
| 70 | + |
| 71 | +- `request_sync` on the event loop → RuntimeError (use `await request()`). |
| 72 | +- `request_sync` outside a hosted function → RuntimeError (use `asyncio.run(...)`). |
| 73 | +- Always check `reply.get_status()`; errors are envelopes, not exceptions. |
| 74 | +- Local calls reach `private=True` routes; the wire cannot (403). |
| 75 | + |
| 76 | +## Run + configure |
| 77 | + |
| 78 | +```bash |
| 79 | +mercury-serve app.py # config: resources/application.yml |
| 80 | +mercury-serve app.py -Dkey=value # runtime override (engine syntax) |
| 81 | +``` |
| 82 | + |
| 83 | +Well-known keys (full table: [Configuration Reference](configuration-reference.md)): |
| 84 | +`application.name`, `rest.server.port` (default 8085), `log.format` |
| 85 | +(text|json|compact), `log.level`, `info.app.version`, `info.app.description`, |
| 86 | +`show.env.variables`, `show.application.properties`, |
| 87 | +`mandatory.health.dependencies`, `optional.health.dependencies`. |
| 88 | + |
| 89 | +## Health check function (engine interface contract) |
| 90 | + |
| 91 | +```python |
| 92 | +@preload(route="my.health", instances=5, private=True) |
| 93 | +async def health(headers: dict[str, str], _body: Body): |
| 94 | + if headers.get("type") == "info": |
| 95 | + return {"service": "my.dependency", "href": "http://backend"} |
| 96 | + return "my.dependency is running fine" # non-200 reply marks it DOWN |
| 97 | +``` |
| 98 | + |
| 99 | +List the route in `mandatory.health.dependencies` (or `optional.…`). |
| 100 | + |
| 101 | +## HTTP surface (served by the host, no code needed) |
| 102 | + |
| 103 | +`POST /api/event` (envelope wire) · `GET /` `/info` `/info/routes` `/env` `/health` |
| 104 | +`/livenessprobe`. Shapes: [HTTP Surface Reference](http-surface-reference.md). |
| 105 | + |
| 106 | +## Engine-side wiring (for completeness; authored on the engine) |
| 107 | + |
| 108 | +```yaml |
| 109 | +# application.properties: yaml.event.over.http=classpath:/event-over-http.yaml |
| 110 | +event.http: |
| 111 | + - route: 'order.enrich' |
| 112 | + target: 'http://python-host:8086/api/event' |
| 113 | +``` |
| 114 | +
|
| 115 | +Flow task `process: 'order.enrich'` or graph node |
| 116 | +`{"skill": "graph.task", "task": "order.enrich", ...}` (engines ≥ v4.11.11 for |
| 117 | +graph.task). Details: [Join an Event Script Flow](join-event-script.md) · |
| 118 | +[Join a Knowledge Graph](join-knowledge-graph.md). |
| 119 | + |
| 120 | +## DO / DON'T |
| 121 | + |
| 122 | +| DO | DON'T | |
| 123 | +|----|-------| |
| 124 | +| plain `def` for blocking libraries | block inside `async def` | |
| 125 | +| `AppException` for intentional errors | return `{"status": 400, ...}` dicts | |
| 126 | +| keep functions stateless | cache business state in module globals | |
| 127 | +| compose one or two leaf helpers | re-implement flows/retries in Python | |
| 128 | +| let deadlines fail fast (408 envelope) | swallow timeouts and hoard work | |
0 commit comments