File size: 7,790 Bytes
36dac03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
"""
Baseline inference script for the API Integration Debugging Environment.

This script demonstrates an LLM-powered agent interacting with the environment
using the OpenAI API. It runs all 3 tasks (easy, medium, hard) and reports
baseline scores.

Usage:
    # Set your OpenAI API key
    export OPENAI_API_KEY=your-key-here

    # Run baseline
    python scripts/baseline_inference.py

    # Or specify a server URL
    python scripts/baseline_inference.py --server-url http://localhost:8000
"""

import argparse
import json
import os
import sys
from typing import Any, Dict, List, Optional

# Add parent directory to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from models import ApiDebugAction, ApiDebugObservation
from scenarios import get_all_task_ids, get_scenario
from server.api_debug_env_environment import ApiDebugEnvironment


def run_rule_based_baseline(task_id: str) -> Dict[str, Any]:
    """
    Run a simple rule-based baseline agent (no LLM needed).

    Strategy:
    1. Inspect all logs
    2. Inspect all configs
    3. Test all endpoints
    (Does not attempt fixes — tests reward signal for exploration-only behavior)
    """
    env = ApiDebugEnvironment(task_id=task_id)
    obs = env.reset()
    total_reward = 0.0

    # Phase 1: Inspect all logs
    for service in obs.available_targets:
        if obs.done:
            break
        obs = env.step(ApiDebugAction(action_type="inspect_logs", target=service))
        total_reward += obs.reward

    # Phase 2: Inspect all configs
    for service in obs.available_targets:
        if obs.done:
            break
        obs = env.step(ApiDebugAction(action_type="inspect_config", target=service))
        total_reward += obs.reward

    # Phase 3: Test all endpoints
    for service in obs.available_targets:
        if obs.done:
            break
        obs = env.step(ApiDebugAction(action_type="inspect_endpoint", target=service))
        total_reward += obs.reward

    score = env.grade()
    return {
        "task_id": task_id,
        "score": score,
        "total_reward": round(total_reward, 4),
        "steps_used": env._state.step_count,
        "issues_found": len(env._issues_found),
        "issues_fixed": len(env._issues_fixed),
        "issues_total": len(env._scenario.issues) if env._scenario else 0,
    }


def run_llm_baseline(task_id: str, api_key: Optional[str] = None) -> Dict[str, Any]:
    """
    Run an LLM-powered baseline agent using OpenAI API.

    The LLM reads observations and decides what to do next.
    """
    try:
        from openai import OpenAI
    except ImportError:
        print("OpenAI package not installed. Running rule-based baseline instead.")
        return run_rule_based_baseline(task_id)

    key = api_key or os.environ.get("OPENAI_API_KEY")
    if not key:
        print("No OPENAI_API_KEY set. Running rule-based baseline instead.")
        return run_rule_based_baseline(task_id)

    client = OpenAI(api_key=key)
    env = ApiDebugEnvironment(task_id=task_id)
    obs = env.reset()
    total_reward = 0.0

    system_prompt = f"""You are an API debugging agent. Your task: {obs.task_description}

Available actions:
- inspect_logs: Read error logs for a service
- inspect_config: See the configuration of a service
- inspect_endpoint: Test-call an endpoint
- submit_fix: Submit a config fix (requires fix_payload dict)

Available targets: {obs.available_targets}
Total issues to fix: {obs.issues_total}

Respond with JSON: {{"action_type": "...", "target": "...", "fix_payload": {{...}} }}
Only include fix_payload when action_type is "submit_fix"."""

    messages = [{"role": "system", "content": system_prompt}]

    while not obs.done:
        # Build observation message
        obs_text = f"""Step {env._state.step_count}/{env._scenario.max_steps if env._scenario else '?'}
Remaining steps: {obs.remaining_steps}
Issues found: {obs.issues_found}/{obs.issues_total}
Issues fixed: {obs.issues_fixed}/{obs.issues_total}
Last action result: {obs.action_result}"""

        if obs.logs:
            obs_text += f"\nLogs:\n" + "\n".join(obs.logs)
        if obs.config_snapshot:
            obs_text += f"\nConfig: {json.dumps(obs.config_snapshot, indent=2)}"
        if obs.api_response:
            obs_text += f"\nAPI Response: {json.dumps(obs.api_response, indent=2)}"
        if obs.hints:
            obs_text += f"\nHints: {'; '.join(obs.hints)}"

        messages.append({"role": "user", "content": obs_text})

        try:
            response = client.chat.completions.create(
                model="gpt-4o-mini",
                messages=messages,
                temperature=0.2,
                max_tokens=500,
                response_format={"type": "json_object"},
            )

            action_json = json.loads(response.choices[0].message.content)
            messages.append({"role": "assistant", "content": json.dumps(action_json)})

            action = ApiDebugAction(
                action_type=action_json.get("action_type", "inspect_logs"),
                target=action_json.get("target", obs.available_targets[0] if obs.available_targets else ""),
                fix_payload=action_json.get("fix_payload"),
            )
        except Exception as e:
            print(f"  LLM error: {e}. Falling back to inspect_logs.")
            action = ApiDebugAction(
                action_type="inspect_logs",
                target=obs.available_targets[0] if obs.available_targets else "",
            )

        obs = env.step(action)
        total_reward += obs.reward

    score = env.grade()
    return {
        "task_id": task_id,
        "score": score,
        "total_reward": round(total_reward, 4),
        "steps_used": env._state.step_count,
        "issues_found": len(env._issues_found),
        "issues_fixed": len(env._issues_fixed),
        "issues_total": len(env._scenario.issues) if env._scenario else 0,
    }


def main():
    parser = argparse.ArgumentParser(description="Baseline inference for API Debug Env")
    parser.add_argument("--mode", choices=["rule", "llm"], default="rule",
                        help="Baseline mode: 'rule' for rule-based, 'llm' for LLM-powered")
    parser.add_argument("--api-key", type=str, default=None,
                        help="OpenAI API key (or set OPENAI_API_KEY env var)")
    parser.add_argument("--task", type=str, default=None,
                        help="Run specific task only (easy/medium/hard)")
    args = parser.parse_args()

    print("=" * 60)
    print("API Integration Debugging — Baseline Inference")
    print("=" * 60)

    task_ids = [args.task] if args.task else get_all_task_ids()
    all_results = {}

    for task_id in task_ids:
        print(f"\n{'─' * 40}")
        print(f"Task: {task_id}")
        print(f"{'─' * 40}")

        if args.mode == "llm":
            result = run_llm_baseline(task_id, args.api_key)
        else:
            result = run_rule_based_baseline(task_id)

        all_results[task_id] = result
        print(f"  Score:        {result['score']}")
        print(f"  Reward:       {result['total_reward']}")
        print(f"  Steps:        {result['steps_used']}")
        print(f"  Issues found: {result['issues_found']}/{result['issues_total']}")
        print(f"  Issues fixed: {result['issues_fixed']}/{result['issues_total']}")

    print(f"\n{'=' * 60}")
    print("Summary")
    print(f"{'=' * 60}")
    for tid, res in all_results.items():
        print(f"  {tid:8s}  score={res['score']:.4f}  fixed={res['issues_fixed']}/{res['issues_total']}")

    avg_score = sum(r["score"] for r in all_results.values()) / len(all_results)
    print(f"\n  Average score: {avg_score:.4f}")

    return all_results


if __name__ == "__main__":
    main()