agents-framework 0.3.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.
- agents_framework-0.3.0.dist-info/METADATA +1364 -0
- agents_framework-0.3.0.dist-info/RECORD +50 -0
- agents_framework-0.3.0.dist-info/WHEEL +5 -0
- agents_framework-0.3.0.dist-info/entry_points.txt +2 -0
- agents_framework-0.3.0.dist-info/licenses/LICENSE +661 -0
- agents_framework-0.3.0.dist-info/top_level.txt +1 -0
- framework/__init__.py +0 -0
- framework/__main__.py +9 -0
- framework/action_page.py +1102 -0
- framework/approval_buttons.py +775 -0
- framework/approvals.py +678 -0
- framework/calendar_card.py +276 -0
- framework/cli.py +273 -0
- framework/codex_llm.py +401 -0
- framework/config.py +126 -0
- framework/drafter.py +263 -0
- framework/interfaces.py +96 -0
- framework/llm.py +744 -0
- framework/plugins/__init__.py +147 -0
- framework/plugins/agentmail_source.py +355 -0
- framework/plugins/approval_destination.py +478 -0
- framework/plugins/command_action.py +248 -0
- framework/plugins/digest_destination.py +546 -0
- framework/plugins/email_destination.py +248 -0
- framework/plugins/fanout_destination.py +160 -0
- framework/plugins/github_org_source.py +226 -0
- framework/plugins/github_releases_source.py +420 -0
- framework/plugins/ics_source.py +594 -0
- framework/plugins/llm_scorer.py +411 -0
- framework/plugins/multi_source.py +241 -0
- framework/plugins/reddit_source.py +625 -0
- framework/plugins/regex_scorer.py +93 -0
- framework/plugins/rss_source.py +346 -0
- framework/plugins/signal_destination.py +133 -0
- framework/plugins/slack_destination.py +461 -0
- framework/plugins/slack_draft_action.py +137 -0
- framework/plugins/slack_post_action.py +65 -0
- framework/plugins/slack_workspace_source.py +992 -0
- framework/plugins/twitter_action.py +210 -0
- framework/plugins/websearch_source.py +761 -0
- framework/plugins/wordpress_action.py +413 -0
- framework/proposals.py +246 -0
- framework/registry.py +166 -0
- framework/runlog.py +125 -0
- framework/runner.py +243 -0
- framework/schedule.py +571 -0
- framework/signal_messenger.py +1418 -0
- framework/slack.py +801 -0
- framework/state.py +39 -0
- framework/templating.py +76 -0
framework/codex_llm.py
ADDED
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
"""Codex subscription as a waterfall vendor (issue #44).
|
|
2
|
+
|
|
3
|
+
Ported from shmobster's `codex_llm.py`, verbatim where the two codebases allow,
|
|
4
|
+
so the copies can still be diffed against each other.
|
|
5
|
+
|
|
6
|
+
Every other rung in the waterfall is an API-key HTTP row, so LiteLLM can dial it
|
|
7
|
+
from config alone. A codex *subscription* is not: it authenticates with the
|
|
8
|
+
ChatGPT OAuth tokens the codex CLI keeps in `~/.codex/auth.json`, and it speaks
|
|
9
|
+
the Responses API rather than chat/completions. This module is the bridge that
|
|
10
|
+
makes it look like any other rung.
|
|
11
|
+
|
|
12
|
+
Three decisions, all deliberate:
|
|
13
|
+
|
|
14
|
+
**In-process, not a separate server.** Registered as a `litellm.CustomLLM` via
|
|
15
|
+
`litellm.custom_provider_map`, so the waterfall row is
|
|
16
|
+
`{"name": "codex", "model": "codex/chatgpt/<model>"}` -- no `api_key_env`, no
|
|
17
|
+
`api_base`, and no second process under the scheduler.
|
|
18
|
+
|
|
19
|
+
**We read codex's tokens; we do NOT run codex.** The framework used to drive the
|
|
20
|
+
binary (`codex exec`), which kept the token out of our hands but handed us an
|
|
21
|
+
*agent*: codex brings its own tool set, sandbox and approval policy, prints hook
|
|
22
|
+
chatter around its answer, and costs a process start of several seconds per
|
|
23
|
+
call. A waterfall rung needs a plain model call and nothing else, and reading
|
|
24
|
+
the token gives exactly that.
|
|
25
|
+
|
|
26
|
+
**We do not refresh the token -- we warn.** `auth.json` is re-read on every
|
|
27
|
+
call, so any rotation the codex CLI performs is picked up for free; the access
|
|
28
|
+
token is a ~10-day JWT and the CLI rotates it whenever it runs. Owning the
|
|
29
|
+
refresh would mean writing back to `auth.json` and racing the CLI over a refresh
|
|
30
|
+
token that may well be single-use -- a bug there breaks the operator's actual
|
|
31
|
+
codex login, which is far worse than one dead rung. Instead the token's own
|
|
32
|
+
`exp` claim is read on every call and an expiry inside `_WARN_BEFORE_SEC` is
|
|
33
|
+
printed to stderr (at most hourly, so a busy run does not turn the warning into
|
|
34
|
+
spam). An already-dead token surfaces as a 401: LiteLLM cools the deployment,
|
|
35
|
+
the chain falls through, and the fix is `codex login` (or any codex CLI use).
|
|
36
|
+
|
|
37
|
+
Contract, established against the live endpoint rather than from docs:
|
|
38
|
+
- POST https://chatgpt.com/backend-api/codex/responses
|
|
39
|
+
- `Authorization: Bearer <tokens.access_token>` + `ChatGPT-Account-Id`
|
|
40
|
+
- `stream: true` is REQUIRED -- a non-streaming request is refused with
|
|
41
|
+
400 "Stream must be set to true", so the SSE body is read whole and parsed
|
|
42
|
+
here even though nothing downstream streams.
|
|
43
|
+
- `store: false`, and the model must be one the ChatGPT plan allows.
|
|
44
|
+
- function tools come back as `function_call` items with call_id/name/
|
|
45
|
+
arguments, which map 1:1 onto OpenAI tool_calls. `LLMClient` sends no
|
|
46
|
+
tools today; the mapping is kept so this file stays a straight port.
|
|
47
|
+
"""
|
|
48
|
+
from __future__ import annotations
|
|
49
|
+
|
|
50
|
+
import base64
|
|
51
|
+
import json
|
|
52
|
+
import os
|
|
53
|
+
import sys
|
|
54
|
+
import time
|
|
55
|
+
import uuid
|
|
56
|
+
|
|
57
|
+
import httpx
|
|
58
|
+
import litellm
|
|
59
|
+
from litellm import CustomLLM
|
|
60
|
+
from litellm.types.utils import (
|
|
61
|
+
ChatCompletionMessageToolCall,
|
|
62
|
+
Function,
|
|
63
|
+
Message,
|
|
64
|
+
Usage,
|
|
65
|
+
)
|
|
66
|
+
from litellm.utils import custom_llm_setup
|
|
67
|
+
|
|
68
|
+
PROVIDER = "codex"
|
|
69
|
+
|
|
70
|
+
_ENDPOINT = "https://chatgpt.com/backend-api/codex/responses"
|
|
71
|
+
|
|
72
|
+
# The originator identifies the *client the credentials belong to*. These are
|
|
73
|
+
# codex's tokens, so this is codex's originator -- not this framework's.
|
|
74
|
+
_ORIGINATOR = "codex_cli_rs"
|
|
75
|
+
|
|
76
|
+
_DEFAULT_TIMEOUT = 300.0
|
|
77
|
+
|
|
78
|
+
# Waterfall rows say `codex/chatgpt/<model>`, and the `chatgpt/` segment is
|
|
79
|
+
# load-bearing rather than decoration. litellm dispatches on the model name
|
|
80
|
+
# BEFORE it dispatches on the custom provider: `model in
|
|
81
|
+
# open_ai_chat_completion_models` is an earlier branch than the custom-provider
|
|
82
|
+
# one, so a row of `codex/gpt-5.5` leaves litellm holding the bare `gpt-5.5`,
|
|
83
|
+
# recognising it as an OpenAI model, and quietly billing a platform API key
|
|
84
|
+
# instead of ever reaching this handler. A segment that is not a known OpenAI
|
|
85
|
+
# model id is what keeps the dispatch honest; it is stripped back off here.
|
|
86
|
+
MODEL_PREFIX = "chatgpt/"
|
|
87
|
+
|
|
88
|
+
# Warn this far ahead of the access token's own expiry. A day is enough notice
|
|
89
|
+
# to run `codex login` before the rung goes dead, and short enough that the
|
|
90
|
+
# warning still means something when it appears.
|
|
91
|
+
_WARN_BEFORE_SEC = 24 * 3600
|
|
92
|
+
_WARN_EVERY_SEC = 3600
|
|
93
|
+
_last_warned = 0.0
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _auth_path():
|
|
97
|
+
home = os.environ.get("CODEX_HOME") or os.path.expanduser("~/.codex")
|
|
98
|
+
retval = os.path.join(home, "auth.json")
|
|
99
|
+
return retval
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _auth(model):
|
|
103
|
+
"""The live access token and account id, re-read every call so a rotation by
|
|
104
|
+
the codex CLI is picked up without a restart. Never logged, never returned to
|
|
105
|
+
a caller that might."""
|
|
106
|
+
path = _auth_path()
|
|
107
|
+
try:
|
|
108
|
+
with open(path, "r") as f:
|
|
109
|
+
data = json.load(f)
|
|
110
|
+
except (OSError, ValueError):
|
|
111
|
+
raise litellm.AuthenticationError(
|
|
112
|
+
f"codex: cannot read {path} -- run `codex login`",
|
|
113
|
+
llm_provider=PROVIDER, model=model)
|
|
114
|
+
tokens = data.get("tokens") or {}
|
|
115
|
+
token = tokens.get("access_token")
|
|
116
|
+
if not token:
|
|
117
|
+
raise litellm.AuthenticationError(
|
|
118
|
+
"codex: no ChatGPT access token in auth.json -- run `codex login`",
|
|
119
|
+
llm_provider=PROVIDER, model=model)
|
|
120
|
+
_warn_if_expiring(token)
|
|
121
|
+
retval = (token, tokens.get("account_id") or "")
|
|
122
|
+
return retval
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _expiry(token):
|
|
126
|
+
"""The `exp` claim, read straight off the JWT payload. Unsigned on purpose:
|
|
127
|
+
this is not a trust decision -- the server verifies the token -- it is only
|
|
128
|
+
"how long before an operator has to act". A token we cannot parse gets no
|
|
129
|
+
warning rather than a wrong one."""
|
|
130
|
+
try:
|
|
131
|
+
payload = token.split(".")[1]
|
|
132
|
+
payload += "=" * (-len(payload) % 4)
|
|
133
|
+
retval = float(json.loads(base64.urlsafe_b64decode(payload))["exp"])
|
|
134
|
+
except (IndexError, ValueError, KeyError, TypeError):
|
|
135
|
+
retval = None
|
|
136
|
+
return retval
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _warn_if_expiring(token):
|
|
140
|
+
"""Tell the operator to rotate before the rung dies, not after. Rate-limited
|
|
141
|
+
because this runs on every single call, and the token is never printed --
|
|
142
|
+
only how long is left on it."""
|
|
143
|
+
global _last_warned
|
|
144
|
+
exp = _expiry(token)
|
|
145
|
+
now = time.time()
|
|
146
|
+
if exp is None or exp - now > _WARN_BEFORE_SEC:
|
|
147
|
+
return
|
|
148
|
+
if now - _last_warned < _WARN_EVERY_SEC:
|
|
149
|
+
return
|
|
150
|
+
_last_warned = now
|
|
151
|
+
left = exp - now
|
|
152
|
+
if left <= 0:
|
|
153
|
+
print("llm: codex: the ChatGPT token has expired; run `codex login` to rotate it",
|
|
154
|
+
file=sys.stderr)
|
|
155
|
+
else:
|
|
156
|
+
# Rounded up: "0h" on a token with 50 minutes left reads as "already
|
|
157
|
+
# dead" when the operator still has time to act.
|
|
158
|
+
print(
|
|
159
|
+
"llm: codex: the ChatGPT token expires in ~%dh; run `codex login` to rotate it "
|
|
160
|
+
"(this framework does not refresh it -- the codex CLI owns that file)"
|
|
161
|
+
% max(1, -(-int(left) // 3600)),
|
|
162
|
+
file=sys.stderr)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _headers(token, account_id):
|
|
166
|
+
retval = {
|
|
167
|
+
"Authorization": f"Bearer {token}",
|
|
168
|
+
"Content-Type": "application/json",
|
|
169
|
+
"Accept": "text/event-stream",
|
|
170
|
+
"originator": _ORIGINATOR,
|
|
171
|
+
"User-Agent": _ORIGINATOR,
|
|
172
|
+
"session_id": str(uuid.uuid4()),
|
|
173
|
+
}
|
|
174
|
+
if account_id:
|
|
175
|
+
retval["ChatGPT-Account-Id"] = account_id
|
|
176
|
+
return retval
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _text_of(content):
|
|
180
|
+
"""Flatten OpenAI chat content into plain text. A content *list* is the
|
|
181
|
+
multimodal shape: the text parts are kept and image parts are dropped rather
|
|
182
|
+
than translated, since an image block the Responses API rejects would fail
|
|
183
|
+
the call outright."""
|
|
184
|
+
if content is None:
|
|
185
|
+
retval = ""
|
|
186
|
+
elif isinstance(content, str):
|
|
187
|
+
retval = content
|
|
188
|
+
elif isinstance(content, list):
|
|
189
|
+
parts = []
|
|
190
|
+
for item in content:
|
|
191
|
+
if isinstance(item, dict) and item.get("type") == "text":
|
|
192
|
+
parts.append(item.get("text") or "")
|
|
193
|
+
elif isinstance(item, dict) and item.get("type") == "image_url":
|
|
194
|
+
parts.append("[image omitted: codex fallback is text-only]")
|
|
195
|
+
retval = "\n".join(p for p in parts if p)
|
|
196
|
+
else:
|
|
197
|
+
retval = str(content)
|
|
198
|
+
return retval
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _to_input(messages):
|
|
202
|
+
"""OpenAI chat messages -> (instructions, Responses input items).
|
|
203
|
+
|
|
204
|
+
System/developer turns become `instructions` because the Responses API has no
|
|
205
|
+
system role. The rest map one-for-one, including the tool round-trip:
|
|
206
|
+
an assistant `tool_calls` entry becomes a `function_call` item and the
|
|
207
|
+
matching `role: tool` reply becomes `function_call_output`, keyed by the same
|
|
208
|
+
call_id -- without that pairing the next turn is rejected."""
|
|
209
|
+
instructions = []
|
|
210
|
+
items = []
|
|
211
|
+
for msg in messages:
|
|
212
|
+
role = msg.get("role")
|
|
213
|
+
if role in ("system", "developer"):
|
|
214
|
+
instructions.append(_text_of(msg.get("content")))
|
|
215
|
+
elif role == "tool":
|
|
216
|
+
items.append({
|
|
217
|
+
"type": "function_call_output",
|
|
218
|
+
"call_id": msg.get("tool_call_id") or "",
|
|
219
|
+
"output": _text_of(msg.get("content")),
|
|
220
|
+
})
|
|
221
|
+
elif role == "assistant":
|
|
222
|
+
text = _text_of(msg.get("content"))
|
|
223
|
+
if text:
|
|
224
|
+
items.append({"type": "message", "role": "assistant",
|
|
225
|
+
"content": [{"type": "output_text", "text": text}]})
|
|
226
|
+
for call in msg.get("tool_calls") or []:
|
|
227
|
+
fn = call.get("function") or {}
|
|
228
|
+
items.append({
|
|
229
|
+
"type": "function_call",
|
|
230
|
+
"call_id": call.get("id") or "",
|
|
231
|
+
"name": fn.get("name") or "",
|
|
232
|
+
"arguments": fn.get("arguments") or "{}",
|
|
233
|
+
})
|
|
234
|
+
else:
|
|
235
|
+
items.append({"type": "message", "role": "user",
|
|
236
|
+
"content": [{"type": "input_text", "text": _text_of(msg.get("content"))}]})
|
|
237
|
+
retval = ("\n\n".join(i for i in instructions if i), items)
|
|
238
|
+
return retval
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _to_tools(tools):
|
|
242
|
+
"""Chat tool schemas -> Responses tool schemas: same JSON Schema, but flat
|
|
243
|
+
(name/description/parameters at the top level) instead of nested under
|
|
244
|
+
`function`."""
|
|
245
|
+
if not tools:
|
|
246
|
+
retval = None
|
|
247
|
+
return retval
|
|
248
|
+
out = []
|
|
249
|
+
for tool in tools:
|
|
250
|
+
fn = tool.get("function") or {}
|
|
251
|
+
out.append({
|
|
252
|
+
"type": "function",
|
|
253
|
+
"name": fn.get("name"),
|
|
254
|
+
"description": fn.get("description") or "",
|
|
255
|
+
"parameters": fn.get("parameters") or {"type": "object", "properties": {}},
|
|
256
|
+
"strict": False,
|
|
257
|
+
})
|
|
258
|
+
retval = out
|
|
259
|
+
return retval
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _parse(body):
|
|
263
|
+
"""Pull the assistant turn out of the SSE body.
|
|
264
|
+
|
|
265
|
+
Only `response.output_item.done` and `response.completed` are read: the delta
|
|
266
|
+
events are the same content arriving in pieces, and nothing downstream
|
|
267
|
+
streams. Reasoning items are ignored -- they carry encrypted state for a
|
|
268
|
+
stored conversation, and this bridge sends the whole history every call."""
|
|
269
|
+
content_parts = []
|
|
270
|
+
tool_calls = []
|
|
271
|
+
usage = None
|
|
272
|
+
for line in body.splitlines():
|
|
273
|
+
if not line.startswith("data:"):
|
|
274
|
+
continue
|
|
275
|
+
raw = line[5:].strip()
|
|
276
|
+
if not raw or raw == "[DONE]":
|
|
277
|
+
continue
|
|
278
|
+
try:
|
|
279
|
+
event = json.loads(raw)
|
|
280
|
+
except ValueError:
|
|
281
|
+
continue
|
|
282
|
+
kind = event.get("type")
|
|
283
|
+
if kind == "response.output_item.done":
|
|
284
|
+
item = event.get("item") or {}
|
|
285
|
+
if item.get("type") == "function_call":
|
|
286
|
+
tool_calls.append(ChatCompletionMessageToolCall(
|
|
287
|
+
id=item.get("call_id") or item.get("id") or "",
|
|
288
|
+
type="function",
|
|
289
|
+
function=Function(name=item.get("name") or "",
|
|
290
|
+
arguments=item.get("arguments") or "{}"),
|
|
291
|
+
))
|
|
292
|
+
elif item.get("type") == "message":
|
|
293
|
+
for part in item.get("content") or []:
|
|
294
|
+
if part.get("type") in ("output_text", "text"):
|
|
295
|
+
content_parts.append(part.get("text") or "")
|
|
296
|
+
elif kind == "response.completed":
|
|
297
|
+
usage = (event.get("response") or {}).get("usage")
|
|
298
|
+
retval = ("".join(content_parts), tool_calls, usage)
|
|
299
|
+
return retval
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _raise_for(status, body, model):
|
|
303
|
+
"""Map codex's HTTP status onto the litellm exception the Router reacts to:
|
|
304
|
+
401/403 and 429 are what it cools a deployment on, so getting these right is
|
|
305
|
+
what makes a dead or throttled codex fall through instead of being re-dialled
|
|
306
|
+
every call."""
|
|
307
|
+
text = (body or "")[:300]
|
|
308
|
+
if status in (401, 403):
|
|
309
|
+
raise litellm.AuthenticationError(
|
|
310
|
+
f"codex: ChatGPT token rejected ({status}) -- run `codex login`",
|
|
311
|
+
llm_provider=PROVIDER, model=model)
|
|
312
|
+
if status == 429:
|
|
313
|
+
raise litellm.RateLimitError(
|
|
314
|
+
f"codex: {text}", llm_provider=PROVIDER, model=model)
|
|
315
|
+
if status == 400:
|
|
316
|
+
raise litellm.BadRequestError(
|
|
317
|
+
f"codex: {text}", model=model, llm_provider=PROVIDER)
|
|
318
|
+
raise litellm.APIError(
|
|
319
|
+
status_code=status, message=f"codex: {text}",
|
|
320
|
+
llm_provider=PROVIDER, model=model)
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
class CodexLLM(CustomLLM):
|
|
324
|
+
def completion(self, model, messages, api_base, custom_prompt_dict,
|
|
325
|
+
model_response, print_verbose, encoding, api_key, logging_obj,
|
|
326
|
+
optional_params, acompletion=None, litellm_params=None,
|
|
327
|
+
logger_fn=None, headers=None, timeout=None, client=None):
|
|
328
|
+
token, account_id = _auth(model)
|
|
329
|
+
wire_model = model[len(MODEL_PREFIX):] if model.startswith(MODEL_PREFIX) else model
|
|
330
|
+
instructions, items = _to_input(messages)
|
|
331
|
+
body = {
|
|
332
|
+
"model": wire_model,
|
|
333
|
+
"instructions": instructions,
|
|
334
|
+
"input": items,
|
|
335
|
+
# Both are required, not preferences: the endpoint refuses a
|
|
336
|
+
# non-streaming request outright, and `store` is what keeps the
|
|
337
|
+
# conversation out of OpenAI-side retention.
|
|
338
|
+
"stream": True,
|
|
339
|
+
"store": False,
|
|
340
|
+
}
|
|
341
|
+
tools = _to_tools(optional_params.get("tools") if optional_params else None)
|
|
342
|
+
if tools:
|
|
343
|
+
body["tools"] = tools
|
|
344
|
+
body["tool_choice"] = optional_params.get("tool_choice") or "auto"
|
|
345
|
+
|
|
346
|
+
secs = timeout if isinstance(timeout, (int, float)) else _DEFAULT_TIMEOUT
|
|
347
|
+
try:
|
|
348
|
+
resp = httpx.post(_ENDPOINT, json=body,
|
|
349
|
+
headers=_headers(token, account_id), timeout=secs)
|
|
350
|
+
# Never litellm.APIConnectionError: the Router skips cooldown for any
|
|
351
|
+
# error whose text contains that name, so a hung or unreachable codex
|
|
352
|
+
# was dialled twice on every call (num_retries=1), each attempt paying
|
|
353
|
+
# the full rung timeout. A Timeout (408) and a 500 are what litellm
|
|
354
|
+
# raises for an HTTP rung in the same state, and both are cooled.
|
|
355
|
+
except httpx.TimeoutException as exc:
|
|
356
|
+
raise litellm.Timeout(
|
|
357
|
+
message=f"codex: {type(exc).__name__}",
|
|
358
|
+
model=model, llm_provider=PROVIDER)
|
|
359
|
+
except httpx.HTTPError as exc:
|
|
360
|
+
raise litellm.InternalServerError(
|
|
361
|
+
message=f"codex: {type(exc).__name__}",
|
|
362
|
+
llm_provider=PROVIDER, model=model)
|
|
363
|
+
if resp.status_code != 200:
|
|
364
|
+
_raise_for(resp.status_code, resp.text, model)
|
|
365
|
+
|
|
366
|
+
content, tool_calls, usage = _parse(resp.text)
|
|
367
|
+
choice = model_response.choices[0]
|
|
368
|
+
choice.message = Message(
|
|
369
|
+
role="assistant",
|
|
370
|
+
content=content or None,
|
|
371
|
+
tool_calls=tool_calls or None,
|
|
372
|
+
)
|
|
373
|
+
choice.finish_reason = "tool_calls" if tool_calls else "stop"
|
|
374
|
+
model_response.model = f"{PROVIDER}/{model}"
|
|
375
|
+
if usage:
|
|
376
|
+
model_response.usage = Usage(
|
|
377
|
+
prompt_tokens=usage.get("input_tokens") or 0,
|
|
378
|
+
completion_tokens=usage.get("output_tokens") or 0,
|
|
379
|
+
total_tokens=usage.get("total_tokens") or 0,
|
|
380
|
+
)
|
|
381
|
+
retval = model_response
|
|
382
|
+
return retval
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
_HANDLER = CodexLLM()
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def register():
|
|
389
|
+
"""Teach litellm the `codex/` prefix, once. `custom_provider_map` is global
|
|
390
|
+
and a duplicate entry would shadow itself on every rebuild of the Router.
|
|
391
|
+
|
|
392
|
+
`custom_llm_setup()` is the second half and is not optional: the map alone
|
|
393
|
+
only tells litellm how to *call* the provider, while the provider *list* is
|
|
394
|
+
what lets it recognise the prefix at all. Without it the Router rejects the
|
|
395
|
+
row at construction time with "LLM Provider NOT provided", because it
|
|
396
|
+
resolves every deployment's provider before any completion is attempted."""
|
|
397
|
+
if not any(e.get("provider") == PROVIDER for e in litellm.custom_provider_map):
|
|
398
|
+
litellm.custom_provider_map = list(litellm.custom_provider_map) + [
|
|
399
|
+
{"provider": PROVIDER, "custom_handler": _HANDLER}
|
|
400
|
+
]
|
|
401
|
+
custom_llm_setup()
|
framework/config.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Config loading for the `agent run` entrypoint.
|
|
2
|
+
|
|
3
|
+
An agent is declared by a *workspace*: one directory per deployed agent, outside
|
|
4
|
+
any git checkout, holding everything the agent owns at runtime (issue #43):
|
|
5
|
+
|
|
6
|
+
<root>/
|
|
7
|
+
_shared/ cross-agent files; llm.json is the LLM waterfall (framework/llm.py)
|
|
8
|
+
<agent-name>/ the workspace
|
|
9
|
+
config.json the agent's declaration; the only file a human edits
|
|
10
|
+
state/ SeenStore and any other per-agent state
|
|
11
|
+
logs/ stdout/stderr when scheduled
|
|
12
|
+
|
|
13
|
+
`config.json` is a single agent's declaration: which source/scorer/destination
|
|
14
|
+
to build, plus each plugin's own settings. The framework validates only the
|
|
15
|
+
shape it needs to resolve plugins; everything else in a component block is
|
|
16
|
+
opaque and handed to that plugin's factory verbatim (see docs/PLUGIN-CONTRACT.md).
|
|
17
|
+
|
|
18
|
+
Config is JSON, not YAML. YAML was the original format, but the only thing it
|
|
19
|
+
bought was comments, and those comments were where decisions went to be lost
|
|
20
|
+
(nothing could read them back). JSON is in the standard library, so the
|
|
21
|
+
framework has one fewer dependency to break a fresh venv, and a comment worth
|
|
22
|
+
keeping is written as a `"_comment"` key the framework ignores.
|
|
23
|
+
|
|
24
|
+
The workspaces root (the parent of a workspace, where `_shared/` lives) is only
|
|
25
|
+
resolved by name for helpers that take an agent *name* rather than a path;
|
|
26
|
+
`agent run` always takes the explicit `--workspace` path and derives `root`
|
|
27
|
+
from it.
|
|
28
|
+
"""
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import json
|
|
32
|
+
import os
|
|
33
|
+
from dataclasses import dataclass
|
|
34
|
+
from pathlib import Path
|
|
35
|
+
from typing import Any
|
|
36
|
+
|
|
37
|
+
CONFIG_FILENAME = "config.json"
|
|
38
|
+
STATE_DIRNAME = "state"
|
|
39
|
+
SEEN_FILENAME = "seen.json"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class ConfigError(ValueError):
|
|
43
|
+
"""Raised when a config file is missing required framework-level shape."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass
|
|
47
|
+
class AgentConfig:
|
|
48
|
+
"""Parsed, framework-validated view of one agent's workspace config."""
|
|
49
|
+
|
|
50
|
+
agent: str
|
|
51
|
+
source: dict[str, Any]
|
|
52
|
+
scorer: dict[str, Any]
|
|
53
|
+
destination: dict[str, Any]
|
|
54
|
+
path: Path
|
|
55
|
+
workspace: Path
|
|
56
|
+
root: Path
|
|
57
|
+
raw: dict[str, Any]
|
|
58
|
+
|
|
59
|
+
@property
|
|
60
|
+
def dir(self) -> Path:
|
|
61
|
+
"""Alias of `workspace`, kept so pre-workspace callers still resolve."""
|
|
62
|
+
retval = self.workspace
|
|
63
|
+
return retval
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def default_state_path(self) -> Path:
|
|
67
|
+
retval = self.workspace / STATE_DIRNAME / SEEN_FILENAME
|
|
68
|
+
return retval
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def default_workspaces_root() -> Path:
|
|
72
|
+
"""Where workspaces live when only an agent name is given.
|
|
73
|
+
|
|
74
|
+
`$AGENT_WORKSPACES_ROOT`, else `~/agent-workspaces`. `agent run` never uses
|
|
75
|
+
this: it takes an explicit `--workspace` path.
|
|
76
|
+
"""
|
|
77
|
+
configured = os.environ.get("AGENT_WORKSPACES_ROOT")
|
|
78
|
+
if configured:
|
|
79
|
+
retval = Path(configured).expanduser().resolve()
|
|
80
|
+
else:
|
|
81
|
+
retval = (Path.home() / "agent-workspaces").resolve()
|
|
82
|
+
return retval
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _require_component(raw: dict[str, Any], key: str, path: Path) -> dict[str, Any]:
|
|
86
|
+
block = raw.get(key)
|
|
87
|
+
if not isinstance(block, dict):
|
|
88
|
+
raise ConfigError(f"{path}: '{key}' must be an object with a 'type' key")
|
|
89
|
+
if not block.get("type"):
|
|
90
|
+
raise ConfigError(f"{path}: '{key}.type' is required")
|
|
91
|
+
return block
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def load_workspace(workspace: str | Path) -> AgentConfig:
|
|
95
|
+
"""Load and framework-validate `<workspace>/config.json`."""
|
|
96
|
+
workspace_path = Path(workspace).expanduser().resolve()
|
|
97
|
+
if not workspace_path.is_dir():
|
|
98
|
+
raise ConfigError(f"workspace directory not found: {workspace_path}")
|
|
99
|
+
config_path = workspace_path / CONFIG_FILENAME
|
|
100
|
+
if not config_path.is_file():
|
|
101
|
+
raise ConfigError(f"config file not found: {config_path}")
|
|
102
|
+
|
|
103
|
+
try:
|
|
104
|
+
loaded = json.loads(config_path.read_text())
|
|
105
|
+
except json.JSONDecodeError as exc:
|
|
106
|
+
raise ConfigError(
|
|
107
|
+
f"{config_path}: invalid JSON at line {exc.lineno} column {exc.colno}: {exc.msg}"
|
|
108
|
+
) from exc
|
|
109
|
+
if not isinstance(loaded, dict):
|
|
110
|
+
raise ConfigError(f"{config_path}: top level must be an object")
|
|
111
|
+
|
|
112
|
+
agent = loaded.get("agent")
|
|
113
|
+
if not agent:
|
|
114
|
+
raise ConfigError(f"{config_path}: 'agent' (name) is required")
|
|
115
|
+
|
|
116
|
+
retval = AgentConfig(
|
|
117
|
+
agent=str(agent),
|
|
118
|
+
source=_require_component(loaded, "source", config_path),
|
|
119
|
+
scorer=_require_component(loaded, "scorer", config_path),
|
|
120
|
+
destination=_require_component(loaded, "destination", config_path),
|
|
121
|
+
path=config_path,
|
|
122
|
+
workspace=workspace_path,
|
|
123
|
+
root=workspace_path.parent,
|
|
124
|
+
raw=loaded,
|
|
125
|
+
)
|
|
126
|
+
return retval
|