File size: 9,498 Bytes
9952eb5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16624b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9952eb5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16624b8
9952eb5
 
 
 
 
 
 
 
 
 
16624b8
 
 
 
 
9952eb5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
---
language:
  - en
license: apache-2.0
task_categories:
  - text-generation
tags:
  - api
  - debugging
  - error-resolution
  - code
  - synthetic
  - python
  - javascript
  - typescript
  - go
  - java
  - rest
pretty_name: API Error Resolution Pairs
size_categories:
  - n<1K
dataset_info:
  features:
    - name: id
      dtype: int64
    - name: language
      dtype: string
    - name: library
      dtype: string
    - name: error_type
      dtype: string
    - name: error_message
      dtype: string
    - name: broken_code
      dtype: string
    - name: explanation
      dtype: string
    - name: fixed_code
      dtype: string
    - name: key_insight
      dtype: string
    - name: tags
      dtype: string
  splits:
    - name: train
      num_examples: 132
    - name: validation
      num_examples: 16
    - name: test
      num_examples: 16
---

# API Error Resolution Pairs

A synthetic dataset of real-world API error scenarios paired with explanations and fixes. Each example captures a broken code snippet, the error it produces, a plain-English explanation of the root cause, a corrected implementation, and a distilled key insight.

## Dataset Summary

| Split | Examples |
|-------|----------|
| train | 132 |
| validation | 16 |
| test | 16 |
| **Total** | **164** |

## Quick Start

### Load the dataset

```python
from datasets import load_dataset

ds = load_dataset("SalutefaceAAC/api-error-resolution-pairs")
print(ds)
# DatasetDict({
#     train: Dataset({features: [...], num_rows: 132}),
#     validation: Dataset({features: [...], num_rows: 16}),
#     test: Dataset({features: [...], num_rows: 16})
# })

# Inspect a record
example = ds["train"][0]
print(example["error_type"])     # e.g. "timeout_missing"
print(example["broken_code"])    # code that triggers the error
print(example["fixed_code"])     # corrected implementation
print(example["key_insight"])    # one-sentence principle
```

### Filter by language or error type

```python
# All Python examples
py_examples = ds["train"].filter(lambda x: x["language"] == "python")

# Rate-limiting errors only
rate_limit = ds["train"].filter(lambda x: x["error_type"] == "rate_limit")

# Multi-filter: TypeScript + auth errors
ts_auth = ds["train"].filter(
    lambda x: x["language"] == "typescript" and "auth" in x["error_type"]
)
```

### RAG retrieval (semantic search over error patterns)

```python
from sentence_transformers import SentenceTransformer
import numpy as np

model = SentenceTransformer("all-MiniLM-L6-v2")

train = ds["train"]
# Embed error messages as the retrieval key
embeddings = model.encode(train["error_message"], show_progress_bar=True)

def find_similar(query: str, top_k: int = 3):
    q_emb = model.encode([query])
    scores = np.dot(embeddings, q_emb.T).squeeze()
    top_idx = np.argsort(scores)[::-1][:top_k]
    for i in top_idx:
        print(f"[{scores[i]:.3f}] {train[int(i)]['error_type']} — {train[int(i)]['key_insight']}")

find_similar("Connection refused when calling external API")
```

### Fine-tuning prompt template

```python
def format_for_finetuning(example):
    """Format a record as an instruction-following prompt."""
    prompt = (
        f"Language: {example['language']}\n"
        f"Library: {example['library']}\n"
        f"Error: {example['error_message']}\n\n"
        f"Broken code:\n```\n{example['broken_code']}\n```\n\n"
        "Explain the root cause and provide the corrected implementation."
    )
    completion = (
        f"Root cause: {example['explanation']}\n\n"
        f"Fixed code:\n```\n{example['fixed_code']}\n```\n\n"
        f"Key insight: {example['key_insight']}"
    )
    return {"prompt": prompt, "completion": completion}

formatted = ds["train"].map(format_for_finetuning)
```

## Sample Records

### Example 1 — Python / requests: Large file download (MemoryError)

| Field | Value |
|-------|-------|
| `language` | python |
| `library` | requests |
| `error_type` | stream_large_response |
| `error_message` | MemoryError downloading large file |

**Broken code:**
```python
resp = requests.get("https://example.com/large-file.zip")
with open("large-file.zip", "wb") as f:
    f.write(resp.content)
```

**Fixed code:**
```python
resp = requests.get("https://example.com/large-file.zip", stream=True)
with open("large-file.zip", "wb") as f:
    for chunk in resp.iter_content(chunk_size=8192):
        f.write(chunk)
```

**Key insight:** Use `stream=True` and `iter_content()` to download large files without loading them into memory.

---

### Example 2 — JavaScript / axios: Unhandled cancellation

