File size: 6,176 Bytes
bf80335
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
#!/usr/bin/env python3
"""
Run OpenHands agent experiments with concurrent execution.
"""
import os
import sys
import json
import argparse
import subprocess
from typing import List, Dict, Any
from concurrent.futures import ProcessPoolExecutor, as_completed
from tqdm import tqdm

# Default dataset path
DATASET_PATH = "/eval/dataset.jsonl"
RESULTS_DIR = "/experiments/openhands/results"

# Default configuration
DEFAULT_API_BASE = "http://localhost:60101/v1"
DEFAULT_MODEL = "qwen-3.5-27b"


def load_dataset(path: str = DATASET_PATH) -> List[Dict[str, Any]]:
    """Load questions from dataset.jsonl."""
    questions = []
    with open(path, 'r') as f:
        for line in f:
            line = line.strip()
            if line:
                questions.append(json.loads(line))
    return questions


def run_single_task(args: tuple) -> Dict[str, Any]:
    """
    Run a single OpenHands agent task.

    This function calls run_agent.py as a subprocess to avoid
    issues with forking and OpenHands internal state.

    Args:
        args: Tuple of (question, try_id, llm_name, api_base, model, enable_thinking)

    Returns:
        Dict with result information
    """
    question, try_id, llm_name, api_base, model, enable_thinking = args

    # Build command
    cmd = [
        '/opt/py312/bin/python3', '/experiments/openhands/exp/run_agent.py',
        '--prog', question['prog'],
        '--src-site-id', str(question['src_site_id']),
        '--to-take', str(question['to_take']),
        '--format', question.get('format', 'unknown'),
        '--try-id', str(try_id),
        '--api-base', api_base,
        '--model', model,
        '--llm-name', llm_name,
    ]

    if enable_thinking:
        cmd.append('--enable-thinking')

    try:
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=10800 * 3,  # 3 hours per task
        )

        return {
            'success': result.returncode == 0,
            'question': question,
            'try_id': try_id,
            'stdout': result.stdout,
            'stderr': result.stderr,
        }

    except subprocess.TimeoutExpired:
        return {
            'success': False,
            'question': question,
            'try_id': try_id,
            'error': 'Task timed out',
        }
    except Exception as e:
        return {
            'success': False,
            'question': question,
            'try_id': try_id,
            'error': str(e),
        }


def main():
    parser = argparse.ArgumentParser(description="Run OpenHands agent experiments")

    # Model configuration
    parser.add_argument("--api-base", type=str, default=DEFAULT_API_BASE,
                        help="OpenAI-compatible API base URL")
    parser.add_argument("--model", type=str, default=DEFAULT_MODEL,
                        help="Model name to use")
    parser.add_argument("--llm-name", type=str, default=None,
                        help="LLM name for result directory (defaults to model name)")
    parser.add_argument("--enable-thinking", action="store_true",
                        help="Enable thinking/reasoning mode")

    # Concurrency settings
    parser.add_argument("--concurrency", type=int, default=1,
                        help="Number of concurrent agents (default: 1, recommend low for OpenHands)")

    # Experiment settings
    parser.add_argument("--num-tries", type=int, default=1,
                        help="Number of tries per question")
    parser.add_argument("--dataset", type=str, default=DATASET_PATH,
                        help="Path to dataset.jsonl")
    parser.add_argument("--num-questions", type=int, default=None,
                        help="Number of questions to test (default: all)")
    parser.add_argument("--start-idx", type=int, default=0,
                        help="Start index in dataset")

    args = parser.parse_args()

    # Set LLM name
    llm_name = args.llm_name if args.llm_name else args.model

    # Load dataset
    print(f"Loading dataset from {args.dataset}...")
    questions = load_dataset(args.dataset)
    print(f"Loaded {len(questions)} questions")

    # Apply question selection
    if args.start_idx > 0:
        questions = questions[args.start_idx:]
        print(f"Starting from index {args.start_idx}")

    if args.num_questions:
        questions = questions[:args.num_questions]
        print(f"Testing {args.num_questions} questions")

    # Build task list
    tasks = []
    for question in questions:
        for try_id in range(args.num_tries):
            tasks.append((
                question,
                try_id,
                llm_name,
                args.api_base,
                args.model,
                args.enable_thinking,
            ))

    total_tasks = len(tasks)
    print(f"\nTotal tasks: {total_tasks}")
    print(f"Questions: {len(questions)}, Tries per question: {args.num_tries}")
    print(f"Concurrency: {args.concurrency}")
    print(f"Model: {args.model}")
    print(f"Thinking mode: {args.enable_thinking}")

    # Create results directory
    os.makedirs(RESULTS_DIR, exist_ok=True)

    # Run with progress bar
    completed = 0
    successes = 0

    with ProcessPoolExecutor(max_workers=args.concurrency) as executor:
        futures = {executor.submit(run_single_task, task): task for task in tasks}

        with tqdm(total=total_tasks, desc="Processing") as pbar:
            for future in as_completed(futures):
                try:
                    result = future.result()
                    if result.get('success'):
                        successes += 1
                except Exception as e:
                    print(f"\nTask failed with exception: {e}")

                completed += 1
                pbar.update(1)
                pbar.set_postfix({"success": successes, "remaining": total_tasks - completed})

    print(f"\n\nExperiment completed!")
    print(f"Total tasks: {total_tasks}")
    print(f"Successful: {successes}")
    print(f"Failed: {total_tasks - successes}")
    print(f"Success rate: {successes / total_tasks * 100:.1f}%")


if __name__ == "__main__":
    main()