futuresearch-btf 0.5.4__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.
- futuresearch_btf/__init__.py +27 -0
- futuresearch_btf/__main__.py +261 -0
- futuresearch_btf/agent.py +361 -0
- futuresearch_btf/corpus.py +714 -0
- futuresearch_btf/http_server.py +493 -0
- futuresearch_btf/prompt.py +90 -0
- futuresearch_btf/score.py +152 -0
- futuresearch_btf/server.py +115 -0
- futuresearch_btf/tools.py +628 -0
- futuresearch_btf-0.5.4.dist-info/METADATA +98 -0
- futuresearch_btf-0.5.4.dist-info/RECORD +15 -0
- futuresearch_btf-0.5.4.dist-info/WHEEL +5 -0
- futuresearch_btf-0.5.4.dist-info/entry_points.txt +2 -0
- futuresearch_btf-0.5.4.dist-info/licenses/LICENSE-code.txt +202 -0
- futuresearch_btf-0.5.4.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Offline research tools for Bench to the Future releases: search, read, forecast, score.
|
|
2
|
+
|
|
3
|
+
The stable API (see INTEGRATING.md): `Release` (questions, prompts, tool calls),
|
|
4
|
+
`schemas` (tool definitions for OpenAI, Anthropic or MCP), `ToolResult`, `ERROR_CODES`,
|
|
5
|
+
`UnknownQuestion`, `render` and `validate`; `futuresearch_btf.score.score` scores a run file.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
__version__ = "0.5.4"
|
|
9
|
+
|
|
10
|
+
# the module (not the function), so futuresearch_btf.score.score works after `import futuresearch_btf`;
|
|
11
|
+
# re-exported by the alias, not __all__
|
|
12
|
+
from . import score as score
|
|
13
|
+
from .corpus import QuestionView, Release, UnknownQuestion
|
|
14
|
+
from .prompt import render, validate
|
|
15
|
+
from .tools import ERROR_CODES, ToolResult, schemas
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"ERROR_CODES",
|
|
19
|
+
"QuestionView",
|
|
20
|
+
"Release",
|
|
21
|
+
"ToolResult",
|
|
22
|
+
"UnknownQuestion",
|
|
23
|
+
"__version__",
|
|
24
|
+
"render",
|
|
25
|
+
"schemas",
|
|
26
|
+
"validate",
|
|
27
|
+
]
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
"""futuresearch_btf command line: questions, search, serve, serve-http, run, schemas, score."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import importlib
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from .tools import LATEST_TOOLSET, TOOLSETS
|
|
13
|
+
|
|
14
|
+
DATA_HELP = "the release directory"
|
|
15
|
+
TOOLSET_HELP = (
|
|
16
|
+
f"tool definitions: {LATEST_TOOLSET} (default), 2 (as in 0.4.x) "
|
|
17
|
+
"or 1 (as in 0.2.1 to 0.3.x)"
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _need(module: str, extra: str) -> None:
|
|
22
|
+
"""Exit with the install command when the optional dependency `module` is missing."""
|
|
23
|
+
try:
|
|
24
|
+
importlib.import_module(module)
|
|
25
|
+
except ModuleNotFoundError:
|
|
26
|
+
raise SystemExit(
|
|
27
|
+
f'this command needs {module}: pip install "futuresearch-btf[{extra}]"'
|
|
28
|
+
) from None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def main() -> None:
|
|
32
|
+
try:
|
|
33
|
+
_main()
|
|
34
|
+
sys.stdout.flush()
|
|
35
|
+
except BrokenPipeError:
|
|
36
|
+
# the reader closed the pipe early (e.g. `| head`): exit without a traceback
|
|
37
|
+
os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
|
|
38
|
+
sys.exit(1)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _main() -> None:
|
|
42
|
+
ap = argparse.ArgumentParser(prog="python -m futuresearch_btf")
|
|
43
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
44
|
+
|
|
45
|
+
qs = sub.add_parser("questions", help="list the question ids, types and questions")
|
|
46
|
+
qs.add_argument("--data", type=Path, required=True, help=DATA_HELP)
|
|
47
|
+
|
|
48
|
+
s = sub.add_parser(
|
|
49
|
+
"search",
|
|
50
|
+
help="run the search tool for one question, as a model would; one JSON line per result",
|
|
51
|
+
)
|
|
52
|
+
s.add_argument("--data", type=Path, required=True, help=DATA_HELP)
|
|
53
|
+
s.add_argument("--question-id", required=True)
|
|
54
|
+
s.add_argument("query")
|
|
55
|
+
s.add_argument(
|
|
56
|
+
"-k",
|
|
57
|
+
type=int,
|
|
58
|
+
default=10,
|
|
59
|
+
help="max_results, as a model would send it (default 10, at most 50)",
|
|
60
|
+
)
|
|
61
|
+
s.add_argument(
|
|
62
|
+
"--toolset",
|
|
63
|
+
type=int,
|
|
64
|
+
choices=sorted(TOOLSETS),
|
|
65
|
+
default=LATEST_TOOLSET,
|
|
66
|
+
help=TOOLSET_HELP,
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
v = sub.add_parser("serve", help="MCP server (stdio) for one question")
|
|
70
|
+
v.add_argument("--data", type=Path, required=True, help=DATA_HELP)
|
|
71
|
+
v.add_argument("--question-id", required=True)
|
|
72
|
+
v.add_argument(
|
|
73
|
+
"--out",
|
|
74
|
+
type=Path,
|
|
75
|
+
required=True,
|
|
76
|
+
help="where submit_forecast writes the forecast JSON",
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
r = sub.add_parser("run", help="reference agent over LiteLLM")
|
|
80
|
+
r.add_argument("--data", type=Path, required=True, help=DATA_HELP)
|
|
81
|
+
r.add_argument(
|
|
82
|
+
"--model",
|
|
83
|
+
required=True,
|
|
84
|
+
help="a LiteLLM model string, e.g. anthropic/claude-sonnet-5",
|
|
85
|
+
)
|
|
86
|
+
r.add_argument(
|
|
87
|
+
"--out",
|
|
88
|
+
type=Path,
|
|
89
|
+
required=True,
|
|
90
|
+
help="JSONL of forecasts; reruns skip finished questions",
|
|
91
|
+
)
|
|
92
|
+
r.add_argument(
|
|
93
|
+
"--question-ids", nargs="+", help="default: every question in the release"
|
|
94
|
+
)
|
|
95
|
+
r.add_argument("--max-turns", type=int, default=30)
|
|
96
|
+
r.add_argument(
|
|
97
|
+
"--llm-kwargs",
|
|
98
|
+
default="{}",
|
|
99
|
+
help="JSON passed to litellm.completion, e.g. '{\"temperature\": 0}'",
|
|
100
|
+
)
|
|
101
|
+
r.add_argument(
|
|
102
|
+
"--closed-book",
|
|
103
|
+
action="store_true",
|
|
104
|
+
help="no-research baseline: only submit_forecast, no search or reader",
|
|
105
|
+
)
|
|
106
|
+
r.add_argument(
|
|
107
|
+
"--transcripts",
|
|
108
|
+
type=Path,
|
|
109
|
+
help="directory for each question's full conversation, as <question_id>.json",
|
|
110
|
+
)
|
|
111
|
+
r.add_argument(
|
|
112
|
+
"--toolset",
|
|
113
|
+
type=int,
|
|
114
|
+
choices=sorted(TOOLSETS),
|
|
115
|
+
default=LATEST_TOOLSET,
|
|
116
|
+
help=TOOLSET_HELP,
|
|
117
|
+
)
|
|
118
|
+
r.add_argument(
|
|
119
|
+
"--model-cutoff", help="the model's training data cutoff, recorded on each line"
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
h = sub.add_parser(
|
|
123
|
+
"schemas", help="print the tool definitions for a function-calling API, as JSON"
|
|
124
|
+
)
|
|
125
|
+
h.add_argument(
|
|
126
|
+
"--format",
|
|
127
|
+
choices=["openai", "openai-responses", "anthropic", "mcp"],
|
|
128
|
+
default="openai",
|
|
129
|
+
)
|
|
130
|
+
h.add_argument(
|
|
131
|
+
"--toolset",
|
|
132
|
+
type=int,
|
|
133
|
+
choices=sorted(TOOLSETS),
|
|
134
|
+
default=LATEST_TOOLSET,
|
|
135
|
+
help=TOOLSET_HELP,
|
|
136
|
+
)
|
|
137
|
+
h.add_argument(
|
|
138
|
+
"--closed-book",
|
|
139
|
+
action="store_true",
|
|
140
|
+
help="only submit_forecast (no research tools)",
|
|
141
|
+
)
|
|
142
|
+
h.add_argument(
|
|
143
|
+
"--get-question",
|
|
144
|
+
action=argparse.BooleanOptionalAction,
|
|
145
|
+
default=None,
|
|
146
|
+
help="include get_question (default: only for --format mcp)",
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
w = sub.add_parser(
|
|
150
|
+
"serve-http",
|
|
151
|
+
help="HTTP server over the release: every question, JSON in and out",
|
|
152
|
+
)
|
|
153
|
+
w.add_argument("--data", type=Path, required=True, help=DATA_HELP)
|
|
154
|
+
w.add_argument(
|
|
155
|
+
"--host", default="127.0.0.1", help="default 127.0.0.1 (this machine only)"
|
|
156
|
+
)
|
|
157
|
+
w.add_argument(
|
|
158
|
+
"--port", type=int, default=8765, help="default 8765; 0 picks a free port"
|
|
159
|
+
)
|
|
160
|
+
w.add_argument(
|
|
161
|
+
"--token",
|
|
162
|
+
help="require `Authorization: Bearer <token>` (default: $FUTURESEARCH_BTF_TOKEN)",
|
|
163
|
+
)
|
|
164
|
+
w.add_argument("--quiet", action="store_true", help="no per-request log lines")
|
|
165
|
+
w.add_argument(
|
|
166
|
+
"--window-endpoints",
|
|
167
|
+
action="store_true",
|
|
168
|
+
help="also serve POST /v1/search and /v1/read for any research window (trusted callers only)",
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
c = sub.add_parser("score", help="score a run file against the resolutions")
|
|
172
|
+
c.add_argument("--data", type=Path, required=True, help=DATA_HELP)
|
|
173
|
+
c.add_argument("--runs", type=Path, required=True)
|
|
174
|
+
c.add_argument(
|
|
175
|
+
"--json",
|
|
176
|
+
action="store_true",
|
|
177
|
+
help="print the per-question table as JSON instead of the summary",
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
a = ap.parse_args()
|
|
181
|
+
if a.cmd in ("search", "serve") and getattr(a, "question_id", None):
|
|
182
|
+
from .corpus import Release, UnknownQuestion
|
|
183
|
+
|
|
184
|
+
try:
|
|
185
|
+
Release(a.data).question(a.question_id)
|
|
186
|
+
except UnknownQuestion:
|
|
187
|
+
raise SystemExit(
|
|
188
|
+
f"no question {a.question_id!r} in {a.data}; "
|
|
189
|
+
f"`python -m futuresearch_btf questions --data {a.data}` lists them"
|
|
190
|
+
) from None
|
|
191
|
+
if a.cmd == "questions":
|
|
192
|
+
from .corpus import Release
|
|
193
|
+
|
|
194
|
+
qs = Release(a.data).questions[["question_id", "question_type", "question"]]
|
|
195
|
+
for qid, qtype, text in qs.itertuples(index=False):
|
|
196
|
+
print(f"{qid}\t{qtype}\t{text[:100]}")
|
|
197
|
+
elif a.cmd == "search":
|
|
198
|
+
from .corpus import Release
|
|
199
|
+
|
|
200
|
+
# through call_tool, so the command shows what a model gets from `search` in that toolset
|
|
201
|
+
# (toolset 3 reads site: as a filter); one whole result per line instead of one JSON list
|
|
202
|
+
res = Release(a.data).call_tool(
|
|
203
|
+
a.question_id,
|
|
204
|
+
"search",
|
|
205
|
+
{"query": a.query, "max_results": a.k},
|
|
206
|
+
toolset=a.toolset,
|
|
207
|
+
)
|
|
208
|
+
if res.is_error:
|
|
209
|
+
print(res.text)
|
|
210
|
+
raise SystemExit(1)
|
|
211
|
+
for hit in res.output:
|
|
212
|
+
print(json.dumps(hit, default=str, ensure_ascii=False))
|
|
213
|
+
elif a.cmd == "serve":
|
|
214
|
+
_need("mcp", "mcp")
|
|
215
|
+
from .server import serve
|
|
216
|
+
|
|
217
|
+
serve(a.data, a.question_id, a.out)
|
|
218
|
+
elif a.cmd == "serve-http":
|
|
219
|
+
from .http_server import serve_http
|
|
220
|
+
|
|
221
|
+
serve_http(a.data, a.host, a.port, a.token, a.quiet, a.window_endpoints)
|
|
222
|
+
elif a.cmd == "run":
|
|
223
|
+
_need("litellm", "agent")
|
|
224
|
+
from .agent import run
|
|
225
|
+
|
|
226
|
+
run(
|
|
227
|
+
a.data,
|
|
228
|
+
a.model,
|
|
229
|
+
a.out,
|
|
230
|
+
a.question_ids,
|
|
231
|
+
a.max_turns,
|
|
232
|
+
json.loads(a.llm_kwargs),
|
|
233
|
+
a.closed_book,
|
|
234
|
+
a.transcripts,
|
|
235
|
+
a.toolset,
|
|
236
|
+
a.model_cutoff,
|
|
237
|
+
)
|
|
238
|
+
elif a.cmd == "schemas":
|
|
239
|
+
from .tools import schemas
|
|
240
|
+
|
|
241
|
+
print(
|
|
242
|
+
json.dumps(
|
|
243
|
+
schemas(
|
|
244
|
+
a.format,
|
|
245
|
+
closed_book=a.closed_book,
|
|
246
|
+
get_question=a.get_question,
|
|
247
|
+
toolset=a.toolset,
|
|
248
|
+
),
|
|
249
|
+
indent=2,
|
|
250
|
+
)
|
|
251
|
+
)
|
|
252
|
+
elif a.cmd == "score":
|
|
253
|
+
from .score import score
|
|
254
|
+
|
|
255
|
+
df = score(a.data, a.runs, echo=not a.json)
|
|
256
|
+
if a.json:
|
|
257
|
+
print(df.to_json(orient="records"))
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
if __name__ == "__main__":
|
|
261
|
+
main()
|
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
"""Reference forecasting agent: a plain tool-calling loop over LiteLLM.
|
|
2
|
+
|
|
3
|
+
python -m futuresearch_btf run --data <release dir> --model anthropic/claude-opus-5-5 --out runs/opus.jsonl
|
|
4
|
+
|
|
5
|
+
Any model LiteLLM can call with tools works (OpenAI, Anthropic, Gemini, vLLM,
|
|
6
|
+
OpenRouter, ...). The loop is deliberately minimal: the system prompt and the
|
|
7
|
+
question from `prompt.py`, the three tools and one result per tool call. On the
|
|
8
|
+
last turn the model is told to submit; from then on research calls are refused
|
|
9
|
+
and it gets `FINAL_ATTEMPTS` more turns to call `submit_forecast`. The submit is
|
|
10
|
+
asked for in words, not forced through `tool_choice`, because some models
|
|
11
|
+
(Claude Opus 5.5 among them) reject a forced tool call. Results append to `--out`
|
|
12
|
+
as JSONL, one line per question, and a rerun retries only the questions without a forecast.
|
|
13
|
+
|
|
14
|
+
Every turn resends the whole conversation, pages read included, so for Claude
|
|
15
|
+
models the newest message carries a prompt-cache breakpoint (`_cache_points`)
|
|
16
|
+
and the next turn reads everything before it from the cache. OpenAI and Gemini
|
|
17
|
+
cache prefixes on their own.
|
|
18
|
+
|
|
19
|
+
`--closed-book` is the no-research baseline: only `submit_forecast`, and a
|
|
20
|
+
system prompt that says there are no tools. `--transcripts DIR` writes each
|
|
21
|
+
question's full conversation (tool results included) to `DIR/<question_id>.json`.
|
|
22
|
+
|
|
23
|
+
From toolset 2 every line also records how it was made (`_record_settings`): the
|
|
24
|
+
package version (`btf_tools`), `max_turns` and the caller's `llm_kwargs` with secrets
|
|
25
|
+
redacted, so a run can be repeated from its file. Toolset 1 lines keep the
|
|
26
|
+
0.2.1 shape.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import json
|
|
32
|
+
import re
|
|
33
|
+
import time
|
|
34
|
+
from datetime import UTC, datetime
|
|
35
|
+
from pathlib import Path
|
|
36
|
+
from typing import Any
|
|
37
|
+
|
|
38
|
+
from . import __version__
|
|
39
|
+
from .corpus import Release
|
|
40
|
+
from .prompt import render
|
|
41
|
+
from .tools import LATEST_TOOLSET, schemas
|
|
42
|
+
|
|
43
|
+
NUDGE = "Use one of the tools: search, read_page, or submit_forecast."
|
|
44
|
+
NUDGE_CLOSED_BOOK = "Call submit_forecast."
|
|
45
|
+
LAST_TURN = "This is your last turn. Call submit_forecast now."
|
|
46
|
+
OUT_OF_BUDGET = "The research budget is used up. Call submit_forecast now."
|
|
47
|
+
FINAL_ATTEMPTS = 2
|
|
48
|
+
|
|
49
|
+
#: Setting names whose values are written as REDACTED in a run file's `llm_kwargs`: anything
|
|
50
|
+
#: naming a key, secret, token, password, auth (Authorization, X-Auth), cookie or credential.
|
|
51
|
+
#: "tokens" (max_tokens, budget_tokens) are counts, not secrets, so they stay.
|
|
52
|
+
SECRET_NAME = re.compile(
|
|
53
|
+
r"key|secret|token(?!s)|password|auth|cookie|credential", re.IGNORECASE
|
|
54
|
+
)
|
|
55
|
+
REDACTED = "<redacted>"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _redact(x: Any) -> Any:
|
|
59
|
+
"""`x` as JSON-ready data, with the value of every dict key that names a secret replaced
|
|
60
|
+
by REDACTED, at any depth (an `api_key`, or an `x-api-key` inside `extra_headers`)."""
|
|
61
|
+
if isinstance(x, dict):
|
|
62
|
+
return {
|
|
63
|
+
str(k): REDACTED if SECRET_NAME.search(str(k)) else _redact(v)
|
|
64
|
+
for k, v in x.items()
|
|
65
|
+
}
|
|
66
|
+
if isinstance(x, (list, tuple)):
|
|
67
|
+
return [_redact(v) for v in x]
|
|
68
|
+
if x is None or isinstance(x, (str, int, float, bool)):
|
|
69
|
+
return x
|
|
70
|
+
return str(x)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _record_settings(
|
|
74
|
+
rec: dict,
|
|
75
|
+
toolset: int,
|
|
76
|
+
max_turns: int,
|
|
77
|
+
llm_kwargs: dict,
|
|
78
|
+
model_cutoff: str | None,
|
|
79
|
+
) -> None:
|
|
80
|
+
"""What every line records about the run beyond the forecast. Toolset 1 lines are exactly
|
|
81
|
+
the 0.2.1 shape (plus `model_cutoff` when given); later toolsets say which tools, which
|
|
82
|
+
package version, how many turns and which model-call settings made them."""
|
|
83
|
+
if toolset != 1:
|
|
84
|
+
rec["toolset"] = toolset
|
|
85
|
+
rec["btf_tools"] = __version__
|
|
86
|
+
rec["max_turns"] = max_turns
|
|
87
|
+
rec["llm_kwargs"] = _redact(llm_kwargs)
|
|
88
|
+
if model_cutoff:
|
|
89
|
+
rec["model_cutoff"] = model_cutoff
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _cache_points(model: str) -> list[dict]:
|
|
93
|
+
"""LiteLLM `cache_control_injection_points` for this model: one breakpoint on the
|
|
94
|
+
newest message for Claude, none for providers that cache without being asked."""
|
|
95
|
+
return [{"location": "message", "index": -1}] if "claude" in model.lower() else []
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _turn_cost(litellm, resp, usage) -> float | None:
|
|
99
|
+
"""One call's cost in USD, or None when nothing can price it. The provider's own figure comes
|
|
100
|
+
first (OpenRouter returns `usage.cost`); then LiteLLM's price table. That table raises for a model
|
|
101
|
+
it does not know and returns 0.0 for some it knows without prices, so a zero for a call that used
|
|
102
|
+
tokens is unknown, not free."""
|
|
103
|
+
reported = getattr(usage, "cost", None)
|
|
104
|
+
if isinstance(reported, (int, float)) and not isinstance(reported, bool):
|
|
105
|
+
return float(reported)
|
|
106
|
+
try:
|
|
107
|
+
cost = float(litellm.completion_cost(resp) or 0)
|
|
108
|
+
except Exception:
|
|
109
|
+
return None
|
|
110
|
+
used = int(getattr(usage, "prompt_tokens", 0) or 0) + int(
|
|
111
|
+
getattr(usage, "completion_tokens", 0) or 0
|
|
112
|
+
)
|
|
113
|
+
return None if cost == 0 and used else cost
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _record_served(rec: dict, served: list[tuple], toolset: int) -> None:
|
|
117
|
+
"""Who answered: `providers` and `model_versions` (sorted, distinct) and `response_ids` (one per
|
|
118
|
+
call, in order), as the API reported them. Left out when it reported none, and for toolset 1."""
|
|
119
|
+
if toolset == 1:
|
|
120
|
+
return
|
|
121
|
+
providers = sorted({p for p, _m, _i in served if p})
|
|
122
|
+
versions = sorted({m for _p, m, _i in served if m})
|
|
123
|
+
ids = [i for _p, _m, i in served if i]
|
|
124
|
+
if providers:
|
|
125
|
+
rec["providers"] = providers
|
|
126
|
+
if versions:
|
|
127
|
+
rec["model_versions"] = versions
|
|
128
|
+
if ids:
|
|
129
|
+
rec["response_ids"] = ids
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _save_transcript(transcripts: Path | None, rec: dict, messages: list[dict]) -> None:
|
|
133
|
+
if transcripts is None:
|
|
134
|
+
return
|
|
135
|
+
transcripts.mkdir(parents=True, exist_ok=True)
|
|
136
|
+
# bytes with backslashreplace: a lone surrogate a model sent must not lose the forecast
|
|
137
|
+
(transcripts / f"{rec['question_id']}.json").write_bytes(
|
|
138
|
+
json.dumps(
|
|
139
|
+
{**rec, "messages": messages}, default=str, ensure_ascii=False
|
|
140
|
+
).encode("utf-8", "backslashreplace")
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def run_question(
|
|
145
|
+
rel: Release,
|
|
146
|
+
question_id: str,
|
|
147
|
+
model: str,
|
|
148
|
+
max_turns: int = 30,
|
|
149
|
+
closed_book: bool = False,
|
|
150
|
+
transcripts: Path | None = None,
|
|
151
|
+
toolset: int = LATEST_TOOLSET,
|
|
152
|
+
model_cutoff: str | None = None,
|
|
153
|
+
**llm_kwargs,
|
|
154
|
+
) -> dict:
|
|
155
|
+
import litellm # pyright: ignore[reportMissingImports] # optional: pip install futuresearch-btf[agent]
|
|
156
|
+
|
|
157
|
+
# the settings as the caller gave them (what to pass to --llm-kwargs to repeat the run),
|
|
158
|
+
# before the automatic cache breakpoint is added
|
|
159
|
+
given = dict(llm_kwargs)
|
|
160
|
+
points = _cache_points(model)
|
|
161
|
+
if points and "cache_control_injection_points" not in llm_kwargs:
|
|
162
|
+
llm_kwargs = {**llm_kwargs, "cache_control_injection_points": points}
|
|
163
|
+
q = rel.question(question_id)
|
|
164
|
+
# the same definitions every harness gets (tools.TOOLSETS), in OpenAI format
|
|
165
|
+
tools = schemas("openai", closed_book=closed_book, toolset=toolset)
|
|
166
|
+
nudge = NUDGE_CLOSED_BOOK if closed_book else NUDGE
|
|
167
|
+
system, user = render(q, closed_book)
|
|
168
|
+
messages: list[dict] = [
|
|
169
|
+
{"role": "system", "content": system},
|
|
170
|
+
{"role": "user", "content": user},
|
|
171
|
+
]
|
|
172
|
+
rec = {
|
|
173
|
+
"question_id": question_id,
|
|
174
|
+
"model": model,
|
|
175
|
+
"probability": None,
|
|
176
|
+
"cdf": None,
|
|
177
|
+
"rationale": None,
|
|
178
|
+
"turns": 0,
|
|
179
|
+
"searches": 0,
|
|
180
|
+
"reads": 0,
|
|
181
|
+
"cost_usd": 0.0,
|
|
182
|
+
"input_tokens": 0,
|
|
183
|
+
"output_tokens": 0,
|
|
184
|
+
"cache_read_tokens": 0,
|
|
185
|
+
"cache_write_tokens": 0,
|
|
186
|
+
"closed_book": closed_book,
|
|
187
|
+
"error": None,
|
|
188
|
+
}
|
|
189
|
+
# toolset 1 records are exactly the 0.2.1 shape; later toolsets say how they were made
|
|
190
|
+
_record_settings(rec, toolset, max_turns, given, model_cutoff)
|
|
191
|
+
t0 = time.time()
|
|
192
|
+
# (provider, model version, response id) per call: who actually answered (OpenRouter routes one
|
|
193
|
+
# model name to several hosts), recorded from toolset 2 on (toolset 1 keeps the 0.2.1 record)
|
|
194
|
+
served: list[tuple] = []
|
|
195
|
+
for turn in range(max_turns + FINAL_ATTEMPTS):
|
|
196
|
+
final = turn >= max_turns - 1
|
|
197
|
+
if turn == max_turns - 1:
|
|
198
|
+
messages.append({"role": "user", "content": LAST_TURN})
|
|
199
|
+
resp = litellm.completion(
|
|
200
|
+
model=model,
|
|
201
|
+
messages=messages,
|
|
202
|
+
tools=tools,
|
|
203
|
+
tool_choice="auto",
|
|
204
|
+
**llm_kwargs,
|
|
205
|
+
)
|
|
206
|
+
usage = getattr(resp, "usage", None)
|
|
207
|
+
# Anthropic-style fields first, then OpenAI-style prompt_tokens_details (what OpenRouter
|
|
208
|
+
# returns: before 0.5.1 these read 0 for every OpenRouter run)
|
|
209
|
+
details = getattr(usage, "prompt_tokens_details", None)
|
|
210
|
+
rec["input_tokens"] += int(getattr(usage, "prompt_tokens", 0) or 0)
|
|
211
|
+
rec["output_tokens"] += int(getattr(usage, "completion_tokens", 0) or 0)
|
|
212
|
+
rec["cache_read_tokens"] += int(
|
|
213
|
+
getattr(usage, "cache_read_input_tokens", 0)
|
|
214
|
+
or getattr(details, "cached_tokens", 0)
|
|
215
|
+
or 0
|
|
216
|
+
)
|
|
217
|
+
rec["cache_write_tokens"] += int(
|
|
218
|
+
getattr(usage, "cache_creation_input_tokens", 0)
|
|
219
|
+
or getattr(details, "cache_write_tokens", 0)
|
|
220
|
+
or 0
|
|
221
|
+
)
|
|
222
|
+
served.append(
|
|
223
|
+
tuple(
|
|
224
|
+
v if isinstance(v, str) else None
|
|
225
|
+
for v in (
|
|
226
|
+
getattr(resp, "provider", None),
|
|
227
|
+
getattr(resp, "model", None),
|
|
228
|
+
getattr(resp, "id", None),
|
|
229
|
+
)
|
|
230
|
+
)
|
|
231
|
+
)
|
|
232
|
+
cost = _turn_cost(litellm, resp, usage)
|
|
233
|
+
# one unpriced call makes the total unknown: null, never a sum that looks real
|
|
234
|
+
if cost is None:
|
|
235
|
+
rec["cost_usd"] = None
|
|
236
|
+
elif rec["cost_usd"] is not None:
|
|
237
|
+
rec["cost_usd"] += cost
|
|
238
|
+
rec["turns"] = turn + 1
|
|
239
|
+
msg = resp.choices[0].message
|
|
240
|
+
messages.append(msg.model_dump(exclude_none=True))
|
|
241
|
+
calls = msg.tool_calls or []
|
|
242
|
+
if not calls:
|
|
243
|
+
messages.append({"role": "user", "content": LAST_TURN if final else nudge})
|
|
244
|
+
continue
|
|
245
|
+
for call in calls:
|
|
246
|
+
name = call.function.name
|
|
247
|
+
raw = call.function.arguments or "{}"
|
|
248
|
+
research = name in ("search", "read_page")
|
|
249
|
+
# the JSON check and the budget refusal come before the dispatcher, in this order,
|
|
250
|
+
# so a bad-JSON call on the last turn still gets the JSON error
|
|
251
|
+
try:
|
|
252
|
+
json.loads(raw)
|
|
253
|
+
except (
|
|
254
|
+
ValueError,
|
|
255
|
+
RecursionError,
|
|
256
|
+
) as e: # as call_tool: huge ints, deep nesting
|
|
257
|
+
content = json.dumps({"error": f"arguments are not valid JSON: {e}"})
|
|
258
|
+
else:
|
|
259
|
+
if final and research and not closed_book:
|
|
260
|
+
content = json.dumps({"error": OUT_OF_BUDGET})
|
|
261
|
+
else:
|
|
262
|
+
if research and not closed_book:
|
|
263
|
+
rec["searches" if name == "search" else "reads"] += 1
|
|
264
|
+
result = rel.call_tool(
|
|
265
|
+
question_id, name, raw, closed_book=closed_book, toolset=toolset
|
|
266
|
+
)
|
|
267
|
+
if result.forecast is not None:
|
|
268
|
+
rec.update(
|
|
269
|
+
probability=result.forecast["probability"],
|
|
270
|
+
cdf=result.forecast["cdf"],
|
|
271
|
+
rationale=result.forecast["rationale"],
|
|
272
|
+
seconds=round(time.time() - t0, 1),
|
|
273
|
+
)
|
|
274
|
+
for key in ("cited_doc_ids", "invalid_cited_doc_ids"):
|
|
275
|
+
if key in result.forecast:
|
|
276
|
+
rec[key] = result.forecast[key]
|
|
277
|
+
_record_served(rec, served, toolset)
|
|
278
|
+
_save_transcript(transcripts, rec, messages)
|
|
279
|
+
return rec
|
|
280
|
+
content = result.text
|
|
281
|
+
messages.append(
|
|
282
|
+
{"role": "tool", "tool_call_id": call.id, "content": content}
|
|
283
|
+
)
|
|
284
|
+
rec.update(
|
|
285
|
+
error="no valid forecast within max_turns", seconds=round(time.time() - t0, 1)
|
|
286
|
+
)
|
|
287
|
+
_record_served(rec, served, toolset)
|
|
288
|
+
_save_transcript(transcripts, rec, messages)
|
|
289
|
+
return rec
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def run(
|
|
293
|
+
data: Path,
|
|
294
|
+
model: str,
|
|
295
|
+
out: Path,
|
|
296
|
+
question_ids: list[str] | None,
|
|
297
|
+
max_turns: int,
|
|
298
|
+
llm_kwargs: dict,
|
|
299
|
+
closed_book: bool = False,
|
|
300
|
+
transcripts: Path | None = None,
|
|
301
|
+
toolset: int = LATEST_TOOLSET,
|
|
302
|
+
model_cutoff: str | None = None,
|
|
303
|
+
) -> None:
|
|
304
|
+
rel = Release(data)
|
|
305
|
+
ids = question_ids or rel.questions["question_id"].tolist()
|
|
306
|
+
# a rerun retries questions that errored, and skips the ones with a forecast
|
|
307
|
+
done = set()
|
|
308
|
+
if out.exists():
|
|
309
|
+
# read as the scorer does: a half-written line (a killed run) is skipped, not fatal
|
|
310
|
+
from .score import read_runs
|
|
311
|
+
|
|
312
|
+
latest, _bad = read_runs(out)
|
|
313
|
+
mine = {"model": model, "closed_book": closed_book, "toolset": toolset}
|
|
314
|
+
for r in latest.values():
|
|
315
|
+
other = {k: r[k] for k, v in mine.items() if k in r and r[k] != v}
|
|
316
|
+
if other:
|
|
317
|
+
was = ", ".join(f"{k}={v}" for k, v in other.items())
|
|
318
|
+
now = ", ".join(f"{k}={mine[k]}" for k in other)
|
|
319
|
+
raise SystemExit(
|
|
320
|
+
f"{out} holds forecasts made with {was}; this run has {now}. "
|
|
321
|
+
"Use another --out."
|
|
322
|
+
)
|
|
323
|
+
done = {qid for qid, r in latest.items() if not r.get("error")}
|
|
324
|
+
if out.read_bytes()[-1:] not in (b"", b"\n"): # end the half-written line first
|
|
325
|
+
with out.open("a") as fh:
|
|
326
|
+
fh.write("\n")
|
|
327
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
328
|
+
for i, qid in enumerate(ids, 1):
|
|
329
|
+
if qid in done:
|
|
330
|
+
continue
|
|
331
|
+
try:
|
|
332
|
+
rec = run_question(
|
|
333
|
+
rel,
|
|
334
|
+
qid,
|
|
335
|
+
model,
|
|
336
|
+
max_turns,
|
|
337
|
+
closed_book,
|
|
338
|
+
transcripts,
|
|
339
|
+
toolset=toolset,
|
|
340
|
+
model_cutoff=model_cutoff,
|
|
341
|
+
**llm_kwargs,
|
|
342
|
+
)
|
|
343
|
+
except Exception as e:
|
|
344
|
+
rec: dict[str, Any] = {
|
|
345
|
+
"question_id": qid,
|
|
346
|
+
"model": model,
|
|
347
|
+
"error": f"{type(e).__name__}: {e}",
|
|
348
|
+
}
|
|
349
|
+
_record_settings(rec, toolset, max_turns, llm_kwargs, model_cutoff)
|
|
350
|
+
rec["finished_at"] = datetime.now(UTC).isoformat()
|
|
351
|
+
with out.open("a") as fh:
|
|
352
|
+
fh.write(json.dumps(rec) + "\n")
|
|
353
|
+
shown = (
|
|
354
|
+
rec.get("probability")
|
|
355
|
+
if rec.get("probability") is not None
|
|
356
|
+
else rec.get("cdf")
|
|
357
|
+
)
|
|
358
|
+
print(
|
|
359
|
+
f"[{i}/{len(ids)}] {qid[:8]} -> {shown} {rec.get('error') or ''}",
|
|
360
|
+
flush=True,
|
|
361
|
+
)
|