| Field | Value |
|-------|-------|
| `language` | javascript |
| `library` | axios |
| `error_type` | cancel_request |
| `error_message` | CanceledError unhandled when navigating away |

**Broken code:**
```javascript
const source = axios.CancelToken.source();
axios.get("/slow-api", { cancelToken: source.token });
source.cancel();
```

**Fixed code:**
```javascript
const controller = new AbortController();
try {
    const resp = await axios.get("/slow-api", { signal: controller.signal });
    process(resp.data);
} catch (err) {
    if (!axios.isCancel(err)) throw err;
}
// to cancel: controller.abort();
```

**Key insight:** Use `AbortController` with axios (v1+) and filter cancellations with `axios.isCancel(err)`.

---

### Example 3 — REST: Content negotiation failure

| Field | Value |
|-------|-------|
| `language` | rest |
| `library` | generic |
| `error_type` | content_negotiation |
| `error_message` | 406 Not Acceptable |

**Broken request:**
```http
GET /api/data
Accept: text/html
```

**Fixed request:**
```http
GET /api/data
Accept: application/json
```

**Key insight:** Match the `Accept` header to the media types the server advertises.

## Schema

| Field | Type | Description |
|-------|------|-------------|
| `id` | int | Unique record identifier |
| `language` | string | Programming language (python, javascript, typescript, go, java, rest) |
| `library` | string | Library or framework (requests, httpx, boto3, openai, anthropic, fetch, axios, okhttp, net/http, …) |
| `error_type` | string | Short error category slug |
| `error_message` | string | The actual error message or symptom |
| `broken_code` | string | Snippet that triggers the error |
| `explanation` | string | Root cause explanation |
| `fixed_code` | string | Corrected implementation |
| `key_insight` | string | One-sentence principle to prevent this class of error |
| `tags` | string | Comma-separated tag list |

## Coverage

### Languages & Libraries

| Language | Libraries |
|----------|-----------|
| Python | `requests`, `httpx`, `boto3`, `openai`, `anthropic`, `aiohttp`, `grpc`, `gql`, `stripe`, `google-auth`, `redis` |
| JavaScript | `fetch`, `axios` |
| TypeScript | `openai`, `react-query` |
| Go | `net/http` |
| Java | `okhttp` |
| REST | Generic HTTP patterns |

### Error Categories

- **Auth**: missing/malformed credentials, 401 flows
- **Timeout**: missing timeouts, context deadlines
- **JSON body**: wrong encoding, missing Content-Type
- **Error handling**: unchecked 4xx/5xx, silent failures
- **Rate limiting**: 429, Retry-After, backoff
- **Pagination**: offset vs cursor, last-page edge cases
- **Resource leaks**: unclosed bodies, sessions, connections
- **SSL/TLS**: certificate verification, insecure channels
- **Performance**: connection pools, pipelines, parallel requests
- **Streaming**: async iteration, chunk handling
- **Function/tool calling**: history management, tool result format
- **Structured output**: JSON mode, Zod schemas
- **Idempotency**: duplicate charges, retry safety
- **Versioning**: breaking changes, additive vs destructive

## Generation Methodology

Records were hand-authored one at a time, each capturing a distinct error pattern from real developer experience. A parametric augmentation layer generates variants across different API endpoints, token formats, and timeout values to increase dataset breadth without noise. All records passed MD5-based deduplication (keyed on `broken_code + fixed_code`).

**No model was used to generate records.** All `broken_code` / `fixed_code` / `explanation` / `key_insight` values were written manually.

## Intended Uses

- Fine-tuning code LLMs on error diagnosis and remediation
- Retrieval-augmented code assistance (RAG over error patterns)
- Benchmark evaluation for debugging models
- Developer education tooling

## Limitations

- **Augmentation depth**: parametric augmentation varies endpoints and timeout values only — augmented records share structure with their base and increase breadth but not conceptual depth.
- **Language coverage**: Java examples focus on Android context (OkHttp); server-side Java (Spring, Quarkus) patterns are underrepresented. Go examples cover `net/http` only.
- **Scenario complexity**: each record is a single-error / single-fix scenario. Multi-step debugging chains and cascading failures are out of scope.
- **Domain scope**: covers mainstream REST and gRPC clients; WebSocket, GraphQL subscriptions, and binary protocols are not included.
- **No runtime validation**: code snippets are validated by human review, not executed; edge-case compilation issues may exist.

## License

Apache 2.0

## Citation

```bibtex
@dataset{saluteface_api_error_resolution_2026,
  title  = {API Error Resolution Pairs},
  author = {SalutefaceAAC},
  year   = {2026},
  url    = {https://huggingface.co/datasets/SalutefaceAAC/api-error-resolution-pairs}
}
```