File size: 6,689 Bytes
f1cc981
50bf486
 
 
 
f1cc981
50bf486
f1cc981
 
 
50bf486
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8100965
 
 
 
50bf486
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8100965
 
50bf486
28179dd
 
50bf486
 
8100965
 
 
 
 
 
50bf486
 
 
 
 
 
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
---
title: SQL Debug Env
emoji: πŸ› οΈ
colorFrom: blue
colorTo: purple
sdk: docker
app_port: 7860
pinned: false
---

# sql-debug-env

> Teaching AI agents to debug SQL the way we all had to learn β€” by staring at cryptic error messages and wondering why our JOINs return 47x more rows than expected.

## What is this?

An [OpenEnv](https://github.com/openenv) environment for reinforcement learning. The agent gets a bugged SQL query, a database schema, and some sample data. It tries to fix the query, gets real feedback (actual error messages, result previews, row counts), and iterates until it either nails it or runs out of steps.

Think of it like a SQL homework grader, but the student is an LLM.

### Why SQL?

Honestly, debugging SQL felt like a natural fit for this kind of iterative RL setup:

- **Deterministic grading** β€” run the query against SQLite, compare results mathematically. No fuzzy evaluation needed.
- **Everyone encounters it** β€” data engineers, backend devs, analysts... we've all been there.
- **Genuine feedback loops** β€” not a one-shot problem. The agent can read error messages and actually learn from them mid-episode.
- **Rich partial credit** β€” an almost-right query that returns 90% of the correct rows isn't the same as a completely wrong one.

---

## Tasks

We have 3 tasks right now, ordered by difficulty:

| ID | What it does | Difficulty |
|----|-------------|-----------|
| `fix_syntax` | Fix misspelled keywords, wrong punctuation, etc. | Easy |
| `fix_join` | Fix JOIN that runs fine but gives wrong results (the sneaky kind) | Medium |
| `optimize_query` | Rewrite a correlated subquery that's technically correct but painfully slow | Hard |

---

## How the agent interacts

### Action space

Pretty simple β€” the agent just submits a SQL string:

```json
{ "query": "SELECT name, salary FROM employees WHERE department = 'Engineering' ORDER BY salary DESC" }
```

### What it gets back (observation)

| Field | Type | What it is |
|-------|------|-----------|
| `task_id` | `string` | Which task we're on |
| `broken_query` | `string` | The original bugged query |
| `schema_description` | `string` | Human-readable schema info |
| `error_message` | `string?` | SQL error from last attempt (if any) |
| `result_preview` | `list[dict]?` | First 10 rows of what the query returned |
| `expected_row_count` | `int` | How many rows the correct answer has |
| `current_row_count` | `int?` | How many rows the agent's query returned |
| `step_number` | `int` | Where we are in the episode |
| `max_steps` | `int` | Hard cap (8 steps) |
| `hint` | `string?` | We give hints at certain steps if the agent is struggling |

---

## Scoring

Reward is ∈ [0, 1], broken into 4 components:

| Component | Weight | What earns it |
|-----------|--------|--------------|
| Syntax valid | 0.15 | Query parses without blowing up |
| Row-level F1 | 0.55 | How many correct rows did it get? (precision Γ— recall) |
| Exact match | 0.20 | Bonus for getting it 100% right |
| Efficiency | 0.10 | Task 3 only β€” did it actually get rid of the correlated subquery? |

Episode ends when the agent hits β‰₯0.89 total reward or exhausts all 8 steps.

---

## Database

### Task 1 (employees)
```sql
employees(id, name, department, salary, hire_date)
departments(id, name, budget, manager_id)
```

### Tasks 2 & 3 (e-commerce)
```sql
users(user_id, name, email, region)
orders(order_id, user_id, created_at, status)
order_items(item_id, order_id, product_id, quantity, price)
products(product_id, name, category, unit_price)
```

---

## Getting started

### Prerequisites
- Python 3.10+
- Docker (if you want to deploy it properly)

### Running locally

```bash
# install everything
pip install -e ".[server,inference,dev]"

# fire up the server
python -m uvicorn server.app:app --host 0.0.0.0 --port 7860

# in another terminal β€” run the baseline agent
export API_BASE_URL="https://integrate.api.nvidia.com/v1"   # or any OpenAI-compatible endpoint
export MODEL_NAME="meta/llama-3.3-70b-instruct"             # NVIDIA NIM model name
export HF_TOKEN="your-nvidia-or-hf-api-key-here"           # required β€” no default
export ENV_URL="http://localhost:7860"
python inference.py
```

### Docker

```bash
docker build -t sql-debug-env -f server/Dockerfile .
docker run -p 7860:7860 sql-debug-env

# quick sanity check
curl http://localhost:7860/health
```

### Using the Python client

```python
from sql_debug_env import SQLDebugEnv, SQLAction

with SQLDebugEnv(base_url="http://localhost:7860").sync() as env:
    result = env.reset(task_id="fix_syntax")
    print(result.observation.error_message)  # see what's wrong

    result = env.step(SQLAction(query="SELECT name, salary FROM employees WHERE department = 'Engineering' ORDER BY salary DESC"))
    print(f"reward={result.reward}, done={result.done}")
```

### REST API (if you prefer curl)

```bash
curl -s -X POST http://localhost:7860/reset \
  -H "Content-Type: application/json" \
  -d '{"task_id": "fix_syntax"}' | python -m json.tool
```

---

## Project layout

```
sql-debug-env/
β”œβ”€β”€ openenv.yaml              # OpenEnv manifest
β”œβ”€β”€ README.md
β”œβ”€β”€ inference.py              # Baseline LLM agent
β”œβ”€β”€ pyproject.toml
β”œβ”€β”€ sql_debug_env/            # Client-side package
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ models.py             # Action / Observation / State types
β”‚   └── client.py             # WebSocket client
└── server/
    β”œβ”€β”€ Dockerfile
    β”œβ”€β”€ requirements.txt
    β”œβ”€β”€ app.py                # FastAPI + OpenEnv wiring
    β”œβ”€β”€ environment.py        # Core env logic (reset/step/state)
    β”œβ”€β”€ tasks.py              # Task definitions & broken queries
    β”œβ”€β”€ grader.py             # Reward computation
    └── seed_db.py            # Populates the SQLite DB
```

---

## Baseline scores

Evaluated using NVIDIA NIM (OpenAI-compatible API) with LLaMA 3.3 70B Instruct.
Scores are computed as best reward across all steps per task (0.0–1.0 scale):

Scores are computed as best reward across all steps per task (0.0–1.0 scale):

| Model | fix_syntax | fix_join | optimize_query | Avg |
|-------|-----------|----------|---------------|-----|
| meta/llama-3.3-70b-instruct (NVIDIA NIM) | 0.90 | 0.90 | 1.00 | 0.93 |
| meta/llama-3.1-70b-instruct (NVIDIA NIM) | 0.90 | 0.90 | 0.90 | 0.90 |
| meta/llama-3.1-8b-instruct (NVIDIA NIM) | 0.90 | 0.15 | 0.90 | 0.65 |

> Scores reflect correct queries submitted by the model. `fix_syntax` and `fix_join` max out at 0.90 (no efficiency bonus).
> `optimize_query` earns 1.0 only if the model eliminates the correlated subquery.

---

## License

MIT