Datasets:
Commit ·
14a6861
0
Parent(s):
Duplicate from embodied-analysis/FinanceGym
Browse filesCo-authored-by: Embodied Analysis <embodied-analysis@users.noreply.huggingface.co>
- .gitattributes +60 -0
- README.md +321 -0
- assets/financegym-benchmark-results.png +3 -0
- assets/financegym-logo.svg +41 -0
- assets/financegym-teaser.png +3 -0
- data/test-00000-of-00002.parquet +3 -0
- data/test-00001-of-00002.parquet +3 -0
- run_eval.py +446 -0
- scripts/convert_to_parquet.py +120 -0
.gitattributes
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.avro filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.lz4 filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.mds filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
# Audio files - uncompressed
|
| 40 |
+
*.pcm filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
*.sam filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
*.raw filter=lfs diff=lfs merge=lfs -text
|
| 43 |
+
# Audio files - compressed
|
| 44 |
+
*.aac filter=lfs diff=lfs merge=lfs -text
|
| 45 |
+
*.flac filter=lfs diff=lfs merge=lfs -text
|
| 46 |
+
*.mp3 filter=lfs diff=lfs merge=lfs -text
|
| 47 |
+
*.ogg filter=lfs diff=lfs merge=lfs -text
|
| 48 |
+
*.wav filter=lfs diff=lfs merge=lfs -text
|
| 49 |
+
# Image files - uncompressed
|
| 50 |
+
*.bmp filter=lfs diff=lfs merge=lfs -text
|
| 51 |
+
*.gif filter=lfs diff=lfs merge=lfs -text
|
| 52 |
+
*.png filter=lfs diff=lfs merge=lfs -text
|
| 53 |
+
*.tiff filter=lfs diff=lfs merge=lfs -text
|
| 54 |
+
# Image files - compressed
|
| 55 |
+
*.jpg filter=lfs diff=lfs merge=lfs -text
|
| 56 |
+
*.jpeg filter=lfs diff=lfs merge=lfs -text
|
| 57 |
+
*.webp filter=lfs diff=lfs merge=lfs -text
|
| 58 |
+
# Video files - compressed
|
| 59 |
+
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
+
*.webm filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
pretty_name: FinanceGym
|
| 4 |
+
task_categories:
|
| 5 |
+
- image-text-to-text
|
| 6 |
+
tags:
|
| 7 |
+
- benchmark
|
| 8 |
+
- evaluation
|
| 9 |
+
- finance
|
| 10 |
+
- multimodal
|
| 11 |
+
- agent
|
| 12 |
+
- computer-use
|
| 13 |
+
- gui
|
| 14 |
+
- trajectories
|
| 15 |
+
configs:
|
| 16 |
+
- config_name: default
|
| 17 |
+
data_files:
|
| 18 |
+
- split: test
|
| 19 |
+
path: data/test-*.parquet
|
| 20 |
+
---
|
| 21 |
+
|
| 22 |
+
# FinanceGym: A Dataset for Financial Multimodal Agents
|
| 23 |
+
|
| 24 |
+
<p align="center">
|
| 25 |
+
<img src="./assets/financegym-teaser.png" alt="FinanceGym" width="820">
|
| 26 |
+
</p>
|
| 27 |
+
|
| 28 |
+
<p align="center">
|
| 29 |
+
<strong>A dataset for financial multimodal agents.</strong>
|
| 30 |
+
</p>
|
| 31 |
+
|
| 32 |
+
<p align="center">
|
| 33 |
+
<strong>59K+ training samples</strong>
|
| 34 |
+
·
|
| 35 |
+
<strong>2.4K testing samples</strong>
|
| 36 |
+
</p>
|
| 37 |
+
|
| 38 |
+
<p align="center">
|
| 39 |
+
Public test split only
|
| 40 |
+
·
|
| 41 |
+
Apache-2.0
|
| 42 |
+
·
|
| 43 |
+
Source snapshot: August 13, 2026
|
| 44 |
+
</p>
|
| 45 |
+
|
| 46 |
+
<p align="center">
|
| 47 |
+
<a href="https://embodiedanalysis.com/finance-gym">Website</a>
|
| 48 |
+
·
|
| 49 |
+
<a href="https://huggingface.co/datasets/embodied-analysis/FinanceGym/viewer">Dataset Viewer</a>
|
| 50 |
+
</p>
|
| 51 |
+
|
| 52 |
+
---
|
| 53 |
+
|
| 54 |
+
FinanceGym is a finance-oriented dataset designed to teach multimodal agents to turn financial instructions into correctly grounded actions in software interfaces. Each public example combines the task and dialogue context, preceding interaction history, step-level screenshots, the available computer-use tool schema, and a human reference action for the next step. This structure supports controlled evaluation of visual grounding, state tracking, tool use, and action selection in realistic financial workflows.
|
| 55 |
+
|
| 56 |
+
Unlike finance question-answering benchmarks that primarily test what a model knows, FinanceGym tests whether an agent can interpret an interface, follow the state of a multi-step task, and decide what to do next. The public release contains the test set and the training set is available upon request.
|
| 57 |
+
|
| 58 |
+
## Key Facts
|
| 59 |
+
|
| 60 |
+
| Item | Value |
|
| 61 |
+
| --- | ---: |
|
| 62 |
+
| Train split size | 59700 |
|
| 63 |
+
| Test split size | 2397 |
|
| 64 |
+
| Public data split | Test set open-sourced <br>Training set: contact charles@embodiedanalysis.com |
|
| 65 |
+
| Repository size | 1.71 GB |
|
| 66 |
+
| License | Apache-2.0 |
|
| 67 |
+
|
| 68 |
+
## What FinanceGym Trains and Evaluates
|
| 69 |
+
|
| 70 |
+
- **Visual grounding.** Locating controls, fields, charts, tables, and state changes in screenshots.
|
| 71 |
+
- **Context tracking.** Reasoning over multimodal histories containing text, images, tool calls, and tool results.
|
| 72 |
+
- **Computer use.** Selecting the appropriate computer-use operation and its arguments.
|
| 73 |
+
|
| 74 |
+
FinanceGym measures the execution layer of a financial multimodal agent. It is not a benchmark of financial advice quality, regulatory compliance, portfolio performance, or production safety.
|
| 75 |
+
|
| 76 |
+
## How the Data Is Created
|
| 77 |
+
|
| 78 |
+
FinanceGym is produced through an end-to-end human-demonstration pipeline designed to preserve the relationship between a financial task, the interface state, and the action taken by an operator.
|
| 79 |
+
|
| 80 |
+
1. **Task design.** Multi-step tasks are defined around the repetitive execution work found in finance-related roles, including research, data entry, calculation, reconciliation, reporting, and status tracking.
|
| 81 |
+
2. **Human demonstration.** Human operators complete the tasks from start to finish in isolated test environments. Task context, dialogue, step-level screenshots, interface actions, and synchronized narration are preserved.
|
| 82 |
+
3. **Transcription and structuring.** Operator recordings are transcribed and parsed into aligned multimodal trajectories so that each observation can be associated with its action and surrounding context.
|
| 83 |
+
4. **Cleaning and normalization.** Redundant interactions are removed, trajectories are normalized into a consistent action and message structure, and the resulting records are prepared for model use and inspection.
|
| 84 |
+
5. **Review and audit.** Screenshot, action, and narration alignment is reviewed at the step level. Manifests and distribution reports support traceability and coverage analysis.
|
| 85 |
+
6. **Public benchmark packaging.** The public evaluation examples are released as structured `messages`, referenced `images`, a serialized `tools` schema, and the next-action `ground_truth` target.
|
| 86 |
+
|
| 87 |
+
The documented collection workflow uses test environments separated from production networks and excludes real identities, bank-card data, login credentials, phone numbers, and email addresses.
|
| 88 |
+
|
| 89 |
+
## Financial Application Coverage
|
| 90 |
+
|
| 91 |
+
FinanceGym's task design covers the operational work behind multiple finance-related roles. Representative scenario groups from the project documentation include:
|
| 92 |
+
|
| 93 |
+
| Scenario group | Representative workflow | Related roles |
|
| 94 |
+
| --- | --- | --- |
|
| 95 |
+
| Market and investment research | Search for market information, inspect charts and tables, compare instruments, and record findings. | Finance Analyst; Financial Market Researcher; Options Market Researcher; Stock Exchange Researcher |
|
| 96 |
+
| Tax operations | Gather supporting records, research tax information, calculate amounts, validate a filing, and prepare submission or archiving. | Tax Information Researcher |
|
| 97 |
+
| Personal finance and credit | Compare financial products, research credit-card terms, use calculators, and prepare personal-finance analyses. | Personal Finance Specialist; Personal Finance Researcher; Credit Card Research Analyst |
|
| 98 |
+
| Budgeting and revenue | Enter and adjust assumptions, calculate totals, update budget-control sheets, prepare reports, and track revenue status. | Budget Planning & Control Specialist; Revenue Manager; Financial Specialist |
|
| 99 |
+
| Bills, AP/AR, and vendor operations | Enter invoice data, review bills, match records, and track vendor invoices and payments. | Bills & Payables Specialist; Invoice (AP/AR) Data Entry Specialist; Vendor Invoice & Payment Tracking Specialist |
|
| 100 |
+
| Bank reconciliation and expenses | Compare statements with internal records, classify expenses, check totals, and maintain expense logs. | Bank Statement & Expense Log Specialist |
|
| 101 |
+
|
| 102 |
+
These scenarios target high-frequency, standardized execution work. They do not imply that professional judgment, compliance review, or accountable human oversight can be removed from financial operations.
|
| 103 |
+
|
| 104 |
+
## Benchmark Task
|
| 105 |
+
|
| 106 |
+
For each episode, the model receives:
|
| 107 |
+
|
| 108 |
+
- system and user messages;
|
| 109 |
+
- previous assistant messages and tool-call messages;
|
| 110 |
+
- interface screenshots referenced by the conversation; and
|
| 111 |
+
- the available `computer_use` tool definition.
|
| 112 |
+
|
| 113 |
+
The model predicts the next computer-use action or action sequence. The prediction can then be compared with the JSON reference stored in `ground_truth`.
|
| 114 |
+
|
| 115 |
+
Example reference action:
|
| 116 |
+
|
| 117 |
+
```json
|
| 118 |
+
[
|
| 119 |
+
{
|
| 120 |
+
"action": "left_click",
|
| 121 |
+
"coordinate": [504, 555]
|
| 122 |
+
}
|
| 123 |
+
]
|
| 124 |
+
```
|
| 125 |
+
|
| 126 |
+
The public data also contains scrolling and drag interactions. A drag may be represented as an ordered sequence of mouse-down, mouse-move, and mouse-up actions.
|
| 127 |
+
|
| 128 |
+
## Benchmark Results
|
| 129 |
+
|
| 130 |
+
<p align="center">
|
| 131 |
+
<img src="./assets/financegym-benchmark-results.png" alt="FinanceGym benchmark results across eight multimodal agents" width="100%">
|
| 132 |
+
</p>
|
| 133 |
+
|
| 134 |
+
### Run the evaluation
|
| 135 |
+
|
| 136 |
+
Download this dataset repository, install the evaluator dependencies, and set
|
| 137 |
+
an OpenRouter API key:
|
| 138 |
+
|
| 139 |
+
```bash
|
| 140 |
+
pip install -U huggingface_hub pyarrow requests
|
| 141 |
+
hf download embodied-analysis/FinanceGym --repo-type dataset \
|
| 142 |
+
--local-dir FinanceGym
|
| 143 |
+
cd FinanceGym
|
| 144 |
+
export OPENROUTER_API_KEY="your-openrouter-api-key"
|
| 145 |
+
```
|
| 146 |
+
|
| 147 |
+
Evaluate a model once on every test example:
|
| 148 |
+
|
| 149 |
+
```bash
|
| 150 |
+
python run_eval.py 'data/test-*.parquet' \
|
| 151 |
+
--models z-ai/glm-5v-turbo
|
| 152 |
+
```
|
| 153 |
+
|
| 154 |
+
The evaluator reconstructs OpenAI-compatible multimodal messages, calls the
|
| 155 |
+
native `computer_use` tool through OpenRouter, scores each predicted action
|
| 156 |
+
against `ground_truth`, and writes resumable JSONL checkpoints plus
|
| 157 |
+
`openrouter_rollouts/summary.json`. The default is one rollout per example;
|
| 158 |
+
use `--rollouts N` for repeated samples and `--concurrency N` to control API
|
| 159 |
+
parallelism. The key may also be supplied as `OPENROUTER_KEY` or stored in
|
| 160 |
+
`~/.env`.
|
| 161 |
+
|
| 162 |
+
## Dataset Structure
|
| 163 |
+
|
| 164 |
+
| Field | Type | Description |
|
| 165 |
+
| --- | --- | --- |
|
| 166 |
+
| `messages` | `list<struct>` | Multimodal interaction history with `role`, `content`, `tool_calls`, and `tool_call_id`. |
|
| 167 |
+
| `images` | `Sequence(Image())` | JPEG screenshots referenced by the messages, stored in message order. |
|
| 168 |
+
| `tools` | `string` | JSON-serialized OpenAI-compatible `computer_use` tool schema shown to the model. |
|
| 169 |
+
| `ground_truth` | `string` | JSON-serialized reference action list for the next step. |
|
| 170 |
+
|
| 171 |
+
Each `messages[].content` value is a list of typed parts. A text part looks like:
|
| 172 |
+
|
| 173 |
+
```json
|
| 174 |
+
{"type": "text", "text": "..."}
|
| 175 |
+
```
|
| 176 |
+
|
| 177 |
+
An image part stores an index rather than duplicating the image bytes:
|
| 178 |
+
|
| 179 |
+
```json
|
| 180 |
+
{"type": "image", "image_index": 0}
|
| 181 |
+
```
|
| 182 |
+
|
| 183 |
+
`image_index` points to the corresponding screenshot in the row's `images` field.
|
| 184 |
+
|
| 185 |
+
## Quick Start
|
| 186 |
+
|
| 187 |
+
Install the dataset client:
|
| 188 |
+
|
| 189 |
+
```bash
|
| 190 |
+
pip install -U datasets pillow
|
| 191 |
+
```
|
| 192 |
+
|
| 193 |
+
Load the public test split:
|
| 194 |
+
|
| 195 |
+
```python
|
| 196 |
+
import json
|
| 197 |
+
|
| 198 |
+
from datasets import load_dataset
|
| 199 |
+
|
| 200 |
+
dataset = load_dataset(
|
| 201 |
+
"embodied-analysis/FinanceGym",
|
| 202 |
+
split="test",
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
row = dataset[0]
|
| 206 |
+
|
| 207 |
+
print(dataset)
|
| 208 |
+
print(row.keys())
|
| 209 |
+
print(json.loads(row["ground_truth"]))
|
| 210 |
+
print(json.loads(row["tools"]))
|
| 211 |
+
```
|
| 212 |
+
|
| 213 |
+
## Coordinate Convention
|
| 214 |
+
|
| 215 |
+
Reference actions use a nominal **1000 × 1000** coordinate space, while the stored screenshots use their native resolution.
|
| 216 |
+
|
| 217 |
+
Rescale coordinates before drawing an action on a stored screenshot:
|
| 218 |
+
|
| 219 |
+
```python
|
| 220 |
+
ACTION_WIDTH = 1000
|
| 221 |
+
ACTION_HEIGHT = 1000
|
| 222 |
+
IMAGE_WIDTH = 1664
|
| 223 |
+
IMAGE_HEIGHT = 928
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def action_to_image(x_action, y_action):
|
| 227 |
+
x_image = x_action * IMAGE_WIDTH / ACTION_WIDTH
|
| 228 |
+
y_image = y_action * IMAGE_HEIGHT / ACTION_HEIGHT
|
| 229 |
+
return round(x_image), round(y_image)
|
| 230 |
+
```
|
| 231 |
+
|
| 232 |
+
Any published evaluation should state its rounding, clipping, coordinate-tolerance, and invalid-output rules.
|
| 233 |
+
|
| 234 |
+
## Reconstructing OpenAI-Style Multimodal Messages
|
| 235 |
+
|
| 236 |
+
Use `Image(decode=False)` to preserve the original JPEG bytes. Decoding a screenshot to PIL and saving it again would re-encode the image.
|
| 237 |
+
|
| 238 |
+
```python
|
| 239 |
+
import base64
|
| 240 |
+
|
| 241 |
+
from datasets import Image, load_dataset
|
| 242 |
+
|
| 243 |
+
dataset = load_dataset(
|
| 244 |
+
"embodied-analysis/FinanceGym",
|
| 245 |
+
split="test",
|
| 246 |
+
)
|
| 247 |
+
dataset = dataset.cast_column("images", [Image(decode=False)])
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def to_openai_messages(row):
|
| 251 |
+
output = []
|
| 252 |
+
|
| 253 |
+
for message in row["messages"]:
|
| 254 |
+
content = []
|
| 255 |
+
|
| 256 |
+
for part in message["content"]:
|
| 257 |
+
if part["type"] == "text":
|
| 258 |
+
content.append({
|
| 259 |
+
"type": "text",
|
| 260 |
+
"text": part["text"],
|
| 261 |
+
})
|
| 262 |
+
else:
|
| 263 |
+
image = row["images"][part["image_index"]]
|
| 264 |
+
encoded = base64.b64encode(image["bytes"]).decode("utf-8")
|
| 265 |
+
content.append({
|
| 266 |
+
"type": "image_url",
|
| 267 |
+
"image_url": {
|
| 268 |
+
"url": f"data:image/jpeg;base64,{encoded}",
|
| 269 |
+
},
|
| 270 |
+
})
|
| 271 |
+
|
| 272 |
+
reconstructed = {
|
| 273 |
+
"role": message["role"],
|
| 274 |
+
"content": content,
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
if message["tool_calls"]:
|
| 278 |
+
reconstructed["tool_calls"] = message["tool_calls"]
|
| 279 |
+
if message["tool_call_id"] is not None:
|
| 280 |
+
reconstructed["tool_call_id"] = message["tool_call_id"]
|
| 281 |
+
|
| 282 |
+
output.append(reconstructed)
|
| 283 |
+
|
| 284 |
+
return output
|
| 285 |
+
```
|
| 286 |
+
|
| 287 |
+
## Recommended Evaluation Practice
|
| 288 |
+
|
| 289 |
+
FinanceGym provides reference next actions but does not prescribe a single official scoring formula in this dataset card. To make results reproducible, report:
|
| 290 |
+
|
| 291 |
+
- the model, checkpoint, and inference configuration;
|
| 292 |
+
- the prompt and message-conversion procedure;
|
| 293 |
+
- JSON parsing and invalid-output handling;
|
| 294 |
+
- action-name normalization and matching rules;
|
| 295 |
+
- coordinate tolerance for pointer actions;
|
| 296 |
+
- multi-action sequence matching rules; and
|
| 297 |
+
- the aggregation method used for the final score.
|
| 298 |
+
|
| 299 |
+
Evaluate only on the public `test` split and do not use its screenshots, messages, or reference actions as model-training data.
|
| 300 |
+
|
| 301 |
+
## License
|
| 302 |
+
|
| 303 |
+
This repository is released under the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0).
|
| 304 |
+
|
| 305 |
+
## Citation
|
| 306 |
+
|
| 307 |
+
If you use FinanceGym in research or evaluation, please cite the dataset. Use the following provisional BibTeX entry:
|
| 308 |
+
|
| 309 |
+
```bibtex
|
| 310 |
+
@misc{financegym2026,
|
| 311 |
+
title = {FinanceGym: A Benchmark for Financial GUI Agents},
|
| 312 |
+
author = {{Embodied Analysis}},
|
| 313 |
+
year = {2026},
|
| 314 |
+
howpublished = {Hugging Face Datasets},
|
| 315 |
+
url = {https://huggingface.co/datasets/embodied-analysis/FinanceGym}
|
| 316 |
+
}
|
| 317 |
+
```
|
| 318 |
+
|
| 319 |
+
## Contact
|
| 320 |
+
|
| 321 |
+
To contact the team, reachout to [charles@embodiedanalysis.com](charles@embodiedanalysis.com). To report a data issue, share an evaluation result, or ask about collaboration, open a thread in the [FinanceGym Community](https://huggingface.co/datasets/embodied-analysis/FinanceGym/discussions).
|
assets/financegym-benchmark-results.png
ADDED
|
Git LFS Details
|
assets/financegym-logo.svg
ADDED
|
|
assets/financegym-teaser.png
ADDED
|
Git LFS Details
|
data/test-00000-of-00002.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:64bb949eea4e3bc8cb082e4ced66c18740c0a90b65c4cd57e4a37c55d1335c41
|
| 3 |
+
size 846527437
|
data/test-00001-of-00002.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8f8791ef8f70c708735ece54a909d6d8937e8ec23c97f8d51a9988e4328c3a15
|
| 3 |
+
size 864642524
|
run_eval.py
ADDED
|
@@ -0,0 +1,446 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Run and score OpenRouter models on the FinanceGym test split.
|
| 3 |
+
|
| 4 |
+
The output is resumable: one JSONL file is maintained per model and existing
|
| 5 |
+
task/rollout pairs are skipped. Each API call requests one completion because
|
| 6 |
+
OpenRouter providers do not consistently support ``n > 1``.
|
| 7 |
+
|
| 8 |
+
Example:
|
| 9 |
+
python scripts/run_openrouter_rollouts.py data/test-*.parquet
|
| 10 |
+
python scripts/run_openrouter_rollouts.py data/test-*.parquet --limit 2
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import argparse
|
| 16 |
+
import base64
|
| 17 |
+
import glob
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
import random
|
| 21 |
+
import re
|
| 22 |
+
import sys
|
| 23 |
+
import threading
|
| 24 |
+
import time
|
| 25 |
+
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
|
| 26 |
+
from difflib import SequenceMatcher
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
from typing import Any
|
| 29 |
+
|
| 30 |
+
import requests
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
import pyarrow.parquet as pq
|
| 34 |
+
except ImportError:
|
| 35 |
+
sys.exit("Missing dependency: install with `python -m pip install pyarrow requests`.")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
DEFAULT_MODELS = [
|
| 39 |
+
"moonshotai/kimi-k2.6",
|
| 40 |
+
"moonshotai/kimi-k3",
|
| 41 |
+
"qwen/qwen3.8-max",
|
| 42 |
+
"bytedance-seed/seed-2-1-turbo"
|
| 43 |
+
]
|
| 44 |
+
OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions"
|
| 45 |
+
TRANSIENT_HTTP = {408, 409, 425, 429, 500, 502, 503, 504, 522, 524}
|
| 46 |
+
SYSTEM_PROMPT = (
|
| 47 |
+
"You are a GUI agent operating a computer via screenshots. At each step, "
|
| 48 |
+
"decide the next UI action and call the `computer_use` tool with the "
|
| 49 |
+
"appropriate action and arguments. Coordinates are on a 0-999 grid. Call "
|
| 50 |
+
"the tool exactly once per step; do not output the action as plain text."
|
| 51 |
+
)
|
| 52 |
+
COORD_TOL = 50.0
|
| 53 |
+
CLICK_VERBS = {
|
| 54 |
+
"left_click", "right_click", "double_click", "triple_click", "mouse_move",
|
| 55 |
+
"left_mouse_down", "left_mouse_up",
|
| 56 |
+
}
|
| 57 |
+
WRITE_LOCK = threading.Lock()
|
| 58 |
+
PRINT_LOCK = threading.Lock()
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def load_key(env_file: Path) -> str:
|
| 62 |
+
for name in ("OPENROUTER_API_KEY", "OPENROUTER_KEY"):
|
| 63 |
+
if os.environ.get(name):
|
| 64 |
+
return os.environ[name].strip().strip("\"'")
|
| 65 |
+
if env_file.exists():
|
| 66 |
+
for raw in env_file.read_text().splitlines():
|
| 67 |
+
line = raw.strip()
|
| 68 |
+
for name in ("OPENROUTER_API_KEY", "OPENROUTER_KEY"):
|
| 69 |
+
if line.startswith(name + "="):
|
| 70 |
+
return line.split("=", 1)[1].strip().strip("\"'")
|
| 71 |
+
raise SystemExit(f"No OPENROUTER_KEY or OPENROUTER_API_KEY found in env or {env_file}")
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def data_url(image: Any) -> str:
|
| 75 |
+
if isinstance(image, dict):
|
| 76 |
+
blob = image.get("bytes")
|
| 77 |
+
if blob is None and image.get("path"):
|
| 78 |
+
blob = Path(image["path"]).read_bytes()
|
| 79 |
+
else:
|
| 80 |
+
blob = image
|
| 81 |
+
if isinstance(blob, memoryview):
|
| 82 |
+
blob = blob.tobytes()
|
| 83 |
+
if not isinstance(blob, bytes):
|
| 84 |
+
raise TypeError(f"Unsupported image value: {type(image)!r}")
|
| 85 |
+
return "data:image/jpeg;base64," + base64.b64encode(blob).decode("ascii")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def openai_messages(row: dict[str, Any]) -> list[dict[str, Any]]:
|
| 89 |
+
images = row["images"]
|
| 90 |
+
messages: list[dict[str, Any]] = []
|
| 91 |
+
for source in row["messages"]:
|
| 92 |
+
parts = []
|
| 93 |
+
for part in source.get("content") or []:
|
| 94 |
+
if part.get("type") == "text":
|
| 95 |
+
parts.append({"type": "text", "text": part.get("text") or ""})
|
| 96 |
+
elif part.get("type") == "image":
|
| 97 |
+
parts.append({
|
| 98 |
+
"type": "image_url",
|
| 99 |
+
"image_url": {"url": data_url(images[part["image_index"]])},
|
| 100 |
+
})
|
| 101 |
+
message: dict[str, Any] = {"role": source["role"], "content": parts}
|
| 102 |
+
if source.get("tool_calls"):
|
| 103 |
+
message["tool_calls"] = source["tool_calls"]
|
| 104 |
+
if source.get("tool_call_id") is not None:
|
| 105 |
+
message["tool_call_id"] = source["tool_call_id"]
|
| 106 |
+
messages.append(message)
|
| 107 |
+
if messages and messages[0]["role"] == "system":
|
| 108 |
+
messages[0] = {"role": "system", "content": SYSTEM_PROMPT}
|
| 109 |
+
else:
|
| 110 |
+
messages.insert(0, {"role": "system", "content": SYSTEM_PROMPT})
|
| 111 |
+
return messages
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def parse_actions(message: dict[str, Any]) -> list[dict[str, Any]]:
|
| 115 |
+
actions = []
|
| 116 |
+
for call in message.get("tool_calls") or []:
|
| 117 |
+
fn = call.get("function") or {}
|
| 118 |
+
value = fn.get("arguments")
|
| 119 |
+
try:
|
| 120 |
+
value = json.loads(value) if isinstance(value, str) else value
|
| 121 |
+
except json.JSONDecodeError:
|
| 122 |
+
continue
|
| 123 |
+
if isinstance(value, dict):
|
| 124 |
+
actions.append(value)
|
| 125 |
+
if actions:
|
| 126 |
+
return actions
|
| 127 |
+
content = message.get("content") or ""
|
| 128 |
+
if isinstance(content, list):
|
| 129 |
+
content = " ".join(p.get("text", "") for p in content if isinstance(p, dict))
|
| 130 |
+
for match in re.finditer(r"<tool_call>\s*(\{.*?\})\s*</tool_call>", content, re.S):
|
| 131 |
+
try:
|
| 132 |
+
value = json.loads(match.group(1))
|
| 133 |
+
value = value.get("arguments", value)
|
| 134 |
+
value = json.loads(value) if isinstance(value, str) else value
|
| 135 |
+
if isinstance(value, dict):
|
| 136 |
+
actions.append(value)
|
| 137 |
+
except (json.JSONDecodeError, AttributeError):
|
| 138 |
+
pass
|
| 139 |
+
return actions
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def coord_score(a: Any, b: Any) -> float:
|
| 143 |
+
try:
|
| 144 |
+
distance = ((float(a[0]) - float(b[0])) ** 2 + (float(a[1]) - float(b[1])) ** 2) ** 0.5
|
| 145 |
+
return max(0.0, 1.0 - distance / COORD_TOL)
|
| 146 |
+
except (TypeError, ValueError, IndexError):
|
| 147 |
+
return 0.0
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def pair_score(pred: dict[str, Any], gt: dict[str, Any]) -> float:
|
| 151 |
+
if pred.get("action") != gt.get("action"):
|
| 152 |
+
return 0.0
|
| 153 |
+
verb = gt.get("action")
|
| 154 |
+
values = []
|
| 155 |
+
if verb in CLICK_VERBS or "coordinate" in gt:
|
| 156 |
+
values.append(coord_score(pred.get("coordinate"), gt.get("coordinate")))
|
| 157 |
+
if verb == "type":
|
| 158 |
+
a, b = str(pred.get("text") or "").strip(), str(gt.get("text") or "").strip()
|
| 159 |
+
values.append(1.0 if a == b else 0.9 if a.lower() == b.lower() else SequenceMatcher(None, a, b).ratio())
|
| 160 |
+
if verb == "key":
|
| 161 |
+
a, b = [str(x).lower() for x in pred.get("keys") or []], [str(x).lower() for x in gt.get("keys") or []]
|
| 162 |
+
remaining, common = list(b), 0
|
| 163 |
+
for key in a:
|
| 164 |
+
if key in remaining:
|
| 165 |
+
common += 1
|
| 166 |
+
remaining.remove(key)
|
| 167 |
+
values.append(common / (max(len(a), len(b)) or 1))
|
| 168 |
+
if verb == "scroll" and pred.get("pixels") is not None and gt.get("pixels") is not None:
|
| 169 |
+
p, g = float(pred["pixels"]), float(gt["pixels"])
|
| 170 |
+
same_direction = (p >= 0) == (g >= 0)
|
| 171 |
+
magnitude = 1.0 - min(1.0, abs(p - g) / (abs(g) + 1e-6))
|
| 172 |
+
values.append((0.5 if same_direction else 0.0) + 0.5 * max(0.0, magnitude))
|
| 173 |
+
if verb == "terminate":
|
| 174 |
+
values.append(float(pred.get("status") == gt.get("status")))
|
| 175 |
+
return sum(values) / len(values) if values else 1.0
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def normalize_drags(actions: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
| 179 |
+
out, index = [], 0
|
| 180 |
+
while index < len(actions):
|
| 181 |
+
action = actions[index]
|
| 182 |
+
if (index + 2 < len(actions) and action.get("action") == "left_mouse_down"
|
| 183 |
+
and actions[index + 1].get("action") == "mouse_move"
|
| 184 |
+
and actions[index + 2].get("action") == "left_mouse_up"):
|
| 185 |
+
out.append({"action": "drag", "start": action.get("coordinate"),
|
| 186 |
+
"end": actions[index + 2].get("coordinate") or actions[index + 1].get("coordinate")})
|
| 187 |
+
index += 3
|
| 188 |
+
elif action.get("action") == "left_click_drag":
|
| 189 |
+
out.append({"action": "drag", "start": None, "end": action.get("coordinate")})
|
| 190 |
+
index += 1
|
| 191 |
+
else:
|
| 192 |
+
out.append(action)
|
| 193 |
+
index += 1
|
| 194 |
+
return out
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def score(message: dict[str, Any], ground_truth: str) -> tuple[float, list[dict[str, Any]]]:
|
| 198 |
+
pred = normalize_drags(parse_actions(message))
|
| 199 |
+
gt = normalize_drags(json.loads(ground_truth))
|
| 200 |
+
if not gt or not pred:
|
| 201 |
+
return 0.0, pred
|
| 202 |
+
total = 0.0
|
| 203 |
+
for index, expected in enumerate(gt):
|
| 204 |
+
if index >= len(pred):
|
| 205 |
+
continue
|
| 206 |
+
actual = pred[index]
|
| 207 |
+
if expected.get("action") == actual.get("action") == "drag":
|
| 208 |
+
values = [coord_score(actual.get("end"), expected.get("end"))]
|
| 209 |
+
if actual.get("start") is not None and expected.get("start") is not None:
|
| 210 |
+
values.append(coord_score(actual["start"], expected["start"]))
|
| 211 |
+
total += sum(values) / len(values)
|
| 212 |
+
else:
|
| 213 |
+
total += pair_score(actual, expected)
|
| 214 |
+
return total / max(len(gt), len(pred)), pred
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def retry_delay(response: requests.Response | None, attempt: int, maximum: float) -> float:
|
| 218 |
+
"""Honor Retry-After, otherwise use capped exponential backoff + full jitter."""
|
| 219 |
+
if response is not None:
|
| 220 |
+
value = response.headers.get("Retry-After")
|
| 221 |
+
if value:
|
| 222 |
+
try:
|
| 223 |
+
return min(maximum, max(0.0, float(value)))
|
| 224 |
+
except ValueError:
|
| 225 |
+
pass
|
| 226 |
+
if response.status_code == 429:
|
| 227 |
+
# Provider-wide TPM limits need a materially longer pause than a
|
| 228 |
+
# transport failure; short retries create a thundering herd.
|
| 229 |
+
low = min(maximum, 10.0 * (2.0 ** attempt))
|
| 230 |
+
high = min(maximum, 20.0 * (2.0 ** attempt))
|
| 231 |
+
return random.uniform(low, max(low, high))
|
| 232 |
+
ceiling = min(maximum, 2.0 ** attempt)
|
| 233 |
+
return random.uniform(0.5, max(0.5, ceiling))
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def api_call(key: str, payload: dict[str, Any], timeout: int, retries: int,
|
| 237 |
+
max_backoff: float) -> tuple[dict[str, Any] | None, str | None, bool]:
|
| 238 |
+
"""Return (response, error, retryable).
|
| 239 |
+
|
| 240 |
+
OpenRouter may route successive requests to different providers. Transient
|
| 241 |
+
statuses are retried here; if exhausted, retryable=True ensures a later
|
| 242 |
+
program invocation attempts the rollout again.
|
| 243 |
+
"""
|
| 244 |
+
headers = {"Authorization": f"Bearer {key}", "Content-Type": "application/json"}
|
| 245 |
+
last_error = None
|
| 246 |
+
retryable = True
|
| 247 |
+
for attempt in range(retries):
|
| 248 |
+
response = None
|
| 249 |
+
try:
|
| 250 |
+
response = requests.post(OPENROUTER_URL, headers=headers, json=payload, timeout=timeout)
|
| 251 |
+
if response.status_code == 200:
|
| 252 |
+
body = response.json()
|
| 253 |
+
if body.get("choices"):
|
| 254 |
+
return body, None, False
|
| 255 |
+
last_error = f"empty response: {str(body)[:300]}"
|
| 256 |
+
else:
|
| 257 |
+
last_error = f"HTTP {response.status_code}: {response.text[:500]}"
|
| 258 |
+
retryable = response.status_code in TRANSIENT_HTTP
|
| 259 |
+
if not retryable:
|
| 260 |
+
break
|
| 261 |
+
except (requests.Timeout, requests.ConnectionError) as exc:
|
| 262 |
+
last_error = f"{type(exc).__name__}: {exc}"
|
| 263 |
+
retryable = True
|
| 264 |
+
except requests.RequestException as exc:
|
| 265 |
+
last_error = f"{type(exc).__name__}: {exc}"
|
| 266 |
+
retryable = False
|
| 267 |
+
break
|
| 268 |
+
if attempt + 1 < retries:
|
| 269 |
+
delay = retry_delay(response, attempt, max_backoff)
|
| 270 |
+
with PRINT_LOCK:
|
| 271 |
+
print(f" retry {attempt + 1}/{retries - 1} in {delay:.1f}s: {last_error[:180]}", flush=True)
|
| 272 |
+
time.sleep(delay)
|
| 273 |
+
return None, last_error, retryable
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def count_rows(paths: list[str], limit: int) -> int:
|
| 277 |
+
total = sum(pq.ParquetFile(path).metadata.num_rows for path in paths)
|
| 278 |
+
return min(total, limit) if limit else total
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def iter_rows(paths: list[str], limit: int):
|
| 282 |
+
task_id = 0
|
| 283 |
+
for path in paths:
|
| 284 |
+
parquet = pq.ParquetFile(path)
|
| 285 |
+
for batch in parquet.iter_batches(batch_size=8):
|
| 286 |
+
for row in batch.to_pylist():
|
| 287 |
+
row["task_id"] = task_id
|
| 288 |
+
yield row
|
| 289 |
+
task_id += 1
|
| 290 |
+
if limit and task_id >= limit:
|
| 291 |
+
return
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def safe_name(model: str) -> str:
|
| 295 |
+
return re.sub(r"[^A-Za-z0-9._-]+", "__", model)
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def normalized_tools(value: Any) -> list[dict[str, Any]]:
|
| 299 |
+
"""Return provider-portable JSON Schema for the dataset's native tools."""
|
| 300 |
+
tools = json.loads(value) if isinstance(value, str) else value
|
| 301 |
+
# Round-trip so the Parquet row is never mutated across model calls.
|
| 302 |
+
tools = json.loads(json.dumps(tools))
|
| 303 |
+
for tool in tools:
|
| 304 |
+
properties = (((tool.get("function") or {}).get("parameters") or {})
|
| 305 |
+
.get("properties") or {})
|
| 306 |
+
for name, schema in properties.items():
|
| 307 |
+
if schema.get("type") == "array" and "items" not in schema:
|
| 308 |
+
schema["items"] = {"type": "number" if name == "coordinate" else "string"}
|
| 309 |
+
return tools
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def completed_keys(path: Path) -> set[tuple[int, int]]:
|
| 313 |
+
done = set()
|
| 314 |
+
if path.exists():
|
| 315 |
+
for line in path.read_text().splitlines():
|
| 316 |
+
try:
|
| 317 |
+
item = json.loads(line)
|
| 318 |
+
# Failed attempts remain eligible on the next invocation.
|
| 319 |
+
if item.get("ok") and item.get("score") is not None:
|
| 320 |
+
done.add((int(item["task_id"]), int(item["rollout"])))
|
| 321 |
+
except (json.JSONDecodeError, KeyError, ValueError):
|
| 322 |
+
pass
|
| 323 |
+
return done
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def run_one(key: str, model: str, row: dict[str, Any], rollout: int, args: argparse.Namespace) -> dict[str, Any]:
|
| 327 |
+
payload = {
|
| 328 |
+
"model": model,
|
| 329 |
+
"messages": openai_messages(row),
|
| 330 |
+
"tools": normalized_tools(row["tools"]),
|
| 331 |
+
"tool_choice": "auto",
|
| 332 |
+
"temperature": args.temperature,
|
| 333 |
+
"max_tokens": args.max_tokens,
|
| 334 |
+
}
|
| 335 |
+
body, error, retryable = api_call(
|
| 336 |
+
key, payload, args.timeout, args.retries, args.max_backoff
|
| 337 |
+
)
|
| 338 |
+
if body:
|
| 339 |
+
message = body["choices"][0].get("message") or {}
|
| 340 |
+
value, actions = score(message, row["ground_truth"])
|
| 341 |
+
return {"task_id": row["task_id"], "rollout": rollout, "score": value,
|
| 342 |
+
"ok": True, "actions": actions, "message": message,
|
| 343 |
+
"usage": body.get("usage")}
|
| 344 |
+
return {"task_id": row["task_id"], "rollout": rollout, "score": None,
|
| 345 |
+
"ok": False, "retryable": retryable, "error": error}
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def summarize(path: Path, model: str) -> dict[str, Any]:
|
| 349 |
+
records = [json.loads(line) for line in path.read_text().splitlines() if line.strip()]
|
| 350 |
+
good = [r for r in records if r.get("ok") and r.get("score") is not None]
|
| 351 |
+
task_scores: dict[int, list[float]] = {}
|
| 352 |
+
for item in good:
|
| 353 |
+
task_scores.setdefault(item["task_id"], []).append(float(item["score"]))
|
| 354 |
+
per_task = [sum(values) / len(values) for values in task_scores.values()]
|
| 355 |
+
return {"model": model, "successful_rollouts": len(good), "total_records": len(records),
|
| 356 |
+
"tasks_with_success": len(task_scores),
|
| 357 |
+
"average_score": sum(per_task) / len(per_task) if per_task else None}
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def main() -> None:
|
| 361 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 362 |
+
parser.add_argument("input", nargs="+", help="Input Parquet file(s); shell globs are accepted")
|
| 363 |
+
parser.add_argument("--models", nargs="+", default=DEFAULT_MODELS)
|
| 364 |
+
parser.add_argument("--rollouts", type=int, default=1)
|
| 365 |
+
parser.add_argument("--output-dir", type=Path, default=Path("openrouter_rollouts"))
|
| 366 |
+
parser.add_argument("--env-file", type=Path, default=Path.home() / ".env")
|
| 367 |
+
parser.add_argument("--concurrency", type=int, default=8)
|
| 368 |
+
parser.add_argument("--temperature", type=float, default=1.0)
|
| 369 |
+
parser.add_argument("--max-tokens", type=int, default=2048)
|
| 370 |
+
parser.add_argument("--timeout", type=int, default=300)
|
| 371 |
+
parser.add_argument("--retries", type=int, default=5)
|
| 372 |
+
parser.add_argument("--max-backoff", type=float, default=60.0,
|
| 373 |
+
help="Maximum seconds between API retries")
|
| 374 |
+
parser.add_argument("--limit", type=int, default=0, help="Only run the first N tasks (smoke tests)")
|
| 375 |
+
args = parser.parse_args()
|
| 376 |
+
if args.rollouts < 1 or args.concurrency < 1:
|
| 377 |
+
parser.error("--rollouts and --concurrency must be positive")
|
| 378 |
+
|
| 379 |
+
paths = sorted({p for pattern in args.input for p in (glob.glob(pattern) or [pattern])})
|
| 380 |
+
missing = [p for p in paths if not Path(p).is_file()]
|
| 381 |
+
if missing:
|
| 382 |
+
parser.error("Input file(s) not found: " + ", ".join(missing))
|
| 383 |
+
key = load_key(args.env_file)
|
| 384 |
+
row_count = count_rows(paths, args.limit)
|
| 385 |
+
args.output_dir.mkdir(parents=True, exist_ok=True)
|
| 386 |
+
print(f"Found {row_count} test tasks in {len(paths)} file(s)", flush=True)
|
| 387 |
+
|
| 388 |
+
summaries = []
|
| 389 |
+
for model in args.models:
|
| 390 |
+
path = args.output_dir / f"{safe_name(model)}.jsonl"
|
| 391 |
+
done = completed_keys(path)
|
| 392 |
+
pending_count = row_count * args.rollouts - len(done)
|
| 393 |
+
print(f"{model}: completed={len(done)} pending={pending_count}", flush=True)
|
| 394 |
+
with path.open("a", encoding="utf-8") as output, ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
| 395 |
+
futures = {}
|
| 396 |
+
completed = 0
|
| 397 |
+
|
| 398 |
+
def collect(future) -> None:
|
| 399 |
+
nonlocal completed
|
| 400 |
+
try:
|
| 401 |
+
record = future.result()
|
| 402 |
+
except Exception as exc:
|
| 403 |
+
task_id, rollout = futures[future]
|
| 404 |
+
record = {"task_id": task_id, "rollout": rollout, "score": None,
|
| 405 |
+
"ok": False, "retryable": True,
|
| 406 |
+
"error": f"{type(exc).__name__}: {exc}"}
|
| 407 |
+
output.write(json.dumps(record, ensure_ascii=False) + "\n")
|
| 408 |
+
output.flush()
|
| 409 |
+
completed += 1
|
| 410 |
+
if completed % 25 == 0 or completed == pending_count:
|
| 411 |
+
print(f" {model}: {completed}/{pending_count} new rollouts", flush=True)
|
| 412 |
+
|
| 413 |
+
for row in iter_rows(paths, args.limit):
|
| 414 |
+
for rollout in range(args.rollouts):
|
| 415 |
+
if (row["task_id"], rollout) in done:
|
| 416 |
+
continue
|
| 417 |
+
while len(futures) >= args.concurrency * 2:
|
| 418 |
+
finished, _ = wait(futures, return_when=FIRST_COMPLETED)
|
| 419 |
+
for future in finished:
|
| 420 |
+
collect(future)
|
| 421 |
+
del futures[future]
|
| 422 |
+
future = pool.submit(run_one, key, model, row, rollout, args)
|
| 423 |
+
futures[future] = (row["task_id"], rollout)
|
| 424 |
+
while futures:
|
| 425 |
+
finished, _ = wait(futures, return_when=FIRST_COMPLETED)
|
| 426 |
+
for future in finished:
|
| 427 |
+
collect(future)
|
| 428 |
+
del futures[future]
|
| 429 |
+
result = summarize(path, model)
|
| 430 |
+
summaries.append(result)
|
| 431 |
+
print(json.dumps(result, ensure_ascii=False), flush=True)
|
| 432 |
+
|
| 433 |
+
summary_path = args.output_dir / "summary.json"
|
| 434 |
+
combined = {}
|
| 435 |
+
if summary_path.exists():
|
| 436 |
+
try:
|
| 437 |
+
combined = {item["model"]: item for item in json.loads(summary_path.read_text())}
|
| 438 |
+
except (json.JSONDecodeError, KeyError, TypeError):
|
| 439 |
+
combined = {}
|
| 440 |
+
combined.update({item["model"]: item for item in summaries})
|
| 441 |
+
summary_path.write_text(json.dumps(list(combined.values()), indent=2) + "\n")
|
| 442 |
+
print(f"Summary written to {summary_path}")
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
if __name__ == "__main__":
|
| 446 |
+
main()
|
scripts/convert_to_parquet.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Convert raw shard_*.jsonl trajectories into viewer-friendly Parquet.
|
| 2 |
+
|
| 3 |
+
The raw JSONL uses OpenAI chat format, where `content` is sometimes a string
|
| 4 |
+
and sometimes a list of parts. Arrow has no union type, so that field alone
|
| 5 |
+
prevents the Hub from building a Parquet conversion (and therefore the viewer).
|
| 6 |
+
|
| 7 |
+
This script normalizes `content` to always be a list of parts, and lifts the
|
| 8 |
+
base64 screenshots out into a top-level `images` column typed as Image() so the
|
| 9 |
+
viewer renders thumbnails instead of 165 KB of base64 text.
|
| 10 |
+
|
| 11 |
+
Usage:
|
| 12 |
+
python scripts/convert_to_parquet.py ~/Downloads/shard_*.jsonl -o data/
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import argparse
|
| 16 |
+
import base64
|
| 17 |
+
import json
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
from datasets import Dataset, Features, Image, Sequence, Value
|
| 21 |
+
|
| 22 |
+
DEFAULT_SPLIT = "test" # FinanceGym ships as an eval set
|
| 23 |
+
|
| 24 |
+
FEATURES = Features(
|
| 25 |
+
{
|
| 26 |
+
"ground_truth": Value("string"), # JSON: list of actions
|
| 27 |
+
"tools": Value("string"), # JSON: OpenAI tool schema
|
| 28 |
+
"images": Sequence(Image()),
|
| 29 |
+
"messages": [
|
| 30 |
+
{
|
| 31 |
+
"role": Value("string"),
|
| 32 |
+
"content": [
|
| 33 |
+
{
|
| 34 |
+
"type": Value("string"), # "text" | "image"
|
| 35 |
+
"text": Value("string"),
|
| 36 |
+
"image_index": Value("int32"), # -> images[i], -1 for text
|
| 37 |
+
}
|
| 38 |
+
],
|
| 39 |
+
"tool_calls": [
|
| 40 |
+
{
|
| 41 |
+
"id": Value("string"),
|
| 42 |
+
"type": Value("string"),
|
| 43 |
+
"function": {
|
| 44 |
+
"name": Value("string"),
|
| 45 |
+
"arguments": Value("string"),
|
| 46 |
+
},
|
| 47 |
+
}
|
| 48 |
+
],
|
| 49 |
+
"tool_call_id": Value("string"),
|
| 50 |
+
}
|
| 51 |
+
],
|
| 52 |
+
}
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def convert_row(raw):
|
| 57 |
+
images = []
|
| 58 |
+
messages = []
|
| 59 |
+
|
| 60 |
+
for msg in raw["messages"]:
|
| 61 |
+
content = msg["content"]
|
| 62 |
+
# Normalize the str/list union into a single list-of-parts shape.
|
| 63 |
+
if isinstance(content, str):
|
| 64 |
+
content = [{"type": "text", "text": content}]
|
| 65 |
+
|
| 66 |
+
parts = []
|
| 67 |
+
for part in content:
|
| 68 |
+
if part["type"] == "text":
|
| 69 |
+
parts.append({"type": "text", "text": part["text"], "image_index": -1})
|
| 70 |
+
else:
|
| 71 |
+
url = part["image_url"]["url"]
|
| 72 |
+
images.append(base64.b64decode(url.split(",", 1)[1]))
|
| 73 |
+
parts.append(
|
| 74 |
+
{"type": "image", "text": None, "image_index": len(images) - 1}
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
messages.append(
|
| 78 |
+
{
|
| 79 |
+
"role": msg["role"],
|
| 80 |
+
"content": parts,
|
| 81 |
+
"tool_calls": msg.get("tool_calls") or [],
|
| 82 |
+
"tool_call_id": msg.get("tool_call_id"),
|
| 83 |
+
}
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
return {
|
| 87 |
+
"ground_truth": raw["ground_truth"],
|
| 88 |
+
"tools": json.dumps(raw["tools"]),
|
| 89 |
+
"images": images,
|
| 90 |
+
"messages": messages,
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def main():
|
| 95 |
+
ap = argparse.ArgumentParser()
|
| 96 |
+
ap.add_argument("shards", nargs="+", type=Path)
|
| 97 |
+
ap.add_argument("-o", "--outdir", type=Path, default=Path("data"))
|
| 98 |
+
ap.add_argument("--split", default=DEFAULT_SPLIT)
|
| 99 |
+
args = ap.parse_args()
|
| 100 |
+
|
| 101 |
+
args.outdir.mkdir(parents=True, exist_ok=True)
|
| 102 |
+
shards = sorted(args.shards)
|
| 103 |
+
|
| 104 |
+
def gen():
|
| 105 |
+
for shard in shards:
|
| 106 |
+
with open(shard) as f:
|
| 107 |
+
for line in f:
|
| 108 |
+
yield convert_row(json.loads(line))
|
| 109 |
+
|
| 110 |
+
ds = Dataset.from_generator(gen, features=FEATURES)
|
| 111 |
+
|
| 112 |
+
n = len(shards)
|
| 113 |
+
for i, shard in enumerate(ds.shard(num_shards=n, index=j) for j in range(n)):
|
| 114 |
+
out = args.outdir / f"{args.split}-{i:05d}-of-{n:05d}.parquet"
|
| 115 |
+
shard.to_parquet(out)
|
| 116 |
+
print(f"{out} {len(shard)} rows {out.stat().st_size / 1e6:.1f} MB")
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
if __name__ == "__main__":
|
| 120 |
+
main()
|