agentplaykit 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.
- agentplaykit/__init__.py +4 -0
- agentplaykit/__main__.py +4 -0
- agentplaykit/agents/__init__.py +1 -0
- agentplaykit/agents/_http.py +180 -0
- agentplaykit/agents/anthropic_agent.py +156 -0
- agentplaykit/agents/command.py +144 -0
- agentplaykit/agents/config.py +67 -0
- agentplaykit/agents/http_agent.py +56 -0
- agentplaykit/agents/mcp_agent.py +86 -0
- agentplaykit/agents/openai_compat.py +161 -0
- agentplaykit/agents/pricing.py +29 -0
- agentplaykit/agents/proc.py +55 -0
- agentplaykit/agents/prompting.py +124 -0
- agentplaykit/agents/scripted.py +82 -0
- agentplaykit/cli/__init__.py +1 -0
- agentplaykit/cli/main.py +276 -0
- agentplaykit/core/__init__.py +44 -0
- agentplaykit/core/agent.py +51 -0
- agentplaykit/core/bus.py +95 -0
- agentplaykit/core/environment.py +111 -0
- agentplaykit/core/evaluator.py +111 -0
- agentplaykit/core/log.py +122 -0
- agentplaykit/core/plain.py +41 -0
- agentplaykit/core/runner.py +429 -0
- agentplaykit/envs/__init__.py +1 -0
- agentplaykit/envs/blank.py +51 -0
- agentplaykit/envs/ox.py +67 -0
- agentplaykit/envs/rps.py +77 -0
- agentplaykit/evals/__init__.py +1 -0
- agentplaykit/evals/judge.py +167 -0
- agentplaykit/evals/outcome.py +59 -0
- agentplaykit/evals/summary.py +136 -0
- agentplaykit/py.typed +0 -0
- agentplaykit/registry/__init__.py +342 -0
- agentplaykit/scenario/__init__.py +496 -0
- agentplaykit/scenarios/demo.yaml +8 -0
- agentplaykit/schemas/evalresult.schema.json +84 -0
- agentplaykit/schemas/runlog.schema.json +572 -0
- agentplaykit/schemas/scenario.schema.json +152 -0
- agentplaykit/testkit.py +383 -0
- agentplaykit-0.1.0.dist-info/METADATA +123 -0
- agentplaykit-0.1.0.dist-info/RECORD +45 -0
- agentplaykit-0.1.0.dist-info/WHEEL +4 -0
- agentplaykit-0.1.0.dist-info/entry_points.txt +2 -0
- agentplaykit-0.1.0.dist-info/licenses/LICENSE +21 -0
agentplaykit/__init__.py
ADDED
agentplaykit/__main__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""HTTP and retry helpers for the adapters (ADP-012). Standard library only."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import http.client
|
|
7
|
+
import json
|
|
8
|
+
import random
|
|
9
|
+
import socket
|
|
10
|
+
import urllib.error
|
|
11
|
+
import urllib.request
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple
|
|
14
|
+
|
|
15
|
+
from agentplaykit.core import ProviderError
|
|
16
|
+
|
|
17
|
+
Transport = Callable[[str, Dict[str, str], bytes, float], Tuple[int, Dict[str, str], bytes]]
|
|
18
|
+
RETRYABLE_STATUS = {408, 409, 425, 429}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class Failure:
|
|
23
|
+
retryable: bool
|
|
24
|
+
message: str
|
|
25
|
+
retry_after: Optional[float] = None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def scrub(text: str, secrets: Sequence[str]) -> str:
|
|
29
|
+
for s in secrets:
|
|
30
|
+
if s:
|
|
31
|
+
text = text.replace(s, "[REDACTED]")
|
|
32
|
+
return text
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def retry_after(headers: Any) -> Optional[float]:
|
|
36
|
+
"""Seconds from a Retry-After header (case-insensitive), if it is a number."""
|
|
37
|
+
items = headers.items() if isinstance(headers, Mapping) or hasattr(headers, "items") else []
|
|
38
|
+
for key, value in items:
|
|
39
|
+
if str(key).lower() == "retry-after":
|
|
40
|
+
try:
|
|
41
|
+
return max(0.0, float(value))
|
|
42
|
+
except (TypeError, ValueError):
|
|
43
|
+
return None
|
|
44
|
+
return None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def call_with_retries(
|
|
48
|
+
fn: Callable[[], Any],
|
|
49
|
+
classify: Callable[[BaseException], Optional[Failure]],
|
|
50
|
+
*,
|
|
51
|
+
retries: int,
|
|
52
|
+
sleep: Callable[[float], None],
|
|
53
|
+
) -> Tuple[Any, List[Dict[str, Any]]]:
|
|
54
|
+
"""Run `fn`, retrying retryable failures with backoff and jitter; honors Retry-After.
|
|
55
|
+
|
|
56
|
+
Returns (result, history) where history lists the failed attempts (AGT-015).
|
|
57
|
+
Raises ProviderError when attempts run out or the failure is not retryable.
|
|
58
|
+
"""
|
|
59
|
+
history: List[Dict[str, Any]] = []
|
|
60
|
+
attempt = 0
|
|
61
|
+
while True:
|
|
62
|
+
attempt += 1
|
|
63
|
+
try:
|
|
64
|
+
return fn(), history
|
|
65
|
+
except Exception as exc:
|
|
66
|
+
failure = classify(exc)
|
|
67
|
+
if failure is None:
|
|
68
|
+
raise
|
|
69
|
+
if not failure.retryable or attempt > retries:
|
|
70
|
+
raise ProviderError(
|
|
71
|
+
failure.message, retryable=failure.retryable, attempt=attempt
|
|
72
|
+
) from exc
|
|
73
|
+
history.append({"attempt": attempt, "message": failure.message})
|
|
74
|
+
delay = failure.retry_after
|
|
75
|
+
if delay is None:
|
|
76
|
+
delay = 0.5 * 2 ** (attempt - 1) + random.uniform(0, 0.5)
|
|
77
|
+
sleep(min(delay, 60.0))
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
81
|
+
"""Never follow redirects: a key must only go to the host the user named (SEC-008)."""
|
|
82
|
+
|
|
83
|
+
def redirect_request(self, *args: Any, **kwargs: Any) -> None:
|
|
84
|
+
return None
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
_OPENER = urllib.request.build_opener(_NoRedirect)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def urllib_transport(
|
|
91
|
+
url: str, headers: Dict[str, str], body: bytes, timeout: float
|
|
92
|
+
) -> Tuple[int, Dict[str, str], bytes]:
|
|
93
|
+
req = urllib.request.Request(url, data=body, headers=headers, method="POST")
|
|
94
|
+
try:
|
|
95
|
+
with _OPENER.open(req, timeout=timeout) as resp:
|
|
96
|
+
return resp.status, dict(resp.headers), resp.read()
|
|
97
|
+
except urllib.error.HTTPError as err:
|
|
98
|
+
return err.code, dict(err.headers or {}), err.read()
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class _StatusError(Exception):
|
|
102
|
+
def __init__(self, status: int, headers: Dict[str, str], body: bytes) -> None:
|
|
103
|
+
super().__init__(status)
|
|
104
|
+
self.status, self.headers, self.body = status, headers, body
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class _NotJsonError(Exception):
|
|
108
|
+
pass
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def error_text(body: bytes) -> str:
|
|
112
|
+
try:
|
|
113
|
+
data = json.loads(body)
|
|
114
|
+
except ValueError:
|
|
115
|
+
return body.decode("utf-8", "replace").strip()[:300] or "(empty body)"
|
|
116
|
+
if isinstance(data, dict):
|
|
117
|
+
err = data.get("error", data.get("message", data))
|
|
118
|
+
if isinstance(err, dict):
|
|
119
|
+
err = err.get("message", err)
|
|
120
|
+
return str(err)[:300]
|
|
121
|
+
return str(data)[:300]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def post_json(
|
|
125
|
+
url: str,
|
|
126
|
+
payload: Any,
|
|
127
|
+
*,
|
|
128
|
+
headers: Dict[str, str],
|
|
129
|
+
timeout: float,
|
|
130
|
+
retries: int,
|
|
131
|
+
sleep: Callable[[float], None],
|
|
132
|
+
transport: Transport,
|
|
133
|
+
secrets: Sequence[str] = (),
|
|
134
|
+
server: Optional[str] = None,
|
|
135
|
+
) -> Tuple[Any, List[Dict[str, Any]]]:
|
|
136
|
+
"""POST JSON and return (parsed JSON, retry history). `server` names the base URL in hints."""
|
|
137
|
+
body = json.dumps(payload).encode("utf-8")
|
|
138
|
+
all_headers = {"Content-Type": "application/json", "Accept": "application/json", **headers}
|
|
139
|
+
where = server or url
|
|
140
|
+
|
|
141
|
+
def once() -> Any:
|
|
142
|
+
status, resp_headers, raw = transport(url, all_headers, body, timeout)
|
|
143
|
+
if not 200 <= status < 300:
|
|
144
|
+
raise _StatusError(status, resp_headers, raw)
|
|
145
|
+
try:
|
|
146
|
+
return json.loads(raw)
|
|
147
|
+
except ValueError as exc:
|
|
148
|
+
raise _NotJsonError(raw[:200].decode("utf-8", "replace")) from exc
|
|
149
|
+
|
|
150
|
+
def classify(exc: BaseException) -> Optional[Failure]:
|
|
151
|
+
if isinstance(exc, _StatusError) and 300 <= exc.status < 400:
|
|
152
|
+
location = next((v for k, v in exc.headers.items() if k.lower() == "location"), "?")
|
|
153
|
+
return Failure(
|
|
154
|
+
False,
|
|
155
|
+
f"{exc.status} redirect from {url} to {location}; redirects are not followed so "
|
|
156
|
+
"keys are never sent to another host (set the URL to the final address)",
|
|
157
|
+
)
|
|
158
|
+
if isinstance(exc, _StatusError):
|
|
159
|
+
message = f"{exc.status} from {url}: {error_text(exc.body)}"
|
|
160
|
+
if exc.status in (401, 403):
|
|
161
|
+
message += " (check the API key)"
|
|
162
|
+
retryable = exc.status in RETRYABLE_STATUS or exc.status >= 500
|
|
163
|
+
return Failure(retryable, scrub(message, secrets), retry_after(exc.headers))
|
|
164
|
+
if isinstance(exc, _NotJsonError):
|
|
165
|
+
return Failure(False, scrub(f"response from {url} was not JSON: {exc}", secrets))
|
|
166
|
+
if isinstance(exc, (socket.timeout, TimeoutError)):
|
|
167
|
+
return Failure(True, f"no response from {where} within {timeout:g} s")
|
|
168
|
+
if isinstance(exc, (urllib.error.URLError, OSError, http.client.HTTPException)):
|
|
169
|
+
reason = getattr(exc, "reason", exc)
|
|
170
|
+
if isinstance(reason, (socket.timeout, TimeoutError)):
|
|
171
|
+
return Failure(True, f"no response from {where} within {timeout:g} s")
|
|
172
|
+
if isinstance(reason, ConnectionRefusedError) or "refused" in str(reason).lower():
|
|
173
|
+
return Failure(
|
|
174
|
+
True,
|
|
175
|
+
f"cannot reach {where}: connection refused; is the server at {where} running?",
|
|
176
|
+
)
|
|
177
|
+
return Failure(True, scrub(f"cannot reach {where}: {reason}", secrets))
|
|
178
|
+
return None
|
|
179
|
+
|
|
180
|
+
return call_with_retries(once, classify, retries=retries, sleep=sleep)
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""Claude models through the official Anthropic SDK (ADP-005, ADP-018).
|
|
3
|
+
|
|
4
|
+
Install with: pip install "agentplaykit[anthropic]". Config:
|
|
5
|
+
|
|
6
|
+
model (required) a Claude model id
|
|
7
|
+
api_key_env env var holding the key (default: the SDK's own credential lookup)
|
|
8
|
+
price {input_per_mtok, output_per_mtok} in USD (no built-in prices)
|
|
9
|
+
tool_calls default true (tool_choice auto; text is parsed as a fallback)
|
|
10
|
+
max_output_tokens default 16000
|
|
11
|
+
temperature, top_p sent only when set (some models reject them)
|
|
12
|
+
timeout_s, retries defaults 600 and 2
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import time
|
|
18
|
+
from typing import Any, Callable, Dict, List, Optional
|
|
19
|
+
|
|
20
|
+
from agentplaykit.agents._http import Failure, call_with_retries, retry_after, scrub
|
|
21
|
+
from agentplaykit.agents.config import ConfigError, check_price, read_key, require
|
|
22
|
+
from agentplaykit.agents.pricing import cost_usd
|
|
23
|
+
from agentplaykit.agents.prompting import (
|
|
24
|
+
ACT_DESCRIPTION,
|
|
25
|
+
ACT_SCHEMA,
|
|
26
|
+
build_prompt,
|
|
27
|
+
parse_text_reply,
|
|
28
|
+
reply_from,
|
|
29
|
+
)
|
|
30
|
+
from agentplaykit.core import Agent, AgentError
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class AnthropicAgent(Agent):
|
|
34
|
+
kind = "anthropic"
|
|
35
|
+
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
config: Optional[Dict[str, Any]] = None,
|
|
39
|
+
*,
|
|
40
|
+
client: Any = None,
|
|
41
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
42
|
+
) -> None:
|
|
43
|
+
super().__init__(config)
|
|
44
|
+
c = self.config
|
|
45
|
+
self.model = require(c, "model", "anthropic", "<Claude model id>")
|
|
46
|
+
self.key = read_key(c.get("api_key_env"))
|
|
47
|
+
self.price = check_price(c.get("price"))
|
|
48
|
+
self.sleep = sleep
|
|
49
|
+
if client is None:
|
|
50
|
+
try:
|
|
51
|
+
import anthropic
|
|
52
|
+
except ImportError as exc:
|
|
53
|
+
raise ImportError(
|
|
54
|
+
"the anthropic adapter needs the Anthropic SDK: "
|
|
55
|
+
'pip install "agentplaykit[anthropic]"'
|
|
56
|
+
) from exc
|
|
57
|
+
kwargs: Dict[str, Any] = {"max_retries": 0, "timeout": float(c.get("timeout_s", 600))}
|
|
58
|
+
if self.key:
|
|
59
|
+
kwargs["api_key"] = self.key
|
|
60
|
+
try:
|
|
61
|
+
client = anthropic.Anthropic(**kwargs)
|
|
62
|
+
except Exception as exc: # e.g. no credentials found
|
|
63
|
+
raise ConfigError(
|
|
64
|
+
f"cannot create the Anthropic client: {exc}",
|
|
65
|
+
"set api_key_env to the variable holding your key (e.g. ANTHROPIC_API_KEY)",
|
|
66
|
+
) from exc
|
|
67
|
+
self.client = client
|
|
68
|
+
|
|
69
|
+
def capabilities(self) -> Dict[str, bool]:
|
|
70
|
+
return {
|
|
71
|
+
"tool_calls": bool(self.config.get("tool_calls", True)),
|
|
72
|
+
"vision": False,
|
|
73
|
+
"json_mode": False,
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
def secrets(self) -> List[str]:
|
|
77
|
+
return [self.key] if self.key else []
|
|
78
|
+
|
|
79
|
+
def _classify(self, exc: BaseException) -> Optional[Failure]:
|
|
80
|
+
status = getattr(exc, "status_code", None)
|
|
81
|
+
if isinstance(status, int):
|
|
82
|
+
text = getattr(exc, "message", None) or str(exc)
|
|
83
|
+
headers = getattr(getattr(exc, "response", None), "headers", None) or {}
|
|
84
|
+
retryable = status in (408, 409, 429) or status >= 500
|
|
85
|
+
return Failure(
|
|
86
|
+
retryable,
|
|
87
|
+
scrub(f"{status} from the Anthropic API: {text}", self.secrets()),
|
|
88
|
+
retry_after(headers),
|
|
89
|
+
)
|
|
90
|
+
name = type(exc).__name__
|
|
91
|
+
if "Connection" in name or "Timeout" in name:
|
|
92
|
+
return Failure(True, scrub(f"cannot reach the Anthropic API: {exc}", self.secrets()))
|
|
93
|
+
return None
|
|
94
|
+
|
|
95
|
+
def act(self, request: Dict[str, Any]) -> Dict[str, Any]:
|
|
96
|
+
c = self.config
|
|
97
|
+
system, user = build_prompt(request)
|
|
98
|
+
kwargs: Dict[str, Any] = {
|
|
99
|
+
"model": self.model,
|
|
100
|
+
"max_tokens": int(c.get("max_output_tokens", 16000)),
|
|
101
|
+
"system": system,
|
|
102
|
+
"messages": [{"role": "user", "content": user}],
|
|
103
|
+
}
|
|
104
|
+
if c.get("tool_calls", True):
|
|
105
|
+
kwargs["tools"] = [
|
|
106
|
+
{"name": "act", "description": ACT_DESCRIPTION, "input_schema": ACT_SCHEMA}
|
|
107
|
+
]
|
|
108
|
+
kwargs["tool_choice"] = {
|
|
109
|
+
"type": "auto"
|
|
110
|
+
} # forced tool choice is rejected by some models
|
|
111
|
+
for key in ("temperature", "top_p"):
|
|
112
|
+
if key in c:
|
|
113
|
+
kwargs[key] = c[key]
|
|
114
|
+
|
|
115
|
+
response, retries = call_with_retries(
|
|
116
|
+
lambda: self.client.messages.create(**kwargs),
|
|
117
|
+
self._classify,
|
|
118
|
+
retries=int(c.get("retries", 2)),
|
|
119
|
+
sleep=self.sleep,
|
|
120
|
+
)
|
|
121
|
+
if getattr(response, "stop_reason", None) == "refusal":
|
|
122
|
+
details = getattr(response, "stop_details", None)
|
|
123
|
+
category = getattr(details, "category", None) if details is not None else None
|
|
124
|
+
raise AgentError(f"the model refused (category: {category or 'unspecified'})")
|
|
125
|
+
|
|
126
|
+
actions = request.get("actions")
|
|
127
|
+
reply: Optional[Dict[str, Any]] = None
|
|
128
|
+
texts: List[str] = []
|
|
129
|
+
for block in getattr(response, "content", None) or []:
|
|
130
|
+
kind = getattr(block, "type", None)
|
|
131
|
+
if kind == "tool_use" and getattr(block, "name", None) == "act":
|
|
132
|
+
data = getattr(block, "input", None)
|
|
133
|
+
if isinstance(data, dict) and "action" in data:
|
|
134
|
+
reply = reply_from(data, actions)
|
|
135
|
+
break
|
|
136
|
+
elif kind == "text":
|
|
137
|
+
texts.append(getattr(block, "text", ""))
|
|
138
|
+
mode = "tool" if reply is not None else "text"
|
|
139
|
+
if reply is None:
|
|
140
|
+
reply = parse_text_reply("\n".join(texts), actions)
|
|
141
|
+
|
|
142
|
+
usage = getattr(response, "usage", None)
|
|
143
|
+
in_tokens = int(getattr(usage, "input_tokens", 0) or 0)
|
|
144
|
+
out_tokens = int(getattr(usage, "output_tokens", 0) or 0)
|
|
145
|
+
reply["usage"] = {
|
|
146
|
+
"input_tokens": in_tokens,
|
|
147
|
+
"output_tokens": out_tokens,
|
|
148
|
+
"cost_usd": cost_usd(self.price, in_tokens, out_tokens, local=False),
|
|
149
|
+
}
|
|
150
|
+
reply["meta"] = {
|
|
151
|
+
"provider": "anthropic",
|
|
152
|
+
"model": getattr(response, "model", None) or self.model,
|
|
153
|
+
"mode": mode,
|
|
154
|
+
"retries": retries,
|
|
155
|
+
}
|
|
156
|
+
return reply
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""Any local program as an agent, speaking JSON lines (ADP-004, ADP-015).
|
|
3
|
+
|
|
4
|
+
The program is started once per episode and kept running. Each turn AgentPlay writes one
|
|
5
|
+
Request as a line of JSON to its stdin and reads one Reply line from its stdout. The
|
|
6
|
+
environment variables AGENTPLAYKIT_SEED and AGENTPLAYKIT_AGENT_ID are set. Config:
|
|
7
|
+
|
|
8
|
+
command (required) a list such as ["python", "my_agent.py"] (no shell is used);
|
|
9
|
+
"python" means the interpreter running AgentPlay
|
|
10
|
+
timeout_s seconds to wait for each reply (default 60)
|
|
11
|
+
cwd working directory for the program
|
|
12
|
+
pass_env environment variables to pass through (default: none beyond the
|
|
13
|
+
minimal set; API keys are never passed unless listed here)
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import json
|
|
19
|
+
import queue
|
|
20
|
+
import shlex
|
|
21
|
+
import subprocess
|
|
22
|
+
import sys
|
|
23
|
+
import threading
|
|
24
|
+
from collections import deque
|
|
25
|
+
from typing import IO, Any, Deque, Dict, List, Optional
|
|
26
|
+
|
|
27
|
+
from agentplaykit.agents.config import ConfigError
|
|
28
|
+
from agentplaykit.agents.proc import check_pass_env, minimal_env
|
|
29
|
+
from agentplaykit.core import Agent, AgentError, ProviderError
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class CommandAgent(Agent):
|
|
33
|
+
kind = "command"
|
|
34
|
+
|
|
35
|
+
def __init__(self, config: Optional[Dict[str, Any]] = None) -> None:
|
|
36
|
+
super().__init__(config)
|
|
37
|
+
command = self.config.get("command")
|
|
38
|
+
if isinstance(command, str):
|
|
39
|
+
command = shlex.split(command)
|
|
40
|
+
if (
|
|
41
|
+
not isinstance(command, list)
|
|
42
|
+
or not command
|
|
43
|
+
or not all(isinstance(x, str) for x in command)
|
|
44
|
+
):
|
|
45
|
+
raise ConfigError(
|
|
46
|
+
'the command adapter needs "command" in its config',
|
|
47
|
+
'add "command: [python, my_agent.py]" under the agent\'s config',
|
|
48
|
+
)
|
|
49
|
+
if command[0] == "python": # the interpreter running AgentPlay; "python" may not exist
|
|
50
|
+
command = [sys.executable, *command[1:]]
|
|
51
|
+
self.command: List[str] = command
|
|
52
|
+
self.timeout = float(self.config.get("timeout_s", 60))
|
|
53
|
+
self.cwd = self.config.get("cwd")
|
|
54
|
+
self.pass_env = check_pass_env(self.config.get("pass_env"))
|
|
55
|
+
self.process: Optional[subprocess.Popen] = None # type: ignore[type-arg]
|
|
56
|
+
self.seed = 0
|
|
57
|
+
self.agent_id = ""
|
|
58
|
+
|
|
59
|
+
def reset(self, seed: int, agent_id: str) -> None:
|
|
60
|
+
self.close()
|
|
61
|
+
self.seed, self.agent_id = seed, agent_id
|
|
62
|
+
|
|
63
|
+
def _start(self) -> None:
|
|
64
|
+
env = minimal_env( # SEC-010: no API keys unless listed in pass_env
|
|
65
|
+
self.pass_env, AGENTPLAYKIT_SEED=str(self.seed), AGENTPLAYKIT_AGENT_ID=self.agent_id
|
|
66
|
+
)
|
|
67
|
+
try:
|
|
68
|
+
proc = subprocess.Popen( # noqa: S603 (no shell; the user chose the program)
|
|
69
|
+
self.command,
|
|
70
|
+
stdin=subprocess.PIPE,
|
|
71
|
+
stdout=subprocess.PIPE,
|
|
72
|
+
stderr=subprocess.PIPE,
|
|
73
|
+
cwd=self.cwd,
|
|
74
|
+
env=env,
|
|
75
|
+
text=True,
|
|
76
|
+
encoding="utf-8",
|
|
77
|
+
bufsize=1,
|
|
78
|
+
)
|
|
79
|
+
except OSError as exc:
|
|
80
|
+
raise ProviderError(
|
|
81
|
+
f"cannot start agent program {self.command[0]!r}: {exc}", retryable=False
|
|
82
|
+
) from exc
|
|
83
|
+
self.lines: queue.Queue[Optional[str]] = queue.Queue()
|
|
84
|
+
self.stderr_tail: Deque[str] = deque(maxlen=20)
|
|
85
|
+
self._out = threading.Thread(target=self._pump, args=(proc.stdout,), daemon=True)
|
|
86
|
+
self._err = threading.Thread(target=self._drain, args=(proc.stderr,), daemon=True)
|
|
87
|
+
self._out.start()
|
|
88
|
+
self._err.start()
|
|
89
|
+
self.process = proc
|
|
90
|
+
|
|
91
|
+
def _pump(self, stream: IO[str]) -> None:
|
|
92
|
+
for line in stream:
|
|
93
|
+
if line.strip():
|
|
94
|
+
self.lines.put(line)
|
|
95
|
+
self.lines.put(None)
|
|
96
|
+
|
|
97
|
+
def _drain(self, stream: IO[str]) -> None:
|
|
98
|
+
for line in stream:
|
|
99
|
+
self.stderr_tail.append(line.rstrip())
|
|
100
|
+
|
|
101
|
+
def act(self, request: Dict[str, Any]) -> Dict[str, Any]:
|
|
102
|
+
if self.process is None or self.process.poll() is not None:
|
|
103
|
+
self._start()
|
|
104
|
+
proc = self.process
|
|
105
|
+
assert proc is not None and proc.stdin is not None
|
|
106
|
+
try:
|
|
107
|
+
proc.stdin.write(json.dumps(request) + "\n")
|
|
108
|
+
proc.stdin.flush()
|
|
109
|
+
except OSError:
|
|
110
|
+
pass # the process died; reading below reports it
|
|
111
|
+
try:
|
|
112
|
+
line = self.lines.get(timeout=self.timeout)
|
|
113
|
+
except queue.Empty:
|
|
114
|
+
self.close()
|
|
115
|
+
raise AgentError(f"no reply within {self.timeout:g} s from {self.command[0]}") from None
|
|
116
|
+
if line is None:
|
|
117
|
+
code = proc.wait(timeout=5)
|
|
118
|
+
self._err.join(timeout=2)
|
|
119
|
+
self.process = None
|
|
120
|
+
tail = " | ".join(self.stderr_tail)
|
|
121
|
+
raise AgentError(
|
|
122
|
+
f"agent program exited with code {code}" + (f"; stderr: {tail}" if tail else "")
|
|
123
|
+
)
|
|
124
|
+
try:
|
|
125
|
+
reply = json.loads(line)
|
|
126
|
+
except ValueError as exc:
|
|
127
|
+
raise AgentError(
|
|
128
|
+
f"agent program printed a line that is not JSON: {line.strip()[:200]!r}"
|
|
129
|
+
) from exc
|
|
130
|
+
if not isinstance(reply, dict):
|
|
131
|
+
raise AgentError("agent program must print one JSON object per line")
|
|
132
|
+
return reply
|
|
133
|
+
|
|
134
|
+
def close(self) -> None:
|
|
135
|
+
proc, self.process = self.process, None
|
|
136
|
+
if proc is None:
|
|
137
|
+
return
|
|
138
|
+
try:
|
|
139
|
+
if proc.stdin:
|
|
140
|
+
proc.stdin.close()
|
|
141
|
+
proc.wait(timeout=1)
|
|
142
|
+
except Exception:
|
|
143
|
+
proc.kill()
|
|
144
|
+
proc.wait(timeout=5)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""Config helpers shared by the adapters (ADP-008)."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
from typing import Any, Dict, Optional
|
|
8
|
+
from urllib.parse import urlparse
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ConfigError(ValueError):
|
|
12
|
+
"""A problem in an agent's config. `fix` tells the user what to do."""
|
|
13
|
+
|
|
14
|
+
def __init__(self, message: str, fix: str = "fix the agent's config") -> None:
|
|
15
|
+
super().__init__(message)
|
|
16
|
+
self.fix = fix
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def require(config: Dict[str, Any], key: str, adapter: str, example: str = "...") -> str:
|
|
20
|
+
value = config.get(key)
|
|
21
|
+
if not isinstance(value, str) or not value:
|
|
22
|
+
raise ConfigError(
|
|
23
|
+
f'the {adapter} adapter needs "{key}" in its config',
|
|
24
|
+
f'add "{key}: {example}" under the agent\'s config',
|
|
25
|
+
)
|
|
26
|
+
return value
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def read_key(env_name: Optional[str]) -> Optional[str]:
|
|
30
|
+
"""Read an API key from the environment variable named in config (SEC-001)."""
|
|
31
|
+
if not env_name:
|
|
32
|
+
return None
|
|
33
|
+
value = os.environ.get(env_name)
|
|
34
|
+
if not value:
|
|
35
|
+
raise ConfigError(
|
|
36
|
+
f"environment variable {env_name} is not set",
|
|
37
|
+
f"export {env_name}=<your key>, or remove api_key_env for servers that need no key",
|
|
38
|
+
)
|
|
39
|
+
return value
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def check_price(price: Any) -> Optional[Dict[str, float]]:
|
|
43
|
+
if price is None:
|
|
44
|
+
return None
|
|
45
|
+
try:
|
|
46
|
+
return {
|
|
47
|
+
"input_per_mtok": float(price["input_per_mtok"]),
|
|
48
|
+
"output_per_mtok": float(price["output_per_mtok"]),
|
|
49
|
+
}
|
|
50
|
+
except (TypeError, KeyError, ValueError) as exc:
|
|
51
|
+
raise ConfigError(
|
|
52
|
+
f"invalid price {price!r}",
|
|
53
|
+
'use "price: {input_per_mtok: 2.0, output_per_mtok: 10.0}" (USD per million tokens)',
|
|
54
|
+
) from exc
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def check_key_transport(url: str, key: Optional[str], config: Dict[str, Any]) -> None:
|
|
58
|
+
"""Refuse to send a key over plain http to a remote host (SEC-009)."""
|
|
59
|
+
from agentplaykit.agents.pricing import is_local_url
|
|
60
|
+
|
|
61
|
+
if not key or config.get("allow_insecure_http"):
|
|
62
|
+
return
|
|
63
|
+
if urlparse(url).scheme == "http" and not is_local_url(url):
|
|
64
|
+
raise ConfigError(
|
|
65
|
+
f"refusing to send an API key over plain http to {url}",
|
|
66
|
+
"use https, or set allow_insecure_http: true if you trust this network",
|
|
67
|
+
)
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""Any agent behind a URL (ADP-004): POSTs the Request as JSON, reads the Reply as JSON.
|
|
3
|
+
|
|
4
|
+
Config: url (required), api_key_env (sent as a Bearer token), timeout_s (60), retries (2).
|
|
5
|
+
The reply may include its own `usage`; without it the call costs 0.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import time
|
|
11
|
+
from typing import Any, Callable, Dict, List, Optional
|
|
12
|
+
|
|
13
|
+
from agentplaykit.agents._http import Transport, post_json, urllib_transport
|
|
14
|
+
from agentplaykit.agents.config import check_key_transport, read_key, require
|
|
15
|
+
from agentplaykit.core import Agent, AgentError
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class HttpAgent(Agent):
|
|
19
|
+
kind = "http"
|
|
20
|
+
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
config: Optional[Dict[str, Any]] = None,
|
|
24
|
+
*,
|
|
25
|
+
transport: Optional[Transport] = None,
|
|
26
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
27
|
+
) -> None:
|
|
28
|
+
super().__init__(config)
|
|
29
|
+
self.url = require(self.config, "url", "http", "http://localhost:8000/act")
|
|
30
|
+
self.key = read_key(self.config.get("api_key_env"))
|
|
31
|
+
check_key_transport(self.url, self.key, self.config)
|
|
32
|
+
self.transport = transport or urllib_transport
|
|
33
|
+
self.sleep = sleep
|
|
34
|
+
|
|
35
|
+
def secrets(self) -> List[str]:
|
|
36
|
+
return [self.key] if self.key else []
|
|
37
|
+
|
|
38
|
+
def act(self, request: Dict[str, Any]) -> Dict[str, Any]:
|
|
39
|
+
data, retries = post_json(
|
|
40
|
+
self.url,
|
|
41
|
+
request,
|
|
42
|
+
headers={"Authorization": f"Bearer {self.key}"} if self.key else {},
|
|
43
|
+
timeout=float(self.config.get("timeout_s", 60)),
|
|
44
|
+
retries=int(self.config.get("retries", 2)),
|
|
45
|
+
sleep=self.sleep,
|
|
46
|
+
transport=self.transport,
|
|
47
|
+
secrets=self.secrets(),
|
|
48
|
+
)
|
|
49
|
+
if not isinstance(data, dict) or "action" not in data:
|
|
50
|
+
raise AgentError(
|
|
51
|
+
f'the reply from {self.url} must be a JSON object with an "action" field'
|
|
52
|
+
)
|
|
53
|
+
if retries:
|
|
54
|
+
meta = data.get("meta")
|
|
55
|
+
data["meta"] = {**(meta if isinstance(meta, dict) else {}), "retries": retries}
|
|
56
|
+
return data
|