agnost-evals 0.1.0__tar.gz
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.
- agnost_evals-0.1.0/PKG-INFO +211 -0
- agnost_evals-0.1.0/README.md +186 -0
- agnost_evals-0.1.0/agnost_evals/__init__.py +7 -0
- agnost_evals-0.1.0/agnost_evals/api.py +215 -0
- agnost_evals-0.1.0/agnost_evals/py.typed +0 -0
- agnost_evals-0.1.0/agnost_evals/respond.py +100 -0
- agnost_evals-0.1.0/agnost_evals/rows.py +60 -0
- agnost_evals-0.1.0/agnost_evals/run.py +337 -0
- agnost_evals-0.1.0/agnost_evals/types.py +57 -0
- agnost_evals-0.1.0/agnost_evals/version.py +1 -0
- agnost_evals-0.1.0/agnost_evals/waiting.py +44 -0
- agnost_evals-0.1.0/agnost_evals.egg-info/PKG-INFO +211 -0
- agnost_evals-0.1.0/agnost_evals.egg-info/SOURCES.txt +24 -0
- agnost_evals-0.1.0/agnost_evals.egg-info/dependency_links.txt +1 -0
- agnost_evals-0.1.0/agnost_evals.egg-info/requires.txt +8 -0
- agnost_evals-0.1.0/agnost_evals.egg-info/top_level.txt +1 -0
- agnost_evals-0.1.0/pyproject.toml +48 -0
- agnost_evals-0.1.0/setup.cfg +4 -0
- agnost_evals-0.1.0/tests/test_api.py +210 -0
- agnost_evals-0.1.0/tests/test_contract_helper.py +18 -0
- agnost_evals-0.1.0/tests/test_example.py +82 -0
- agnost_evals-0.1.0/tests/test_package_metadata.py +34 -0
- agnost_evals-0.1.0/tests/test_respond.py +274 -0
- agnost_evals-0.1.0/tests/test_rows.py +91 -0
- agnost_evals-0.1.0/tests/test_run.py +323 -0
- agnost_evals-0.1.0/tests/test_run_api.py +268 -0
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agnost-evals
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Runs your AI agent on an Agnost experiment's dataset and reports each answer back for scoring.
|
|
5
|
+
Author-email: Agnost AI <founders@agnost.ai>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://agnost.ai
|
|
8
|
+
Keywords: agnost,evals,llm-evaluation,ai-agents,experiments
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Typing :: Typed
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
Provides-Extra: dev
|
|
21
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
22
|
+
Requires-Dist: jsonschema>=4.0; extra == "dev"
|
|
23
|
+
Requires-Dist: pyyaml>=6.0; extra == "dev"
|
|
24
|
+
Requires-Dist: tomli>=1.1.0; python_version < "3.11" and extra == "dev"
|
|
25
|
+
|
|
26
|
+
# agnost-evals
|
|
27
|
+
|
|
28
|
+
Run the rows of an Agnost AI experiment's dataset through your own agent, on your
|
|
29
|
+
machine or in CI. Agnost sends the rows, your agent answers each one, and Agnost
|
|
30
|
+
scores the answers with the experiment's evaluators. Your agent runs only on your
|
|
31
|
+
infrastructure and sees each row's input and metadata, never its expected output.
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install agnost-evals
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Requires Python 3.10 or newer. It has no dependencies.
|
|
38
|
+
|
|
39
|
+
## Write an adapter
|
|
40
|
+
|
|
41
|
+
The adapter is the one function you write. It receives a row's `input`, sets up
|
|
42
|
+
your agent from it, runs the agent, and returns the agent's final text. It can be
|
|
43
|
+
a plain or an `async` function.
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
# experiment.py
|
|
47
|
+
from agnost_evals import run_experiment
|
|
48
|
+
from booking import booking_agent
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
async def adapter(input, context):
|
|
52
|
+
reply = await booking_agent.run(input)
|
|
53
|
+
return reply.text
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
run_experiment(adapter)
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
When a row times out or the run is cancelled, an `async` adapter is cancelled
|
|
60
|
+
with `asyncio.CancelledError`. A plain function runs on its own thread and is not
|
|
61
|
+
stopped; check `context.cancelled`, a `threading.Event`, to stop it early.
|
|
62
|
+
|
|
63
|
+
`context` also carries the row's `row_id` and its `metadata`, the row's metadata
|
|
64
|
+
dict from the dataset (`{}` when it has none). Use it for per-row setup that isn't
|
|
65
|
+
part of the user's message, such as a customer tier or locale:
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
async def adapter(input, context):
|
|
69
|
+
agent = booking_agent.with_tier(context.metadata.get("tier"))
|
|
70
|
+
reply = await agent.run(input)
|
|
71
|
+
return reply.text
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
All `async` adapters run on one event loop for the whole run, so clients your
|
|
75
|
+
agent creates once, such as `AsyncOpenAI`, keep working from row to row. Call
|
|
76
|
+
`run_experiment` from synchronous code, such as the top level of your script,
|
|
77
|
+
not from inside `asyncio.run`.
|
|
78
|
+
|
|
79
|
+
## Run an experiment
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
export AGNOST_API_KEY=agnost_... # your project's API key
|
|
83
|
+
python experiment.py --experiment-id 7f3e2a10-5c4b-4d8e-9a61-2b0c8d4e6f19
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
```text
|
|
87
|
+
agnost-evals: started run 0b7c5d1e-2f3a-4b6c-8d9e-1a2b3c4d5e6f of experiment 7f3e2a10-5c4b-4d8e-9a61-2b0c8d4e6f19: 2 rows
|
|
88
|
+
|
|
89
|
+
✓ [1/2] 3c2b1a09-8f7e-4d6c-b5a4-0e9d8c7b6a51 2.4s Booked BK123: 3 nights in Mumbai for ₹7,500.
|
|
90
|
+
✗ [2/2] 4d3c2b1a-9e8f-4a7b-8c6d-1f0e9d8c7b62 120.0s Timed out after 120s
|
|
91
|
+
|
|
92
|
+
2 rows: 1 answered, 1 failed.
|
|
93
|
+
Failed rows:
|
|
94
|
+
4d3c2b1a-9e8f-4a7b-8c6d-1f0e9d8c7b62: Timed out after 120s
|
|
95
|
+
Reported 2 of 2 responses to Agnost (run 0b7c5d1e-2f3a-4b6c-8d9e-1a2b3c4d5e6f).
|
|
96
|
+
Agnost scores them with the experiment's evaluators.
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Each command starts a new run. Each row's response is sent to Agnost as soon as
|
|
100
|
+
the row finishes, so if the run stops partway, the rows already reported stay
|
|
101
|
+
saved in that run. Scores appear in Agnost; the SDK doesn't wait for them.
|
|
102
|
+
|
|
103
|
+
If Agnost can't be reached, times out, or answers with a 5xx, 409, or 429, the
|
|
104
|
+
request is retried, up to 4 attempts. A 409 that persists means the row already
|
|
105
|
+
has a different response; start a new run instead. Any other error stops the run
|
|
106
|
+
with Agnost's reason, such as "Agnost at https://api.agnost.ai rejected the API
|
|
107
|
+
key (401: Invalid API key); check AGNOST_API_KEY and AGNOST_ENDPOINT". A rejected
|
|
108
|
+
API key or a missing experiment names the endpoint, because a key or experiment
|
|
109
|
+
from another Agnost environment fails the same way. The API key is never printed. If starting a run times out and is
|
|
110
|
+
retried, Agnost can keep an extra run with no responses.
|
|
111
|
+
|
|
112
|
+
## Try an adapter on rows from a file
|
|
113
|
+
|
|
114
|
+
A rows file runs your adapter without Agnost, so you can build and check it
|
|
115
|
+
first. Nothing is sent anywhere.
|
|
116
|
+
|
|
117
|
+
```json
|
|
118
|
+
[
|
|
119
|
+
{ "id": "mumbai-budget", "input": { "destination": "Mumbai", "budget": 8000 } },
|
|
120
|
+
{ "id": "bk91-upgrade", "input": "Upgrade booking BK91 to business class." }
|
|
121
|
+
]
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
```bash
|
|
125
|
+
python experiment.py --rows-file rows.json
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
```text
|
|
129
|
+
agnost-evals: running 2 rows from rows.json
|
|
130
|
+
|
|
131
|
+
✓ [1/2] mumbai-budget 2.4s Booked BK123: 3 nights in Mumbai for ₹7,500.
|
|
132
|
+
✗ [2/2] bk91-upgrade 120.0s Timed out after 120s
|
|
133
|
+
|
|
134
|
+
2 rows: 1 answered, 1 failed.
|
|
135
|
+
Failed rows:
|
|
136
|
+
bk91-upgrade: Timed out after 120s
|
|
137
|
+
Local run: nothing was sent to Agnost.
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
Each row needs a unique `id` and an `input`, which can be any JSON value, and may
|
|
141
|
+
have a `metadata` object. Rows have the same shape as Agnost's dataset rows, so a
|
|
142
|
+
saved start-run response, an object with a `rows` list, works as a rows file too;
|
|
143
|
+
other fields are ignored.
|
|
144
|
+
|
|
145
|
+
Rows run one at a time, in file order.
|
|
146
|
+
|
|
147
|
+
## What is recorded for each row
|
|
148
|
+
|
|
149
|
+
| What the adapter does | Answer | Error |
|
|
150
|
+
| --- | --- | --- |
|
|
151
|
+
| Returns a string | The string, even if empty | none |
|
|
152
|
+
| Returns any other value | The value as JSON | none |
|
|
153
|
+
| Returns `None` | none | The adapter returned no answer |
|
|
154
|
+
| Raises | none | The exception's type and message, such as `KeyError: 'customer_id'` |
|
|
155
|
+
| Returns more than 100,000 characters | none | The answer's length |
|
|
156
|
+
| Runs past `timeout` | none | `Timed out after 120s` |
|
|
157
|
+
| Is running when you press Ctrl+C | none | `Cancelled` |
|
|
158
|
+
|
|
159
|
+
Pydantic models and dataclasses are sent as JSON too. Rows not reached after
|
|
160
|
+
Ctrl+C are recorded as `Not run: cancelled`, and in an experiment run they are
|
|
161
|
+
still reported, so every row in the run gets a response. A second Ctrl+C exits
|
|
162
|
+
immediately with code 130, without reporting the rest. Errors longer than 4,000
|
|
163
|
+
characters are truncated.
|
|
164
|
+
|
|
165
|
+
An `async` adapter that makes a blocking call, such as a request with a
|
|
166
|
+
synchronous HTTP client, holds up the event loop, so the timeout can't stop it.
|
|
167
|
+
When its answer arrives late it is recorded as `Timed out`, and a second Ctrl+C
|
|
168
|
+
still exits. Make blocking calls from a plain function, which runs on its own
|
|
169
|
+
thread.
|
|
170
|
+
|
|
171
|
+
## Exit codes
|
|
172
|
+
|
|
173
|
+
`run_experiment` exits the process when the run ends.
|
|
174
|
+
|
|
175
|
+
| Code | Meaning |
|
|
176
|
+
| --- | --- |
|
|
177
|
+
| `0` | Every row answered |
|
|
178
|
+
| `1` | At least one row failed |
|
|
179
|
+
| `2` | The run couldn't start, a response couldn't be reported to Agnost, or the run was cancelled |
|
|
180
|
+
|
|
181
|
+
Exit code `0` means every row produced an answer, not that the answers are good.
|
|
182
|
+
Pass `exit=False` to get a `RunResult` with the exit code, each row's result, and
|
|
183
|
+
the `run_id` of an experiment run instead.
|
|
184
|
+
|
|
185
|
+
## Options
|
|
186
|
+
|
|
187
|
+
| Option | Default | |
|
|
188
|
+
| --- | --- | --- |
|
|
189
|
+
| `adapter` | required | Your function, called once per row as `adapter(input, context)` |
|
|
190
|
+
| `experiment_id` | `--experiment-id` argument | The Agnost experiment to run |
|
|
191
|
+
| `api_key` | `AGNOST_API_KEY` | Your project's API key |
|
|
192
|
+
| `endpoint` | `AGNOST_ENDPOINT`, then `https://api.agnost.ai` | The Agnost API |
|
|
193
|
+
| `rows_file` | `--rows-file` argument | JSON file of rows to run locally instead |
|
|
194
|
+
| `timeout` | `120` | Seconds one row may run |
|
|
195
|
+
| `cancel` | none | A `threading.Event` that cancels the run when set, like Ctrl+C |
|
|
196
|
+
| `argv` | `sys.argv[1:]` | Arguments to read `--experiment-id` and `--rows-file` from; flags it doesn't know are ignored |
|
|
197
|
+
| `exit` | `True` | Exit the process with the exit code; `False` returns the result |
|
|
198
|
+
|
|
199
|
+
Pass either an experiment ID or a rows file, not both.
|
|
200
|
+
|
|
201
|
+
## Example
|
|
202
|
+
|
|
203
|
+
[`examples/`](./examples) has a hotel booking agent, its adapter, and a rows
|
|
204
|
+
file. The agent follows fixed rules instead of calling a model, so it runs
|
|
205
|
+
without an API key. The tests run it on every change, and every release runs it
|
|
206
|
+
against the built wheel:
|
|
207
|
+
|
|
208
|
+
```bash
|
|
209
|
+
pip install agnost-evals
|
|
210
|
+
python examples/experiment.py --rows-file examples/rows.json
|
|
211
|
+
```
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
# agnost-evals
|
|
2
|
+
|
|
3
|
+
Run the rows of an Agnost AI experiment's dataset through your own agent, on your
|
|
4
|
+
machine or in CI. Agnost sends the rows, your agent answers each one, and Agnost
|
|
5
|
+
scores the answers with the experiment's evaluators. Your agent runs only on your
|
|
6
|
+
infrastructure and sees each row's input and metadata, never its expected output.
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
pip install agnost-evals
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Requires Python 3.10 or newer. It has no dependencies.
|
|
13
|
+
|
|
14
|
+
## Write an adapter
|
|
15
|
+
|
|
16
|
+
The adapter is the one function you write. It receives a row's `input`, sets up
|
|
17
|
+
your agent from it, runs the agent, and returns the agent's final text. It can be
|
|
18
|
+
a plain or an `async` function.
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
# experiment.py
|
|
22
|
+
from agnost_evals import run_experiment
|
|
23
|
+
from booking import booking_agent
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
async def adapter(input, context):
|
|
27
|
+
reply = await booking_agent.run(input)
|
|
28
|
+
return reply.text
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
run_experiment(adapter)
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
When a row times out or the run is cancelled, an `async` adapter is cancelled
|
|
35
|
+
with `asyncio.CancelledError`. A plain function runs on its own thread and is not
|
|
36
|
+
stopped; check `context.cancelled`, a `threading.Event`, to stop it early.
|
|
37
|
+
|
|
38
|
+
`context` also carries the row's `row_id` and its `metadata`, the row's metadata
|
|
39
|
+
dict from the dataset (`{}` when it has none). Use it for per-row setup that isn't
|
|
40
|
+
part of the user's message, such as a customer tier or locale:
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
async def adapter(input, context):
|
|
44
|
+
agent = booking_agent.with_tier(context.metadata.get("tier"))
|
|
45
|
+
reply = await agent.run(input)
|
|
46
|
+
return reply.text
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
All `async` adapters run on one event loop for the whole run, so clients your
|
|
50
|
+
agent creates once, such as `AsyncOpenAI`, keep working from row to row. Call
|
|
51
|
+
`run_experiment` from synchronous code, such as the top level of your script,
|
|
52
|
+
not from inside `asyncio.run`.
|
|
53
|
+
|
|
54
|
+
## Run an experiment
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
export AGNOST_API_KEY=agnost_... # your project's API key
|
|
58
|
+
python experiment.py --experiment-id 7f3e2a10-5c4b-4d8e-9a61-2b0c8d4e6f19
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
```text
|
|
62
|
+
agnost-evals: started run 0b7c5d1e-2f3a-4b6c-8d9e-1a2b3c4d5e6f of experiment 7f3e2a10-5c4b-4d8e-9a61-2b0c8d4e6f19: 2 rows
|
|
63
|
+
|
|
64
|
+
✓ [1/2] 3c2b1a09-8f7e-4d6c-b5a4-0e9d8c7b6a51 2.4s Booked BK123: 3 nights in Mumbai for ₹7,500.
|
|
65
|
+
✗ [2/2] 4d3c2b1a-9e8f-4a7b-8c6d-1f0e9d8c7b62 120.0s Timed out after 120s
|
|
66
|
+
|
|
67
|
+
2 rows: 1 answered, 1 failed.
|
|
68
|
+
Failed rows:
|
|
69
|
+
4d3c2b1a-9e8f-4a7b-8c6d-1f0e9d8c7b62: Timed out after 120s
|
|
70
|
+
Reported 2 of 2 responses to Agnost (run 0b7c5d1e-2f3a-4b6c-8d9e-1a2b3c4d5e6f).
|
|
71
|
+
Agnost scores them with the experiment's evaluators.
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Each command starts a new run. Each row's response is sent to Agnost as soon as
|
|
75
|
+
the row finishes, so if the run stops partway, the rows already reported stay
|
|
76
|
+
saved in that run. Scores appear in Agnost; the SDK doesn't wait for them.
|
|
77
|
+
|
|
78
|
+
If Agnost can't be reached, times out, or answers with a 5xx, 409, or 429, the
|
|
79
|
+
request is retried, up to 4 attempts. A 409 that persists means the row already
|
|
80
|
+
has a different response; start a new run instead. Any other error stops the run
|
|
81
|
+
with Agnost's reason, such as "Agnost at https://api.agnost.ai rejected the API
|
|
82
|
+
key (401: Invalid API key); check AGNOST_API_KEY and AGNOST_ENDPOINT". A rejected
|
|
83
|
+
API key or a missing experiment names the endpoint, because a key or experiment
|
|
84
|
+
from another Agnost environment fails the same way. The API key is never printed. If starting a run times out and is
|
|
85
|
+
retried, Agnost can keep an extra run with no responses.
|
|
86
|
+
|
|
87
|
+
## Try an adapter on rows from a file
|
|
88
|
+
|
|
89
|
+
A rows file runs your adapter without Agnost, so you can build and check it
|
|
90
|
+
first. Nothing is sent anywhere.
|
|
91
|
+
|
|
92
|
+
```json
|
|
93
|
+
[
|
|
94
|
+
{ "id": "mumbai-budget", "input": { "destination": "Mumbai", "budget": 8000 } },
|
|
95
|
+
{ "id": "bk91-upgrade", "input": "Upgrade booking BK91 to business class." }
|
|
96
|
+
]
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
python experiment.py --rows-file rows.json
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
```text
|
|
104
|
+
agnost-evals: running 2 rows from rows.json
|
|
105
|
+
|
|
106
|
+
✓ [1/2] mumbai-budget 2.4s Booked BK123: 3 nights in Mumbai for ₹7,500.
|
|
107
|
+
✗ [2/2] bk91-upgrade 120.0s Timed out after 120s
|
|
108
|
+
|
|
109
|
+
2 rows: 1 answered, 1 failed.
|
|
110
|
+
Failed rows:
|
|
111
|
+
bk91-upgrade: Timed out after 120s
|
|
112
|
+
Local run: nothing was sent to Agnost.
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Each row needs a unique `id` and an `input`, which can be any JSON value, and may
|
|
116
|
+
have a `metadata` object. Rows have the same shape as Agnost's dataset rows, so a
|
|
117
|
+
saved start-run response, an object with a `rows` list, works as a rows file too;
|
|
118
|
+
other fields are ignored.
|
|
119
|
+
|
|
120
|
+
Rows run one at a time, in file order.
|
|
121
|
+
|
|
122
|
+
## What is recorded for each row
|
|
123
|
+
|
|
124
|
+
| What the adapter does | Answer | Error |
|
|
125
|
+
| --- | --- | --- |
|
|
126
|
+
| Returns a string | The string, even if empty | none |
|
|
127
|
+
| Returns any other value | The value as JSON | none |
|
|
128
|
+
| Returns `None` | none | The adapter returned no answer |
|
|
129
|
+
| Raises | none | The exception's type and message, such as `KeyError: 'customer_id'` |
|
|
130
|
+
| Returns more than 100,000 characters | none | The answer's length |
|
|
131
|
+
| Runs past `timeout` | none | `Timed out after 120s` |
|
|
132
|
+
| Is running when you press Ctrl+C | none | `Cancelled` |
|
|
133
|
+
|
|
134
|
+
Pydantic models and dataclasses are sent as JSON too. Rows not reached after
|
|
135
|
+
Ctrl+C are recorded as `Not run: cancelled`, and in an experiment run they are
|
|
136
|
+
still reported, so every row in the run gets a response. A second Ctrl+C exits
|
|
137
|
+
immediately with code 130, without reporting the rest. Errors longer than 4,000
|
|
138
|
+
characters are truncated.
|
|
139
|
+
|
|
140
|
+
An `async` adapter that makes a blocking call, such as a request with a
|
|
141
|
+
synchronous HTTP client, holds up the event loop, so the timeout can't stop it.
|
|
142
|
+
When its answer arrives late it is recorded as `Timed out`, and a second Ctrl+C
|
|
143
|
+
still exits. Make blocking calls from a plain function, which runs on its own
|
|
144
|
+
thread.
|
|
145
|
+
|
|
146
|
+
## Exit codes
|
|
147
|
+
|
|
148
|
+
`run_experiment` exits the process when the run ends.
|
|
149
|
+
|
|
150
|
+
| Code | Meaning |
|
|
151
|
+
| --- | --- |
|
|
152
|
+
| `0` | Every row answered |
|
|
153
|
+
| `1` | At least one row failed |
|
|
154
|
+
| `2` | The run couldn't start, a response couldn't be reported to Agnost, or the run was cancelled |
|
|
155
|
+
|
|
156
|
+
Exit code `0` means every row produced an answer, not that the answers are good.
|
|
157
|
+
Pass `exit=False` to get a `RunResult` with the exit code, each row's result, and
|
|
158
|
+
the `run_id` of an experiment run instead.
|
|
159
|
+
|
|
160
|
+
## Options
|
|
161
|
+
|
|
162
|
+
| Option | Default | |
|
|
163
|
+
| --- | --- | --- |
|
|
164
|
+
| `adapter` | required | Your function, called once per row as `adapter(input, context)` |
|
|
165
|
+
| `experiment_id` | `--experiment-id` argument | The Agnost experiment to run |
|
|
166
|
+
| `api_key` | `AGNOST_API_KEY` | Your project's API key |
|
|
167
|
+
| `endpoint` | `AGNOST_ENDPOINT`, then `https://api.agnost.ai` | The Agnost API |
|
|
168
|
+
| `rows_file` | `--rows-file` argument | JSON file of rows to run locally instead |
|
|
169
|
+
| `timeout` | `120` | Seconds one row may run |
|
|
170
|
+
| `cancel` | none | A `threading.Event` that cancels the run when set, like Ctrl+C |
|
|
171
|
+
| `argv` | `sys.argv[1:]` | Arguments to read `--experiment-id` and `--rows-file` from; flags it doesn't know are ignored |
|
|
172
|
+
| `exit` | `True` | Exit the process with the exit code; `False` returns the result |
|
|
173
|
+
|
|
174
|
+
Pass either an experiment ID or a rows file, not both.
|
|
175
|
+
|
|
176
|
+
## Example
|
|
177
|
+
|
|
178
|
+
[`examples/`](./examples) has a hotel booking agent, its adapter, and a rows
|
|
179
|
+
file. The agent follows fixed rules instead of calling a model, so it runs
|
|
180
|
+
without an API key. The tests run it on every change, and every release runs it
|
|
181
|
+
against the built wheel:
|
|
182
|
+
|
|
183
|
+
```bash
|
|
184
|
+
pip install agnost-evals
|
|
185
|
+
python examples/experiment.py --rows-file examples/rows.json
|
|
186
|
+
```
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Runs your AI agent on an Agnost experiment's dataset and reports each answer back for scoring."""
|
|
2
|
+
|
|
3
|
+
from .run import run_experiment
|
|
4
|
+
from .types import Adapter, AdapterContext, RowResult, RunResult
|
|
5
|
+
from .version import __version__
|
|
6
|
+
|
|
7
|
+
__all__ = ["Adapter", "AdapterContext", "RowResult", "RunResult", "__version__", "run_experiment"]
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import http.client
|
|
2
|
+
import json
|
|
3
|
+
import math
|
|
4
|
+
import platform
|
|
5
|
+
import threading
|
|
6
|
+
import urllib.error
|
|
7
|
+
import urllib.parse
|
|
8
|
+
import urllib.request
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from typing import Callable
|
|
11
|
+
|
|
12
|
+
from .rows import parse_rows
|
|
13
|
+
from .types import AgentResponse, Row
|
|
14
|
+
from .version import __version__
|
|
15
|
+
|
|
16
|
+
DEFAULT_ENDPOINT = "https://api.agnost.ai"
|
|
17
|
+
ATTEMPTS = 4
|
|
18
|
+
RETRY_DELAYS = (0.5, 1.0, 2.0)
|
|
19
|
+
"""Seconds to wait before the second, third, and fourth attempts."""
|
|
20
|
+
REQUEST_TIMEOUT = 30.0
|
|
21
|
+
MAX_RETRY_AFTER = 60.0
|
|
22
|
+
USER_AGENT = f"agnost-evals/{__version__} python/{platform.python_version()}"
|
|
23
|
+
|
|
24
|
+
Describe = Callable[[int, str | None], str]
|
|
25
|
+
"""Turns a failed status and Agnost's `error` message into a message for the person running the experiment."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ApiError(Exception):
|
|
29
|
+
"""A call to Agnost failed. The message says why, for the person running the experiment."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class StartedRun:
|
|
34
|
+
run_id: str
|
|
35
|
+
rows: list[Row]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class AgnostApi:
|
|
39
|
+
"""The two Agnost calls, retried on network errors, timeouts, 5xx, 409, and 429.
|
|
40
|
+
|
|
41
|
+
Agnost answers 409 while another request holds the row or project, and a 409
|
|
42
|
+
changes nothing, so retrying it is safe.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
def __init__(
|
|
46
|
+
self,
|
|
47
|
+
endpoint: str,
|
|
48
|
+
api_key: str,
|
|
49
|
+
*,
|
|
50
|
+
retry_delays: tuple[float, ...] | None = None,
|
|
51
|
+
request_timeout: float | None = None,
|
|
52
|
+
) -> None:
|
|
53
|
+
self.endpoint = endpoint.rstrip("/")
|
|
54
|
+
self._api_key = api_key
|
|
55
|
+
self._retry_delays = tuple(RETRY_DELAYS if retry_delays is None else retry_delays)
|
|
56
|
+
self._request_timeout = REQUEST_TIMEOUT if request_timeout is None else request_timeout
|
|
57
|
+
|
|
58
|
+
def start_run(self, experiment_id: str, cancelled: threading.Event | None = None) -> StartedRun:
|
|
59
|
+
"""Starts a run. Setting `cancelled` stops any further retries."""
|
|
60
|
+
|
|
61
|
+
def describe(status: int, detail: str | None) -> str:
|
|
62
|
+
if status == 404:
|
|
63
|
+
return (
|
|
64
|
+
f"The experiment wasn't found in the API key's project at {self.endpoint} "
|
|
65
|
+
f"{_tag(status, detail)}; check the experiment ID and AGNOST_ENDPOINT"
|
|
66
|
+
)
|
|
67
|
+
return _describe_failure(status, detail, self.endpoint)
|
|
68
|
+
|
|
69
|
+
text = self._send(
|
|
70
|
+
"POST",
|
|
71
|
+
f"/dashboard/api/experiments/{_quote(experiment_id)}/runs",
|
|
72
|
+
cancelled=cancelled,
|
|
73
|
+
describe=describe,
|
|
74
|
+
)
|
|
75
|
+
return _parse_run(text)
|
|
76
|
+
|
|
77
|
+
def report(self, run_id: str, row_id: str, response: AgentResponse) -> None:
|
|
78
|
+
def describe(status: int, detail: str | None) -> str:
|
|
79
|
+
if status == 404:
|
|
80
|
+
return f"Agnost doesn't have this run or row {_tag(status, detail)}"
|
|
81
|
+
return _describe_failure(status, detail, self.endpoint)
|
|
82
|
+
|
|
83
|
+
body = {"row_id": row_id, "agent_output": {"message": response.message, "error": response.error}}
|
|
84
|
+
self._send(
|
|
85
|
+
"POST",
|
|
86
|
+
f"/dashboard/api/experiment-runs/{_quote(run_id)}/responses",
|
|
87
|
+
headers={"Content-Type": "application/json"},
|
|
88
|
+
body=json.dumps(body, ensure_ascii=False).encode("utf-8"),
|
|
89
|
+
describe=describe,
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
def _send(
|
|
93
|
+
self,
|
|
94
|
+
method: str,
|
|
95
|
+
path: str,
|
|
96
|
+
*,
|
|
97
|
+
describe: Describe,
|
|
98
|
+
headers: dict | None = None,
|
|
99
|
+
body: bytes | None = None,
|
|
100
|
+
cancelled: threading.Event | None = None,
|
|
101
|
+
) -> str:
|
|
102
|
+
cancelled = cancelled or threading.Event()
|
|
103
|
+
failure = ""
|
|
104
|
+
delay = 0.0
|
|
105
|
+
for attempt in range(1, ATTEMPTS + 1):
|
|
106
|
+
if (attempt > 1 and cancelled.wait(delay)) or cancelled.is_set():
|
|
107
|
+
raise ApiError("Cancelled")
|
|
108
|
+
backoff = self._retry_delays[min(attempt - 1, len(self._retry_delays) - 1)] if self._retry_delays else 0.0
|
|
109
|
+
|
|
110
|
+
request = urllib.request.Request(
|
|
111
|
+
f"{self.endpoint}{path}",
|
|
112
|
+
data=body,
|
|
113
|
+
method=method,
|
|
114
|
+
headers={
|
|
115
|
+
**(headers or {}),
|
|
116
|
+
"Accept": "application/json",
|
|
117
|
+
"User-Agent": USER_AGENT,
|
|
118
|
+
"X-Api-Key": self._api_key,
|
|
119
|
+
},
|
|
120
|
+
)
|
|
121
|
+
try:
|
|
122
|
+
with urllib.request.urlopen(request, timeout=self._request_timeout) as response:
|
|
123
|
+
return response.read().decode("utf-8", "replace")
|
|
124
|
+
except urllib.error.HTTPError as error:
|
|
125
|
+
status = error.code
|
|
126
|
+
text = _read(error)
|
|
127
|
+
retry_after = _parse_retry_after(error.headers.get("Retry-After"))
|
|
128
|
+
except (OSError, http.client.HTTPException) as error:
|
|
129
|
+
reason = _network_reason(error, self._request_timeout)
|
|
130
|
+
failure = f"Couldn't reach Agnost at {self.endpoint} after {ATTEMPTS} attempts: {reason}"
|
|
131
|
+
delay = backoff
|
|
132
|
+
continue
|
|
133
|
+
except ValueError:
|
|
134
|
+
# http.client refuses a header it can't send, such as an API key with a line break,
|
|
135
|
+
# and its message includes the header's value.
|
|
136
|
+
raise ApiError(
|
|
137
|
+
f"Couldn't send a request to Agnost at {self.endpoint}; check AGNOST_API_KEY and AGNOST_ENDPOINT"
|
|
138
|
+
) from None
|
|
139
|
+
|
|
140
|
+
detail = _error_message(text)
|
|
141
|
+
if status not in (409, 429) and status < 500:
|
|
142
|
+
raise ApiError(describe(status, detail))
|
|
143
|
+
failure = f"Agnost answered {status} after {ATTEMPTS} attempts{f': {detail}' if detail else ''}"
|
|
144
|
+
delay = retry_after if status == 429 and retry_after is not None else backoff
|
|
145
|
+
raise ApiError(failure)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _describe_failure(status: int, detail: str | None, endpoint: str) -> str:
|
|
149
|
+
if status == 401:
|
|
150
|
+
return (
|
|
151
|
+
f"Agnost at {endpoint} rejected the API key {_tag(status, detail)}; "
|
|
152
|
+
"check AGNOST_API_KEY and AGNOST_ENDPOINT"
|
|
153
|
+
)
|
|
154
|
+
return f"Agnost rejected the request {_tag(status, detail)}"
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _tag(status: int, detail: str | None) -> str:
|
|
158
|
+
return f"({status}{f': {detail}' if detail else ''})"
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _quote(segment: str) -> str:
|
|
162
|
+
return urllib.parse.quote(segment, safe="")
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _read(error: urllib.error.HTTPError) -> str:
|
|
166
|
+
try:
|
|
167
|
+
return error.read().decode("utf-8", "replace")
|
|
168
|
+
except (OSError, http.client.HTTPException):
|
|
169
|
+
return ""
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _error_message(text: str) -> str | None:
|
|
173
|
+
try:
|
|
174
|
+
body = json.loads(text)
|
|
175
|
+
except ValueError:
|
|
176
|
+
return None
|
|
177
|
+
message = body.get("error") if isinstance(body, dict) else None
|
|
178
|
+
return message if isinstance(message, str) and message != "" else None
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _parse_run(text: str) -> StartedRun:
|
|
182
|
+
def unexpected(detail: str) -> ApiError:
|
|
183
|
+
return ApiError(f"Agnost sent an unexpected run: {detail}")
|
|
184
|
+
|
|
185
|
+
try:
|
|
186
|
+
run = json.loads(text)
|
|
187
|
+
except ValueError:
|
|
188
|
+
raise unexpected("the response isn't JSON") from None
|
|
189
|
+
if not isinstance(run, dict):
|
|
190
|
+
raise unexpected("the response isn't a JSON object")
|
|
191
|
+
|
|
192
|
+
run_id = run.get("run_id")
|
|
193
|
+
if not isinstance(run_id, str) or run_id == "":
|
|
194
|
+
raise unexpected("the response has no run_id")
|
|
195
|
+
try:
|
|
196
|
+
return StartedRun(run_id=run_id, rows=parse_rows(run.get("rows")))
|
|
197
|
+
except ValueError as error:
|
|
198
|
+
raise unexpected(str(error)) from None
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _parse_retry_after(header: str | None) -> float | None:
|
|
202
|
+
if header is None or header.strip() == "":
|
|
203
|
+
return None
|
|
204
|
+
try:
|
|
205
|
+
seconds = float(header)
|
|
206
|
+
except ValueError:
|
|
207
|
+
return None
|
|
208
|
+
return min(seconds, MAX_RETRY_AFTER) if math.isfinite(seconds) and seconds >= 0 else None
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _network_reason(error: BaseException, timeout: float) -> str:
|
|
212
|
+
reason = error.reason if isinstance(error, urllib.error.URLError) else error
|
|
213
|
+
if isinstance(reason, TimeoutError):
|
|
214
|
+
return f"no answer within {timeout:g}s"
|
|
215
|
+
return str(reason) or type(reason).__name__
|
|
File without changes
|