{{ message }}
Repository navigation
Expand file tree
/
Copy pathrun.py
More file actions
265 lines (242 loc) · 8.67 KB
/
Copy pathrun.py
File metadata and controls
265 lines (242 loc) · 8.67 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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
from __future__ import annotations
import inspect
import threading
import time
import uuid
from datetime import datetime, timezone
from typing import Any, Callable, Dict, Optional, TypeVar
import httpx
from .types import StepPayload, StepType
T = TypeVar("T")
def _get(obj: Any, key: str) -> Any:
"""Get a field from either a dict or an object attribute."""
if isinstance(obj, dict):
return obj.get(key)
return getattr(obj, key, None)
def _sniff_usage(output: Any) -> Dict[str, Any]:
"""Best-effort extraction of token count from well-known LLM response shapes."""
try:
usage = _get(output, "usage") if output is not None else None
if usage is None:
return {}
# Anthropic: input_tokens + output_tokens
input_tokens = _get(usage, "input_tokens")
output_tokens = _get(usage, "output_tokens")
if isinstance(input_tokens, int) and isinstance(output_tokens, int):
return {"token_count": input_tokens + output_tokens}
# OpenAI-compatible: total_tokens
total_tokens = _get(usage, "total_tokens")
if isinstance(total_tokens, int):
return {"token_count": total_tokens}
# OpenAI-compatible: prompt_tokens + completion_tokens
prompt_tokens = _get(usage, "prompt_tokens")
completion_tokens = _get(usage, "completion_tokens")
if isinstance(prompt_tokens, int) and isinstance(completion_tokens, int):
return {"token_count": prompt_tokens + completion_tokens}
except Exception:
pass
return {}
class AgentRun:
def __init__(
self,
*,
project_slug: str,
api_key: str,
base_url: str,
input: Any = None,
label: Optional[str] = None,
golden_id: Optional[str] = None,
goal: Optional[str] = None,
expected_output: Any = None,
expected_behavior: Optional[str] = None,
success_criteria: Optional[list] = None,
trace_assertions: Optional[list] = None,
failure_modes: Optional[list] = None,
metadata: Optional[dict] = None,
) -> None:
self.run_id = uuid.uuid4().hex[:12]
self._api_key = api_key
self._base_url = base_url
self._steps: list = []
self._started_at = time.monotonic()
self._remote_run_id: Optional[str] = None
self._init_remote(
project_slug=project_slug,
input=input,
label=label,
golden_id=golden_id,
goal=goal,
expected_output=expected_output,
expected_behavior=expected_behavior,
success_criteria=success_criteria,
trace_assertions=trace_assertions,
failure_modes=failure_modes,
metadata=metadata or {},
)
def _init_remote(
self,
*,
project_slug: str,
input: Any,
label: Optional[str],
golden_id: Optional[str],
goal: Optional[str],
expected_output: Any,
expected_behavior: Optional[str],
success_criteria: Optional[list],
trace_assertions: Optional[list],
failure_modes: Optional[list],
metadata: dict,
) -> None:
with httpx.Client(follow_redirects=True) as client:
res = client.post(
f"{self._base_url}/runs",
headers={"x-api-key": self._api_key},
json={
"label": label,
"input": input,
"projectSlug": project_slug,
"clientRunId": self.run_id,
"goldenId": golden_id,
"goal": goal,
"expectedOutput": expected_output,
"expectedBehavior": expected_behavior,
"successCriteria": success_criteria,
"traceAssertions": trace_assertions,
"failureModes": failure_modes,
"metadata": metadata,
},
timeout=10,
)
res.raise_for_status()
self._remote_run_id = res.json()["runId"]
def log_step(self, payload: StepPayload) -> None:
step = {
**payload,
"step_index": len(self._steps),
"created_at": datetime.now(timezone.utc).isoformat(),
}
self._steps.append(step)
def _send() -> None:
try:
with httpx.Client(follow_redirects=True) as client:
client.post(
f"{self._base_url}/runs/{self._remote_run_id}/steps",
headers={"x-api-key": self._api_key},
json=step,
timeout=10,
)
except Exception:
pass # SDK must never crash the agent
threading.Thread(target=_send, daemon=True).start()
def trace(
self,
type: StepType,
name: str,
fn: Callable[[], T],
input: Any = None,
extract: Optional[Callable[[Any], Dict[str, Any]]] = None,
) -> T:
"""Wrap a sync callable and auto-log it as a step with latency captured.
``extract`` receives the return value of ``fn`` and should return a dict
with optional keys ``token_count`` (int) and ``cost_usd`` (float). When
omitted, the SDK attempts to detect usage from Anthropic / OpenAI-compatible
response shapes automatically. Falls back to null if neither works.
"""
t0 = time.monotonic()
try:
result = fn()
except Exception as err:
self.log_step({
"type": type,
"name": name,
"input": input,
"output": {"error": str(err)},
"latency_ms": (time.monotonic() - t0) * 1000,
})
raise
usage: Dict[str, Any] = {}
if extract is not None:
try:
usage = extract(result) or {}
except Exception:
pass
else:
usage = _sniff_usage(result)
self.log_step({
"type": type,
"name": name,
"input": input,
"output": result,
"latency_ms": (time.monotonic() - t0) * 1000,
**usage,
})
return result
async def atrace(
self,
type: StepType,
name: str,
fn: Callable[[], Any],
input: Any = None,
extract: Optional[Callable[[Any], Dict[str, Any]]] = None,
) -> Any:
"""Wrap a sync or async callable and auto-log it as a step. Use in async contexts.
See ``trace()`` for docs on the ``extract`` parameter.
"""
t0 = time.monotonic()
try:
result = await fn() if inspect.iscoroutinefunction(fn) else fn()
except Exception as err:
self.log_step({
"type": type,
"name": name,
"input": input,
"output": {"error": str(err)},
"latency_ms": (time.monotonic() - t0) * 1000,
})
raise
usage: Dict[str, Any] = {}
if extract is not None:
try:
usage = extract(result) or {}
except Exception:
pass
else:
usage = _sniff_usage(result)
self.log_step({
"type": type,
"name": name,
"input": input,
"output": result,
"latency_ms": (time.monotonic() - t0) * 1000,
**usage,
})
return result
def complete(self, output: Any) -> dict:
"""Finish the run and trigger grading. Returns {"publicUrl": "..."}."""
with httpx.Client(follow_redirects=True) as client:
res = client.post(
f"{self._base_url}/runs/{self._remote_run_id}/complete",
headers={"x-api-key": self._api_key},
json={"output": output},
timeout=30,
)
res.raise_for_status()
return res.json()
async def acomplete(self, output: Any) -> dict:
"""Async version of complete()."""
async with httpx.AsyncClient(follow_redirects=True) as client:
res = await client.post(
f"{self._base_url}/runs/{self._remote_run_id}/complete",
headers={"x-api-key": self._api_key},
json={"output": output},
timeout=30,
)
res.raise_for_status()
return res.json()
@property
def elapsed_ms(self) -> float:
return (time.monotonic() - self._started_at) * 1000
@property
def remote_run_id(self) -> Optional[str]:
return self._remote_run_id
You can’t perform that action at this time.
