agent-launchpad 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agent_launchpad/__init__.py +8 -0
- agent_launchpad/__main__.py +5 -0
- agent_launchpad/_template/example/.agent-launchpad.toml +3 -0
- agent_launchpad/_template/example/.claude/skills/eval-draft/SKILL.md +13 -0
- agent_launchpad/_template/example/.env.example +63 -0
- agent_launchpad/_template/example/.python-version +1 -0
- agent_launchpad/_template/example/Dockerfile +21 -0
- agent_launchpad/_template/example/README.md +110 -0
- agent_launchpad/_template/example/app/__init__.py +1 -0
- agent_launchpad/_template/example/app/agent.py +367 -0
- agent_launchpad/_template/example/app/approvals.py +188 -0
- agent_launchpad/_template/example/app/db.py +85 -0
- agent_launchpad/_template/example/app/decisions.py +231 -0
- agent_launchpad/_template/example/app/demo.py +76 -0
- agent_launchpad/_template/example/app/guards.py +289 -0
- agent_launchpad/_template/example/app/hooks.py +79 -0
- agent_launchpad/_template/example/app/llm.py +298 -0
- agent_launchpad/_template/example/app/main.py +140 -0
- agent_launchpad/_template/example/app/mcp_server.py +44 -0
- agent_launchpad/_template/example/app/recipes.py +38 -0
- agent_launchpad/_template/example/app/runtime.py +108 -0
- agent_launchpad/_template/example/app/static/index.html +242 -0
- agent_launchpad/_template/example/app/store.py +147 -0
- agent_launchpad/_template/example/app/telemetry.py +56 -0
- agent_launchpad/_template/example/app/tracing.py +195 -0
- agent_launchpad/_template/example/data/store.json +508 -0
- agent_launchpad/_template/example/docker-compose.yml +42 -0
- agent_launchpad/_template/example/evals/DRAFTING.md +33 -0
- agent_launchpad/_template/example/evals/__init__.py +1 -0
- agent_launchpad/_template/example/evals/baseline.py +127 -0
- agent_launchpad/_template/example/evals/cases/heldout.jsonl +24 -0
- agent_launchpad/_template/example/evals/cases/regression.jsonl +50 -0
- agent_launchpad/_template/example/evals/cases/tuning.jsonl +24 -0
- agent_launchpad/_template/example/evals/compare.py +72 -0
- agent_launchpad/_template/example/evals/drafts.py +269 -0
- agent_launchpad/_template/example/evals/grounding.py +140 -0
- agent_launchpad/_template/example/evals/judge.py +155 -0
- agent_launchpad/_template/example/evals/judge_check.py +386 -0
- agent_launchpad/_template/example/evals/judge_labels.jsonl +56 -0
- agent_launchpad/_template/example/evals/judges.py +98 -0
- agent_launchpad/_template/example/evals/rescore.py +56 -0
- agent_launchpad/_template/example/evals/results/README.md +769 -0
- agent_launchpad/_template/example/evals/run.py +226 -0
- agent_launchpad/_template/example/evals/schema.py +92 -0
- agent_launchpad/_template/example/evals/scorer.py +70 -0
- agent_launchpad/_template/example/evals/stats.py +58 -0
- agent_launchpad/_template/example/pyproject.toml +104 -0
- agent_launchpad/_template/example/tests/__init__.py +0 -0
- agent_launchpad/_template/example/tests/conftest.py +26 -0
- agent_launchpad/_template/example/tests/fakes.py +54 -0
- agent_launchpad/_template/example/tests/test_agent.py +167 -0
- agent_launchpad/_template/example/tests/test_api_and_mcp.py +97 -0
- agent_launchpad/_template/example/tests/test_approvals.py +120 -0
- agent_launchpad/_template/example/tests/test_approvals_postgres.py +118 -0
- agent_launchpad/_template/example/tests/test_baseline.py +88 -0
- agent_launchpad/_template/example/tests/test_cascade.py +221 -0
- agent_launchpad/_template/example/tests/test_cases.py +54 -0
- agent_launchpad/_template/example/tests/test_decisions.py +317 -0
- agent_launchpad/_template/example/tests/test_demo.py +33 -0
- agent_launchpad/_template/example/tests/test_drafts.py +209 -0
- agent_launchpad/_template/example/tests/test_guards.py +172 -0
- agent_launchpad/_template/example/tests/test_guards_postgres.py +80 -0
- agent_launchpad/_template/example/tests/test_health.py +32 -0
- agent_launchpad/_template/example/tests/test_judge.py +145 -0
- agent_launchpad/_template/example/tests/test_judge_check.py +96 -0
- agent_launchpad/_template/example/tests/test_lifecycle.py +91 -0
- agent_launchpad/_template/example/tests/test_live_runner.py +61 -0
- agent_launchpad/_template/example/tests/test_live_runs.py +266 -0
- agent_launchpad/_template/example/tests/test_llm.py +261 -0
- agent_launchpad/_template/example/tests/test_postgres.py +110 -0
- agent_launchpad/_template/example/tests/test_postgres_warmup.py +36 -0
- agent_launchpad/_template/example/tests/test_rescore.py +146 -0
- agent_launchpad/_template/example/tests/test_scorer.py +110 -0
- agent_launchpad/_template/example/tests/test_stats.py +77 -0
- agent_launchpad/_template/example/tests/test_store.py +192 -0
- agent_launchpad/_template/example/tests/test_tracing.py +139 -0
- agent_launchpad/_template/example/uv.lock +1767 -0
- agent_launchpad/_template/recipes/approvals.toml +3 -0
- agent_launchpad/_template/recipes/demo.toml +3 -0
- agent_launchpad/_template/recipes/guards.toml +7 -0
- agent_launchpad/_template/recipes/postgres.toml +3 -0
- agent_launchpad/_template/recipes/tracing.toml +3 -0
- agent_launchpad/add.py +152 -0
- agent_launchpad/cli.py +255 -0
- agent_launchpad/generate.py +264 -0
- agent_launchpad/update.py +163 -0
- agent_launchpad-0.1.0.dist-info/METADATA +105 -0
- agent_launchpad-0.1.0.dist-info/RECORD +91 -0
- agent_launchpad-0.1.0.dist-info/WHEEL +4 -0
- agent_launchpad-0.1.0.dist-info/entry_points.txt +2 -0
- agent_launchpad-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""The approval gate's record of requests waiting for a person (#4).
|
|
2
|
+
|
|
3
|
+
When the agent answers a cancellation or address change it can make, code (never the model)
|
|
4
|
+
pauses the agent's graph in Postgres and adds a row here. A person lists what's pending and
|
|
5
|
+
approves or rejects it; the decision resumes the paused graph, even after a restart.
|
|
6
|
+
|
|
7
|
+
Reads never pause: only replies routed `needs_approval` do. The row holds the order id and
|
|
8
|
+
the customer's message, never their email.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import hmac
|
|
14
|
+
import os
|
|
15
|
+
from datetime import UTC, datetime
|
|
16
|
+
from typing import Annotated, Any
|
|
17
|
+
|
|
18
|
+
from fastapi import APIRouter, Depends, Header, HTTPException
|
|
19
|
+
from pydantic import BaseModel, Field
|
|
20
|
+
|
|
21
|
+
from app.agent import Route, StoreAgent
|
|
22
|
+
from app.hooks import ChatContext, Recipe
|
|
23
|
+
from app.runtime import ConnectionPool, Runtime, agent_dependency
|
|
24
|
+
from app.telemetry import tracer
|
|
25
|
+
|
|
26
|
+
STATUSES = ("pending", "approved", "rejected")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def approval_token() -> str | None:
|
|
30
|
+
"""The shared secret an approver sends as `Authorization: Bearer <token>`."""
|
|
31
|
+
return os.environ.get("APPROVAL_TOKEN") or None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def token_matches(authorization: str | None, expected: str) -> bool:
|
|
35
|
+
scheme, _, token = (authorization or "").partition(" ")
|
|
36
|
+
return scheme.lower() == "bearer" and hmac.compare_digest(token.strip(), expected)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class ApprovalStore:
|
|
40
|
+
def __init__(self, pool: ConnectionPool) -> None:
|
|
41
|
+
self._pool = pool
|
|
42
|
+
|
|
43
|
+
async def setup(self) -> None:
|
|
44
|
+
async with self._pool.connection() as conn:
|
|
45
|
+
await conn.execute(
|
|
46
|
+
"CREATE TABLE IF NOT EXISTS approvals ("
|
|
47
|
+
" thread_id text PRIMARY KEY,"
|
|
48
|
+
" order_id text,"
|
|
49
|
+
" request text NOT NULL,"
|
|
50
|
+
" created_at timestamptz NOT NULL DEFAULT now(),"
|
|
51
|
+
" status text NOT NULL DEFAULT 'pending'"
|
|
52
|
+
" CHECK (status IN ('pending', 'approved', 'rejected')),"
|
|
53
|
+
" decided_at timestamptz,"
|
|
54
|
+
" note text)"
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
async def add(self, thread_id: str, order_id: str | None, request: str) -> None:
|
|
58
|
+
async with self._pool.connection() as conn:
|
|
59
|
+
await conn.execute(
|
|
60
|
+
"INSERT INTO approvals (thread_id, order_id, request) VALUES (%s, %s, %s)",
|
|
61
|
+
(thread_id, order_id, request),
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
async def pending(self) -> list[dict[str, Any]]:
|
|
65
|
+
async with self._pool.connection() as conn:
|
|
66
|
+
cursor = await conn.execute(
|
|
67
|
+
"SELECT thread_id, order_id, request, created_at FROM approvals"
|
|
68
|
+
" WHERE status = 'pending' ORDER BY created_at"
|
|
69
|
+
)
|
|
70
|
+
rows = await cursor.fetchall()
|
|
71
|
+
return [{**row, "created_at": row["created_at"].isoformat()} for row in rows]
|
|
72
|
+
|
|
73
|
+
async def status(self, thread_id: str) -> str | None:
|
|
74
|
+
async with self._pool.connection() as conn:
|
|
75
|
+
cursor = await conn.execute(
|
|
76
|
+
"SELECT status FROM approvals WHERE thread_id = %s", (thread_id,)
|
|
77
|
+
)
|
|
78
|
+
row = await cursor.fetchone()
|
|
79
|
+
return str(row["status"]) if row else None
|
|
80
|
+
|
|
81
|
+
async def claim(self, thread_id: str, status: str, note: str | None) -> bool:
|
|
82
|
+
"""Record a decision, only if still pending; False when someone decided first."""
|
|
83
|
+
async with self._pool.connection() as conn:
|
|
84
|
+
cursor = await conn.execute(
|
|
85
|
+
"UPDATE approvals SET status = %s, note = %s, decided_at = now()"
|
|
86
|
+
" WHERE thread_id = %s AND status = 'pending' RETURNING thread_id",
|
|
87
|
+
(status, note, thread_id),
|
|
88
|
+
)
|
|
89
|
+
return await cursor.fetchone() is not None
|
|
90
|
+
|
|
91
|
+
async def release(self, thread_id: str) -> None:
|
|
92
|
+
"""Put a claimed request back to pending, when resuming the graph failed."""
|
|
93
|
+
async with self._pool.connection() as conn:
|
|
94
|
+
await conn.execute(
|
|
95
|
+
"UPDATE approvals SET status = 'pending', note = NULL, decided_at = NULL"
|
|
96
|
+
" WHERE thread_id = %s",
|
|
97
|
+
(thread_id,),
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class Decision(BaseModel):
|
|
102
|
+
approve: bool
|
|
103
|
+
note: str | None = Field(default=None, max_length=500)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class ApprovalsRecipe(Recipe):
|
|
107
|
+
"""Pauses changes until a person decides (#4). Needs the postgres recipe."""
|
|
108
|
+
|
|
109
|
+
name = "approvals"
|
|
110
|
+
|
|
111
|
+
def __init__(self) -> None:
|
|
112
|
+
self.store: ApprovalStore | None = None
|
|
113
|
+
|
|
114
|
+
async def warm_up(self, runtime: Runtime) -> None:
|
|
115
|
+
if runtime.pool is not None:
|
|
116
|
+
store = ApprovalStore(runtime.pool)
|
|
117
|
+
await store.setup()
|
|
118
|
+
self.store = store
|
|
119
|
+
|
|
120
|
+
async def shut_down(self, runtime: Runtime) -> None:
|
|
121
|
+
del runtime
|
|
122
|
+
self.store = None
|
|
123
|
+
|
|
124
|
+
async def after_reply(self, chat: ChatContext) -> None:
|
|
125
|
+
reply = chat.reply
|
|
126
|
+
if reply and reply.route == Route.NEEDS_APPROVAL and chat.thread_id and self.store:
|
|
127
|
+
await self.store.add(chat.thread_id, reply.order_id, chat.message)
|
|
128
|
+
|
|
129
|
+
def approver(self, authorization: str | None) -> ApprovalStore:
|
|
130
|
+
"""Only a person holding APPROVAL_TOKEN can list or decide approvals."""
|
|
131
|
+
token = approval_token()
|
|
132
|
+
if token is None:
|
|
133
|
+
raise HTTPException(status_code=503, detail="approvals are off: set APPROVAL_TOKEN")
|
|
134
|
+
if not token_matches(authorization, token):
|
|
135
|
+
raise HTTPException(status_code=401, detail="a valid approval token is required")
|
|
136
|
+
if self.store is None:
|
|
137
|
+
raise HTTPException(status_code=503, detail="approvals need DATABASE_URL")
|
|
138
|
+
return self.store
|
|
139
|
+
|
|
140
|
+
def routes(self) -> APIRouter:
|
|
141
|
+
router = APIRouter()
|
|
142
|
+
|
|
143
|
+
@router.get("/approvals")
|
|
144
|
+
async def list_approvals( # pyright: ignore[reportUnusedFunction]
|
|
145
|
+
store: Annotated[ApprovalStore, Depends(_approver)],
|
|
146
|
+
) -> dict[str, list[dict[str, object]]]:
|
|
147
|
+
"""Changes the agent paused for a person, oldest first."""
|
|
148
|
+
return {"pending": await store.pending()}
|
|
149
|
+
|
|
150
|
+
@router.post("/approvals/{thread_id}")
|
|
151
|
+
async def decide( # pyright: ignore[reportUnusedFunction]
|
|
152
|
+
thread_id: str,
|
|
153
|
+
decision: Decision,
|
|
154
|
+
store: Annotated[ApprovalStore, Depends(_approver)],
|
|
155
|
+
agent: Annotated[StoreAgent, Depends(agent_dependency)],
|
|
156
|
+
) -> dict[str, object]:
|
|
157
|
+
"""Approve or reject a paused change; resumes the agent's graph from Postgres."""
|
|
158
|
+
if await store.status(thread_id) is None:
|
|
159
|
+
raise HTTPException(status_code=404, detail="no such approval")
|
|
160
|
+
outcome = "approved" if decision.approve else "rejected"
|
|
161
|
+
if not await store.claim(thread_id, outcome, decision.note):
|
|
162
|
+
raise HTTPException(status_code=409, detail="already decided")
|
|
163
|
+
with tracer.start_as_current_span("approval") as span:
|
|
164
|
+
span.set_attribute("thread_id", thread_id)
|
|
165
|
+
span.set_attribute("approved", decision.approve)
|
|
166
|
+
try:
|
|
167
|
+
saved = await agent.decide(
|
|
168
|
+
thread_id,
|
|
169
|
+
{
|
|
170
|
+
"approved": decision.approve,
|
|
171
|
+
"note": decision.note,
|
|
172
|
+
"decided_at": datetime.now(UTC).isoformat(),
|
|
173
|
+
},
|
|
174
|
+
)
|
|
175
|
+
except Exception:
|
|
176
|
+
await store.release(thread_id)
|
|
177
|
+
raise
|
|
178
|
+
return {"thread_id": thread_id, "status": outcome, "approval": saved}
|
|
179
|
+
|
|
180
|
+
return router
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
RECIPE = ApprovalsRecipe()
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _approver(authorization: Annotated[str | None, Header()] = None) -> ApprovalStore:
|
|
187
|
+
"""The approvals routes' dependency; a module-level name, so FastAPI can resolve it."""
|
|
188
|
+
return RECIPE.approver(authorization)
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Postgres: one connection pool for the life of the process.
|
|
2
|
+
|
|
3
|
+
The rules here come from bugs we hit in helpdesk-copilot (docs/traps.md, traps 3 and 4):
|
|
4
|
+
|
|
5
|
+
- Connections are checked before use and recycled before a host drops idle ones, so the
|
|
6
|
+
first request after a quiet hour doesn't fail on a dead connection.
|
|
7
|
+
- The pool is opened once at startup and closed once at shutdown, by the app's lifespan.
|
|
8
|
+
It is never held in a local `AsyncExitStack` that closes when startup returns (the
|
|
9
|
+
`PoolClosed` bug).
|
|
10
|
+
- Connections use autocommit, no prepared statements and dict rows, which is what
|
|
11
|
+
LangGraph's Postgres checkpointer requires.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import logging
|
|
17
|
+
import os
|
|
18
|
+
|
|
19
|
+
from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver
|
|
20
|
+
from psycopg import AsyncConnection
|
|
21
|
+
from psycopg.rows import DictRow, dict_row
|
|
22
|
+
from psycopg_pool import AsyncConnectionPool
|
|
23
|
+
|
|
24
|
+
from app.hooks import Recipe
|
|
25
|
+
from app.runtime import Runtime
|
|
26
|
+
|
|
27
|
+
logger = logging.getLogger(__name__)
|
|
28
|
+
|
|
29
|
+
# Recycle well before the 5 to 10 minutes after which common hosts drop idle connections.
|
|
30
|
+
MAX_IDLE_SECONDS = 240.0
|
|
31
|
+
MAX_LIFETIME_SECONDS = 1800.0
|
|
32
|
+
OPEN_TIMEOUT_SECONDS = 30.0
|
|
33
|
+
|
|
34
|
+
type Pool = AsyncConnectionPool[AsyncConnection[DictRow]]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def database_url() -> str | None:
|
|
38
|
+
"""The Postgres URL from `DATABASE_URL`, or None when the app runs without a database."""
|
|
39
|
+
return os.environ.get("DATABASE_URL") or None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
async def check_connection(conn: AsyncConnection[DictRow]) -> None:
|
|
43
|
+
"""Run before a connection is handed out, so the pool replaces a dead one first."""
|
|
44
|
+
await conn.execute("SELECT 1")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def make_pool(url: str, max_size: int = 5) -> Pool:
|
|
48
|
+
"""A closed pool; open it with `await pool.open(wait=True)` in the lifespan."""
|
|
49
|
+
return AsyncConnectionPool(
|
|
50
|
+
url,
|
|
51
|
+
connection_class=AsyncConnection[DictRow],
|
|
52
|
+
min_size=1,
|
|
53
|
+
max_size=max_size,
|
|
54
|
+
open=False,
|
|
55
|
+
check=check_connection,
|
|
56
|
+
max_idle=MAX_IDLE_SECONDS,
|
|
57
|
+
max_lifetime=MAX_LIFETIME_SECONDS,
|
|
58
|
+
kwargs={"autocommit": True, "prepare_threshold": 0, "row_factory": dict_row},
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class PostgresRecipe(Recipe):
|
|
63
|
+
"""Opens the pool and LangGraph's checkpointer when `DATABASE_URL` is set (#3)."""
|
|
64
|
+
|
|
65
|
+
name = "postgres"
|
|
66
|
+
|
|
67
|
+
async def warm_up(self, runtime: Runtime) -> None:
|
|
68
|
+
url = database_url()
|
|
69
|
+
if url is None:
|
|
70
|
+
logger.warning("DATABASE_URL is not set: running without a checkpointer")
|
|
71
|
+
return
|
|
72
|
+
pool = make_pool(url)
|
|
73
|
+
runtime.pool = pool
|
|
74
|
+
await pool.open(wait=True, timeout=OPEN_TIMEOUT_SECONDS)
|
|
75
|
+
checkpointer = AsyncPostgresSaver(pool) # pyright: ignore[reportArgumentType]
|
|
76
|
+
await checkpointer.setup()
|
|
77
|
+
runtime.checkpointer = checkpointer
|
|
78
|
+
|
|
79
|
+
async def shut_down(self, runtime: Runtime) -> None:
|
|
80
|
+
pool = runtime.pool
|
|
81
|
+
if isinstance(pool, AsyncConnectionPool):
|
|
82
|
+
await pool.close()
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
RECIPE = PostgresRecipe()
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
"""A client for System One decision models: Jev, Clef, Kev and the like.
|
|
2
|
+
|
|
3
|
+
A decision model reads some state, answers typed questions with probabilities in one
|
|
4
|
+
forward pass, and writes no text. TypeSafe's API (`POST /v1/systemone`) and
|
|
5
|
+
OpenRouter's Decisions API (`POST /api/alpha/decisions`) share the request shape, so one
|
|
6
|
+
client covers both. The model id picks the provider:
|
|
7
|
+
|
|
8
|
+
typesafe:jev-latest TypeSafe directly, with TYPESAFE_API_KEY
|
|
9
|
+
typesafe/jev-1.14 OpenRouter, with OPENROUTER_API_KEY
|
|
10
|
+
cloudflare/clef-flash OpenRouter
|
|
11
|
+
|
|
12
|
+
Like the chat client, it counts tokens against an optional budget, never logs or
|
|
13
|
+
prints the key, and can record and replay replies (LLM_RECORDING, LLM_RECORDING_PATH).
|
|
14
|
+
It counts which host answered, and DECISIONS_EXTRA_BODY (JSON, merged into every
|
|
15
|
+
request) can pin one, e.g. {"provider": {"order": ["<slug>"], "allow_fallbacks": false}}.
|
|
16
|
+
|
|
17
|
+
uv run python -m app.decisions --list # decision models on OpenRouter (free)
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import argparse
|
|
23
|
+
import asyncio
|
|
24
|
+
import os
|
|
25
|
+
import sys
|
|
26
|
+
import time
|
|
27
|
+
from dataclasses import dataclass, field
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
from typing import Any
|
|
30
|
+
|
|
31
|
+
import httpx
|
|
32
|
+
|
|
33
|
+
from app.llm import (
|
|
34
|
+
HTTP_OK,
|
|
35
|
+
RETRY_STATUS,
|
|
36
|
+
BudgetExceededError,
|
|
37
|
+
LLMError,
|
|
38
|
+
NotRecordedError,
|
|
39
|
+
Recording,
|
|
40
|
+
Recordings,
|
|
41
|
+
_append_recording, # pyright: ignore[reportPrivateUsage]
|
|
42
|
+
_budget, # pyright: ignore[reportPrivateUsage]
|
|
43
|
+
_extra_body, # pyright: ignore[reportPrivateUsage]
|
|
44
|
+
_read_recordings, # pyright: ignore[reportPrivateUsage]
|
|
45
|
+
request_key,
|
|
46
|
+
safe,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
OPENROUTER_URL = "https://openrouter.ai/api/alpha/decisions"
|
|
50
|
+
OPENROUTER_MODELS_URL = "https://openrouter.ai/api/v1/models?output_modalities=decisions"
|
|
51
|
+
TYPESAFE_URL = "https://api.typesafe.ai/v1/systemone"
|
|
52
|
+
TYPESAFE_PREFIX = "typesafe:"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class Decision:
|
|
57
|
+
"""The probability that the answer is yes, or None if the model gave no usable answer."""
|
|
58
|
+
|
|
59
|
+
yes: float | None
|
|
60
|
+
seconds: float = 0.0
|
|
61
|
+
cost: float = 0.0
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass
|
|
65
|
+
class DecisionClient:
|
|
66
|
+
model: str
|
|
67
|
+
api_key: str = field(repr=False)
|
|
68
|
+
url: str = OPENROUTER_URL
|
|
69
|
+
timeout: float = 30.0
|
|
70
|
+
retries: int = 3
|
|
71
|
+
budget: int | None = None
|
|
72
|
+
recording: Recording = Recording.OFF
|
|
73
|
+
recording_path: Path | None = None
|
|
74
|
+
transport: httpx.AsyncBaseTransport | None = None
|
|
75
|
+
input_tokens: int = 0
|
|
76
|
+
output_tokens: int = 0
|
|
77
|
+
cost: float = 0.0
|
|
78
|
+
calls: int = 0
|
|
79
|
+
# Merged into every request, e.g. to pin one OpenRouter host. Never holds secrets.
|
|
80
|
+
extra_body: dict[str, Any] = field(default_factory=dict[str, Any])
|
|
81
|
+
providers: dict[str, int] = field(default_factory=dict[str, int])
|
|
82
|
+
_replies: Recordings = field(default_factory=lambda: Recordings({}))
|
|
83
|
+
|
|
84
|
+
def __post_init__(self) -> None:
|
|
85
|
+
if self.recording is not Recording.OFF and self.recording_path is None:
|
|
86
|
+
raise LLMError("set LLM_RECORDING_PATH to record or replay")
|
|
87
|
+
if self.recording is Recording.REPLAY:
|
|
88
|
+
self._replies = _read_recordings(self.recording_path)
|
|
89
|
+
|
|
90
|
+
@classmethod
|
|
91
|
+
def from_env(cls, model: str) -> DecisionClient:
|
|
92
|
+
direct = model.startswith(TYPESAFE_PREFIX)
|
|
93
|
+
name = model.removeprefix(TYPESAFE_PREFIX)
|
|
94
|
+
key_name = "TYPESAFE_API_KEY" if direct else "OPENROUTER_API_KEY"
|
|
95
|
+
recording = Recording(os.environ.get("LLM_RECORDING") or "off")
|
|
96
|
+
key = os.environ.get(key_name) or ""
|
|
97
|
+
if not key and recording is not Recording.REPLAY:
|
|
98
|
+
raise LLMError(f"set {key_name} to use {model}")
|
|
99
|
+
raw_path = os.environ.get("LLM_RECORDING_PATH") or ""
|
|
100
|
+
return cls(
|
|
101
|
+
model=name,
|
|
102
|
+
api_key=key,
|
|
103
|
+
url=TYPESAFE_URL if direct else OPENROUTER_URL,
|
|
104
|
+
budget=_budget(os.environ.get("LLM_TOKEN_BUDGET") or ""),
|
|
105
|
+
recording=recording,
|
|
106
|
+
recording_path=Path(raw_path) if raw_path else None,
|
|
107
|
+
extra_body=_extra_body(os.environ.get("DECISIONS_EXTRA_BODY") or "{}"),
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
def used(self) -> int:
|
|
112
|
+
return self.input_tokens + self.output_tokens
|
|
113
|
+
|
|
114
|
+
def usage_report(self) -> dict[str, Any]:
|
|
115
|
+
return {
|
|
116
|
+
"calls": self.calls,
|
|
117
|
+
"input_tokens": self.input_tokens,
|
|
118
|
+
"output_tokens": self.output_tokens,
|
|
119
|
+
"cost_usd": round(self.cost, 6),
|
|
120
|
+
"budget": self.budget,
|
|
121
|
+
"providers": dict(self.providers),
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async def yes_no(
|
|
125
|
+
self, state: str, instructions: str, yes_means: str, no_means: str
|
|
126
|
+
) -> Decision:
|
|
127
|
+
"""Ask one yes/no question about `state`."""
|
|
128
|
+
body: dict[str, Any] = {
|
|
129
|
+
**self.extra_body,
|
|
130
|
+
"model": self.model,
|
|
131
|
+
"state": state,
|
|
132
|
+
"questions": {
|
|
133
|
+
"answer": {
|
|
134
|
+
"type": "noul",
|
|
135
|
+
"instructions": instructions,
|
|
136
|
+
"criteria": {"true": yes_means, "false": no_means},
|
|
137
|
+
}
|
|
138
|
+
},
|
|
139
|
+
}
|
|
140
|
+
key = request_key(body)
|
|
141
|
+
if self.recording is Recording.REPLAY:
|
|
142
|
+
recorded = self._replies.take(key)
|
|
143
|
+
if recorded is None:
|
|
144
|
+
raise NotRecordedError(f"{self.model}: request {key[:12]} was never recorded")
|
|
145
|
+
data, seconds = recorded, 0.0
|
|
146
|
+
else:
|
|
147
|
+
if self.budget is not None and self.used >= self.budget:
|
|
148
|
+
raise BudgetExceededError(
|
|
149
|
+
f"{self.model}: token budget of {self.budget:,} spent ({self.used:,} used)"
|
|
150
|
+
)
|
|
151
|
+
data, seconds = await self._post(body)
|
|
152
|
+
if self.recording is Recording.RECORD and self.recording_path is not None:
|
|
153
|
+
_append_recording(self.recording_path, key, data)
|
|
154
|
+
return self._decision(data, seconds)
|
|
155
|
+
|
|
156
|
+
def _decision(self, data: dict[str, Any], seconds: float) -> Decision:
|
|
157
|
+
self.calls += 1
|
|
158
|
+
usage: dict[str, Any] = data.get("usage") or {}
|
|
159
|
+
self.input_tokens += int(usage.get("input_tokens") or 0)
|
|
160
|
+
self.output_tokens += int(usage.get("output_tokens") or 0)
|
|
161
|
+
cost = float(usage.get("cost") or 0.0)
|
|
162
|
+
self.cost += cost
|
|
163
|
+
provider = data.get("provider")
|
|
164
|
+
if isinstance(provider, str) and provider:
|
|
165
|
+
self.providers[provider] = self.providers.get(provider, 0) + 1
|
|
166
|
+
answers: dict[str, Any] = data.get("answers") or {}
|
|
167
|
+
answer: dict[str, Any] = answers.get("answer") or {}
|
|
168
|
+
# A refusal, a missing answer or an unexpected type is "no answer", never a NO.
|
|
169
|
+
value = answer.get("noul")
|
|
170
|
+
if answer.get("type") != "noul" or not isinstance(value, int | float):
|
|
171
|
+
return Decision(None, seconds, cost)
|
|
172
|
+
return Decision(float(value), seconds, cost)
|
|
173
|
+
|
|
174
|
+
async def _post(self, body: dict[str, Any]) -> tuple[dict[str, Any], float]:
|
|
175
|
+
headers = {"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"}
|
|
176
|
+
async with httpx.AsyncClient(timeout=self.timeout, transport=self.transport) as http:
|
|
177
|
+
for attempt in range(self.retries + 1):
|
|
178
|
+
started = time.perf_counter()
|
|
179
|
+
try:
|
|
180
|
+
response = await http.post(self.url, json=body, headers=headers)
|
|
181
|
+
except httpx.HTTPError as error:
|
|
182
|
+
if attempt == self.retries:
|
|
183
|
+
name = type(error).__name__
|
|
184
|
+
raise LLMError(f"{self.model}: request failed ({name})") from None
|
|
185
|
+
await asyncio.sleep(2**attempt)
|
|
186
|
+
continue
|
|
187
|
+
seconds = time.perf_counter() - started
|
|
188
|
+
if response.status_code in RETRY_STATUS and attempt < self.retries:
|
|
189
|
+
await asyncio.sleep(2**attempt)
|
|
190
|
+
continue
|
|
191
|
+
if response.status_code != HTTP_OK:
|
|
192
|
+
detail = safe(response.text, self.api_key)
|
|
193
|
+
raise LLMError(f"{self.model}: HTTP {response.status_code}: {detail}")
|
|
194
|
+
data: dict[str, Any] = response.json()
|
|
195
|
+
return data, seconds
|
|
196
|
+
raise LLMError(f"{self.model}: no response") # pragma: no cover
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
async def list_models(transport: httpx.AsyncBaseTransport | None = None) -> list[str]:
|
|
200
|
+
"""The decision models OpenRouter lists right now, with their input price per
|
|
201
|
+
million tokens when it is listed. Needs no key and costs nothing."""
|
|
202
|
+
async with httpx.AsyncClient(timeout=30.0, transport=transport) as http:
|
|
203
|
+
response = await http.get(OPENROUTER_MODELS_URL)
|
|
204
|
+
if response.status_code != HTTP_OK:
|
|
205
|
+
raise LLMError(f"listing decision models: HTTP {response.status_code}")
|
|
206
|
+
rows: list[dict[str, Any]] = response.json().get("data") or []
|
|
207
|
+
lines: list[str] = []
|
|
208
|
+
for row in sorted((r for r in rows if "id" in r), key=lambda r: str(r["id"])):
|
|
209
|
+
pricing: dict[str, Any] = row.get("pricing") or {}
|
|
210
|
+
try:
|
|
211
|
+
price = f"${float(pricing['prompt']) * 1_000_000:.3f}/M input"
|
|
212
|
+
except KeyError, TypeError, ValueError:
|
|
213
|
+
price = "price not listed"
|
|
214
|
+
lines.append(f"{row['id']} {price}")
|
|
215
|
+
return lines
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def main(argv: list[str] | None = None) -> int:
|
|
219
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
220
|
+
parser.add_argument("--list", action="store_true", help="list OpenRouter decision models")
|
|
221
|
+
args = parser.parse_args(argv)
|
|
222
|
+
if not args.list:
|
|
223
|
+
parser.print_help()
|
|
224
|
+
return 2
|
|
225
|
+
for model in asyncio.run(list_models()):
|
|
226
|
+
print(model)
|
|
227
|
+
return 0
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
if __name__ == "__main__":
|
|
231
|
+
sys.exit(main())
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""The public demo page: one HTML file and the sample customers it offers.
|
|
2
|
+
|
|
3
|
+
A lean stand-in for the full console (#7, Milestone 2): no build step, no keys in the
|
|
4
|
+
browser. The page calls `/chat` on the same origin, so every guard still applies.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from fastapi import APIRouter
|
|
12
|
+
from fastapi.responses import HTMLResponse
|
|
13
|
+
from pydantic import BaseModel
|
|
14
|
+
|
|
15
|
+
from app.hooks import Recipe
|
|
16
|
+
|
|
17
|
+
PAGE = Path(__file__).parent / "static" / "index.html"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class SampleCustomer(BaseModel):
|
|
21
|
+
email: str
|
|
22
|
+
order_id: str
|
|
23
|
+
try_asking: str
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
# Fictional customers from data/store.json, each with a question that shows one behaviour.
|
|
27
|
+
SAMPLES = (
|
|
28
|
+
SampleCustomer(
|
|
29
|
+
email="ben.okafor@example.com",
|
|
30
|
+
order_id="BP-1002",
|
|
31
|
+
try_asking="Where is my order BP-1002?",
|
|
32
|
+
),
|
|
33
|
+
SampleCustomer(
|
|
34
|
+
email="lena.fischer@example.com",
|
|
35
|
+
order_id="BP-1027",
|
|
36
|
+
try_asking="Can I send back the socks from BP-1027?",
|
|
37
|
+
),
|
|
38
|
+
SampleCustomer(
|
|
39
|
+
email="maya.chen@example.com",
|
|
40
|
+
order_id="BP-1029",
|
|
41
|
+
try_asking="Please cancel BP-1029.",
|
|
42
|
+
),
|
|
43
|
+
SampleCustomer(
|
|
44
|
+
email="rosa.lindgren@example.com",
|
|
45
|
+
order_id="BP-1016",
|
|
46
|
+
try_asking="Has my refund for BP-1016 come through?",
|
|
47
|
+
),
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def page() -> str:
|
|
52
|
+
return PAGE.read_text(encoding="utf-8")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class DemoRecipe(Recipe):
|
|
56
|
+
"""A one-file chat page at `/` and its sample customers."""
|
|
57
|
+
|
|
58
|
+
name = "demo"
|
|
59
|
+
|
|
60
|
+
def routes(self) -> APIRouter:
|
|
61
|
+
router = APIRouter()
|
|
62
|
+
|
|
63
|
+
@router.get("/", response_class=HTMLResponse, include_in_schema=False)
|
|
64
|
+
def home() -> str: # pyright: ignore[reportUnusedFunction]
|
|
65
|
+
"""The demo page: a chat that calls /chat, so every guard still applies."""
|
|
66
|
+
return page()
|
|
67
|
+
|
|
68
|
+
@router.get("/demo/customers")
|
|
69
|
+
def demo_customers() -> list[SampleCustomer]: # pyright: ignore[reportUnusedFunction]
|
|
70
|
+
"""Fictional customers the demo page offers to sign in as."""
|
|
71
|
+
return list(SAMPLES)
|
|
72
|
+
|
|
73
|
+
return router
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
RECIPE = DemoRecipe()
|