Repository navigation
Expand file tree
/
Copy path09_fastapi_service.py
More file actions
139 lines (111 loc) · 4.24 KB
/
Copy path09_fastapi_service.py
File metadata and controls
139 lines (111 loc) · 4.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
"""
================================================================
EXAMPLE 09 — "Lynx behind FastAPI" (ADVANCED)
================================================================
SCENARIO:
Wrap run_agent() in a FastAPI endpoint. One ToolSet + PolicyBundle
built at startup (immutable); each request creates a fresh agent and
streams events to a per-request jsonl sink.
REQUIRES:
pip install fastapi uvicorn
RUN WITH:
uvicorn examples.09_fastapi_service:app --reload
curl -X POST localhost:8000/agent/run \\
-H 'content-type: application/json' \\
-d '{"customer_id": "C-123", "amount_usd": 5, "reason": "1-day outage"}'
"""
from __future__ import annotations
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Any
try:
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from pydantic import BaseModel
except ImportError as exc:
raise SystemExit(
"This example requires fastapi + uvicorn: pip install fastapi uvicorn"
) from exc
from lynx import (
FinalAnswer,
Message,
ToolCall,
ToolSet,
auto_approve,
callback_sink,
load_policy_file,
run_agent,
tool,
)
@tool(reversible=True, scope=("customer:read",))
async def get_customer(customer_id: str) -> dict:
return {"id": customer_id, "name": "Alice"}
@tool(reversible=False, scope=("customer:write",))
async def refund_customer(customer_id: str, amount_usd: float, reason: str) -> dict:
return {"refunded": amount_usd, "to": customer_id, "reason": reason}
@refund_customer.shadow
async def _refund_shadow(customer_id: str, amount_usd: float, reason: str) -> dict:
return {"would_refund": amount_usd}
class ScriptedRefund:
def __init__(self, customer_id: str, amount_usd: float, reason: str):
self._i = 0
self._plan = [
ToolCall("get_customer", {"customer_id": customer_id}, call_id="c1"),
ToolCall(
"refund_customer",
{"customer_id": customer_id, "amount_usd": amount_usd, "reason": reason},
call_id="c2",
),
FinalAnswer(text=f"Refund processed for {customer_id}."),
]
async def step(self, conv: tuple[Message, ...]):
a = self._plan[self._i]
self._i += 1
return a
@asynccontextmanager
async def lifespan(app: FastAPI):
# Build the immutable tools + policy once at startup
policy_path = Path(__file__).resolve().parent / "policies" / "refund.yaml"
app.state.tools = ToolSet.from_functions(get_customer, refund_customer)
app.state.policy = load_policy_file(policy_path)
yield
app = FastAPI(lifespan=lifespan, title="Lynx FastAPI demo")
class RunRequest(BaseModel):
customer_id: str
amount_usd: float
reason: str
@app.post("/agent/run")
async def run_endpoint(req: RunRequest) -> Any:
# Per-request: collect events. We inspect them so the HTTP response can
# reflect a policy denial — without this, the agent's FinalAnswer would
# be returned with a 200 even when the side-effecting tool was blocked.
denials: list[dict[str, Any]] = []
events_seen: list[dict[str, Any]] = []
async def collect(ev):
events_seen.append({"kind": ev.kind, "seq": ev.seq})
if ev.kind == "action.denied":
denials.append({"seq": ev.seq, "reason": ev.body.get("reason", "")})
result = await run_agent(
ScriptedRefund(req.customer_id, req.amount_usd, req.reason),
task=f"Refund {req.customer_id}",
tools=app.state.tools,
policy=app.state.policy,
sinks=(callback_sink(collect),),
on_approval=auto_approve(approver="api"),
)
body = {
"correlation_id": result.correlation_id,
"final_answer": result.final_answer,
"error": result.error,
"steps_taken": result.steps_taken,
"events_count": len(events_seen),
"denials": denials,
}
if denials:
# Policy blocked at least one action. Return 403 + the denial reasons
# so callers see the failure rather than a misleading 200.
return JSONResponse(status_code=403, content=body)
return body
@app.get("/")
async def root():
return {"service": "Lynx FastAPI demo", "tools": list(app.state.tools.names())}