django-explain-errors 0.7.0__tar.gz → 0.8.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. {django_explain_errors-0.7.0/django_explain_errors.egg-info → django_explain_errors-0.8.0}/PKG-INFO +128 -31
  2. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/README.md +127 -30
  3. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0/django_explain_errors.egg-info}/PKG-INFO +128 -31
  4. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/django_explain_errors.egg-info/SOURCES.txt +3 -0
  5. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/explain_errors/client.py +3 -2
  6. django_explain_errors-0.8.0/explain_errors/debug_page.py +172 -0
  7. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/explain_errors/management/commands/build_error_index.py +2 -2
  8. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/explain_errors/middleware.py +66 -11
  9. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/setup.py +1 -1
  10. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/tests/test_build_error_index.py +1 -1
  11. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/tests/test_client.py +3 -2
  12. django_explain_errors-0.8.0/tests/test_debug_page.py +402 -0
  13. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/tests/test_middleware.py +1 -1
  14. django_explain_errors-0.8.0/tests/test_print_stdout.py +130 -0
  15. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/LICENSE +0 -0
  16. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/MANIFEST.in +0 -0
  17. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/django_explain_errors.egg-info/dependency_links.txt +0 -0
  18. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/django_explain_errors.egg-info/requires.txt +0 -0
  19. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/django_explain_errors.egg-info/top_level.txt +0 -0
  20. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/explain_errors/__init__.py +0 -0
  21. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/explain_errors/management/__init__.py +0 -0
  22. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/explain_errors/management/commands/__init__.py +0 -0
  23. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/explain_errors/rag/__init__.py +0 -0
  24. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/explain_errors/rag/indexer.py +0 -0
  25. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/explain_errors/rag/retriever.py +0 -0
  26. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/explain_errors/rag/store.py +0 -0
  27. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/explain_errors/sanitize.py +0 -0
  28. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/explain_errors/throttle.py +0 -0
  29. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/explain_errors/tracebacks.py +0 -0
  30. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/setup.cfg +0 -0
  31. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/tests/test_eval_fixtures.py +0 -0
  32. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/tests/test_eval_judge.py +0 -0
  33. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/tests/test_eval_run.py +0 -0
  34. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/tests/test_language.py +0 -0
  35. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/tests/test_rag.py +0 -0
  36. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/tests/test_sanitize.py +0 -0
  37. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/tests/test_signals.py +0 -0
  38. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/tests/test_throttle.py +0 -0
  39. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/tests/test_tracebacks.py +0 -0
  40. {django_explain_errors-0.7.0 → django_explain_errors-0.8.0}/tests/test_truncation.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: django-explain-errors
3
- Version: 0.7.0
3
+ Version: 0.8.0
4
4
  Summary: Django middleware that explains unhandled exceptions in DEBUG using an LLM, optionally grounded in your own project source via a local vector index. Works with OpenAI, Claude, or any OpenAI-compatible endpoint including local models.
5
5
  Home-page: https://github.com/topunix/django-explain-errors
6
6
  Author: topunix
@@ -45,17 +45,23 @@ Dynamic: summary
45
45
  # Django Explain Errors Middleware
46
46
 
47
47
  This Django middleware captures unhandled errors and exceptions, sends them
48
- to a language model for explanation, and prints the explanation to stdout
49
- when debug mode is enabled. It works with the OpenAI API out of the box, with
50
- Anthropic's Claude models through Anthropic's OpenAI-compatible endpoint, and
51
- with any other OpenAI-compatible endpoint (Ollama, LM Studio, Azure, or a
52
- corporate gateway) by setting a base URL, so explanations can run entirely on
53
- a local model if you prefer not to send code off your machine.
54
-
55
- It can optionally ground explanations in your own project source using a
56
- local vector index (RAG), so explanations reference the actual code that
57
- failed instead of staying generic (measured — see "Does RAG actually
58
- help?" below).
48
+ to a language model for explanation, and, when debug mode is enabled, shows
49
+ the explanation on Django's debug page directly under the exception
50
+ headline, as well as printing it to stdout. It works with the OpenAI API
51
+ out of the box, with Anthropic's Claude models through Anthropic's
52
+ OpenAI-compatible endpoint, and with any other OpenAI-compatible endpoint
53
+ (Ollama, LM Studio, Azure, or a corporate gateway) by setting a base URL,
54
+ so explanations can run entirely on a local model if you prefer not to send
55
+ code off your machine.
56
+
57
+ Enabling RAG is strongly recommended. With it, the middleware retrieves the
58
+ relevant parts of your own project source from a local vector index, so
59
+ explanations name the actual file and function that failed instead of
60
+ guessing. In the package's eval harness, RAG-grounded explanations won 35
61
+ of 43 blind comparisons, with the gap concentrated in pointing at the right
62
+ fix location and not inventing details (see "Does RAG actually help?"
63
+ below). It is off by default because it needs an optional extra and a
64
+ one-time index build.
59
65
 
60
66
  The middleware supports both synchronous (WSGI) and asynchronous (ASGI)
61
67
  views. It auto-detects the view chain at startup and routes requests through
@@ -63,11 +69,17 @@ the matching path, so no extra configuration is required for either server
63
69
  type. Tracebacks are sanitized before leaving the process, and API calls are
64
70
  rate limited.
65
71
 
72
+ ![Django debug page with the explanation banner under the exception headline](https://raw.githubusercontent.com/topunix/django-explain-errors/main/docs/images/debug-page-banner.png)
73
+
74
+ *Real `gpt-4o-mini` output with RAG enabled, recorded by the eval harness
75
+ on its `missing_fk` fixture.*
76
+
66
77
  ## Scope
67
78
 
68
79
  This package explains errors for a person, not for a coding agent to consume
69
- programmatically. The explanation is written for a human reader, in a terminal or an editor's
70
- integrated terminal, and the output format assumes that reader.
80
+ programmatically. The explanation is written for a human reader, on Django's
81
+ debug page in the browser or in a terminal, and the output format assumes
82
+ that reader.
71
83
 
72
84
  If a coding agent is doing the debugging, it does not need this. Agents read tracebacks directly,
73
85
  and tools that expose live runtime state (debugger-over-MCP servers, `mcp-django`) serve that case
@@ -78,9 +90,16 @@ Local development only. It requires `DEBUG = True` and is inert otherwise.
78
90
  ## Features
79
91
 
80
92
  - Captures Django errors and exceptions
93
+ - Shows the explanation on Django's debug page, directly under the
94
+ exception headline (`EXPLAIN_ERRORS_INJECT_DEBUG_PAGE`, on by default)
95
+ - Prints the explanation to stdout, for terminal workflows and logs
96
+ (`EXPLAIN_ERRORS_PRINT_STDOUT`, on by default)
97
+ - Optional JSON 500 response instead of the debug page
98
+ (`EXPLAIN_ERRORS_PRESERVE_DEBUG_PAGE = False`)
81
99
  - Explains errors using OpenAI, Anthropic's Claude models, or any other
82
100
  OpenAI-compatible endpoint (Ollama, LM Studio, Azure, gateways) via `OPENAI_BASE_URL`
83
- - Optional codebase-aware explanations (RAG) backed by a local sqlite-vec index (see the RAG section below)
101
+ - Codebase-aware explanations via RAG over a local sqlite-vec index
102
+ (recommended; see "Codebase-aware explanations" below)
84
103
  - Explanations in your language via `EXPLAIN_ERRORS_LANGUAGE`, with exception names,
85
104
  identifiers, and code kept in English
86
105
  - Redacts secrets, tokens, and emails from tracebacks before sending
@@ -97,13 +116,16 @@ pip install django-explain-errors
97
116
 
98
117
  2. **Add the middleware to your Django project**:
99
118
 
100
- - Open your `settings.py` file and add the middleware to the `MIDDLEWARE` list:
119
+ - Open your `settings.py` file and register the middleware only when `DEBUG` is on (see
120
+ Production Safety below for why):
101
121
 
102
122
  ```python
103
123
  MIDDLEWARE = [
104
124
  ...
105
- 'explain_errors.middleware.ExplainErrorsMiddleware',
106
125
  ]
126
+
127
+ if DEBUG:
128
+ MIDDLEWARE.append('explain_errors.middleware.ExplainErrorsMiddleware')
107
129
  ```
108
130
 
109
131
  In the default preserve mode, `process_exception` returns `None`, so exception handling
@@ -117,15 +139,39 @@ pip install django-explain-errors
117
139
 
118
140
  3. **Set up environment variables**:
119
141
 
120
- - Create a `.env` file in your project's root directory and add your OpenAI API key. Alternatively, you can set the API key in `settings.py`:
142
+ - Create a `.env` file in your project's root directory and add your API key. Alternatively, you can set it in `settings.py`:
121
143
 
122
144
  ```plaintext
123
- OPENAI_API_KEY=your_openai_api_key_here
145
+ OPENAI_API_KEY=your_api_key_here
124
146
  ```
125
147
 
126
148
  The API key is not required if you set `OPENAI_BASE_URL` to a local
127
149
  server such as Ollama, which does not authenticate requests.
128
150
 
151
+ ## Production Safety
152
+
153
+ This middleware is intended for local development only. When active, it sends exception
154
+ tracebacks to the configured LLM provider, which may include source code, file paths, and
155
+ local variable values. Keep it out of production.
156
+
157
+ **Primary safeguard:** register the middleware only when `DEBUG` is on, or only in your
158
+ development settings module:
159
+
160
+ ```python
161
+ # settings.py
162
+ if DEBUG:
163
+ MIDDLEWARE.append("explain_errors.middleware.ExplainErrorsMiddleware")
164
+ ```
165
+
166
+ See Installation above for where the middleware can sit in `MIDDLEWARE`.
167
+
168
+ **Secondary safeguard:** run Django's deployment checks in CI against your production settings.
169
+ This fails the build if `DEBUG = True` (`security.W018`):
170
+
171
+ ```bash
172
+ python manage.py check --deploy --fail-level WARNING
173
+ ```
174
+
129
175
  ## Usage
130
176
 
131
177
  1. **Ensure DEBUG is set to True**:
@@ -138,17 +184,59 @@ pip install django-explain-errors
138
184
 
139
185
  2. **Trigger an error in your Django application**:
140
186
 
141
- The middleware captures the error, sends it to the configured model for explanation, and prints the explanation to stdout. By default (`EXPLAIN_ERRORS_PRESERVE_DEBUG_PAGE=True`), it then lets exception handling continue normally, so Django (or whatever else is watching, such as `runserver_plus` or Sentry — see Compatibility below) renders exactly what it would without this middleware installed. Set `EXPLAIN_ERRORS_PRESERVE_DEBUG_PAGE = False` to instead get a JSON `500` response containing the error message and the explanation.
187
+ The middleware captures the error, sends it to the configured model for explanation, prints the explanation to stdout, and adds it as a banner on Django's debug page. By default (`EXPLAIN_ERRORS_PRESERVE_DEBUG_PAGE=True`), exception handling then continues normally, so Django (or whatever else is watching, such as `runserver_plus` or Sentry, see Compatibility below) renders its usual response. The only change is the banner on Django's own debug page. Set `EXPLAIN_ERRORS_INJECT_DEBUG_PAGE = False` to remove it, or `EXPLAIN_ERRORS_PRESERVE_DEBUG_PAGE = False` to instead get a JSON `500` response containing the error message and the explanation.
188
+
189
+ In the terminal, the explanation is printed with the model that produced it:
190
+
191
+ ```
192
+ Error explanation (gpt-4o-mini):
193
+ The view raised a ValueError because ...
194
+ ```
142
195
 
143
196
  ## Async Support
144
197
 
145
198
  The middleware exposes both `sync_capable = True` and `async_capable = True`. At initialization it inspects `get_response` to decide whether it is part of a sync or async chain:
146
199
 
147
200
  - Under WSGI (for example `runserver` with sync views), requests flow through the synchronous handler.
148
- - Under ASGI (for example with async views), requests are awaited through the async handler. The blocking OpenAI call is offloaded with `asgiref.sync.sync_to_async` so the event loop is not blocked.
201
+ - Under ASGI (for example with async views), requests are awaited through the async handler. The blocking model API call is offloaded with `asgiref.sync.sync_to_async` so the event loop is not blocked.
149
202
 
150
203
  No additional settings are needed. See Installation above for where to place the middleware in `MIDDLEWARE`.
151
204
 
205
+ ## Debug page injection
206
+
207
+ When Django renders its debug page for a 500, `explain_errors` also inserts a banner
208
+ containing the explanation directly under the exception headline, in addition to printing
209
+ it to stdout.
210
+
211
+ Controlled by `EXPLAIN_ERRORS_INJECT_DEBUG_PAGE`, default `True`. Injection happens only
212
+ when all of the following hold:
213
+
214
+ - `DEBUG` is `True`
215
+ - `EXPLAIN_ERRORS_INJECT_DEBUG_PAGE` is `True` (the default)
216
+ - `EXPLAIN_ERRORS_PRESERVE_DEBUG_PAGE` is `True` (the default). With
217
+ `EXPLAIN_ERRORS_PRESERVE_DEBUG_PAGE=False`, the JSON 500 path runs instead and there is
218
+ no debug page to inject into.
219
+ - an explanation was actually produced (not throttled, and the API call succeeded)
220
+
221
+ The banner appears only on the HTML debug page, styled inline (bordered box, light
222
+ background) so it reads on Django's page. The explanation is HTML-escaped first, then a small
223
+ Markdown subset (inline code, code blocks, bold, lists) is rendered as HTML. Nothing from the
224
+ model is ever marked safe.
225
+
226
+ **Fails open.** Any problem building or inserting the banner (a missing request, an
227
+ unexpected debug page layout, anything else) logs one warning and leaves Django's normal
228
+ debug page untouched. This code can never turn a working debug page into a broken one.
229
+
230
+ **Custom exception reporters.** If your project already sets a custom
231
+ `DEFAULT_EXCEPTION_REPORTER`, or something earlier in the request sets
232
+ `request.exception_reporter_class`, `explain_errors` leaves it alone and skips injection
233
+ (logged at debug level) rather than overriding it.
234
+
235
+ **Upgrading.** Turning this on, or upgrading to a version where it defaults on, changes
236
+ what Django's debug page looks like: a new section appears above the request metadata
237
+ table. If you rely on the debug page's exact markup (a scraper, a screenshot test), account
238
+ for this.
239
+
152
240
  ## Compatibility
153
241
 
154
242
  How this middleware interacts with other error-handling and debugging tools, in the default
@@ -156,10 +244,10 @@ preserve mode and with `EXPLAIN_ERRORS_PRESERVE_DEBUG_PAGE=False`:
156
244
 
157
245
  | Package | Preserve mode (default) | `EXPLAIN_ERRORS_PRESERVE_DEBUG_PAGE=False` |
158
246
  | ------- | ------------------------ | ------------------------------------------- |
159
- | Django Debug Toolbar | Works — Django renders its normal debug page, and Debug Toolbar injects into it. | Broken — the JSON 500 response has no HTML to inject into. |
247
+ | Django Debug Toolbar | Works — Django renders its debug page (with the explanation banner, unless `EXPLAIN_ERRORS_INJECT_DEBUG_PAGE = False`), and Debug Toolbar injects into it. | Broken — the JSON 500 response has no HTML to inject into. |
160
248
  | Sentry, Rollbar | Work — the exception propagates and Django re-raises it, so `got_request_exception` fires. | Broken — returning a response ends exception handling before `got_request_exception` fires. |
161
249
  | Django REST Framework | Partial — only exceptions DRF does not already handle itself reach this middleware. | Partial, same reason. |
162
- | Silk and other profiling panels | Timings are inflated by the OpenAI call, since `process_exception` blocks the request path. | Same. |
250
+ | Silk and other profiling panels | Timings are inflated by the model API call, since `process_exception` blocks the request path. | Same. |
163
251
  | CORS, GZip, WhiteNoise | No interaction. | No interaction. |
164
252
  | `runserver_plus` / Werkzeug debugger | Works — returning `None` re-raises the original exception, and `django-extensions` replaces Django's debug-page renderer with one that re-raises instead, so Werkzeug's WSGI wrapper catches it and shows the interactive debugger. | Broken — the JSON 500 response ends exception handling before it reaches `runserver_plus`'s exception hook, so the Werkzeug debugger never appears. |
165
253
 
@@ -183,9 +271,11 @@ developer is actually investigating.
183
271
  | `DEBUG` | Yes | The middleware is only active when `DEBUG=True`. When `False`, requests pass through untouched. |
184
272
  | `OPENAI_MODEL` | No | Model used for explanations. Defaults to `gpt-4o-mini`. |
185
273
  | `OPENAI_MAX_TOKENS` | No | Ceiling on tokens generated for the explanation, not a target — the system prompt itself asks for a concise answer. Defaults to `1000`; scales up automatically when `EXPLAIN_ERRORS_LANGUAGE` is set (see below), unless you set this explicitly, which always overrides the scaling. |
186
- | `OPENAI_TIMEOUT` | No | Request timeout in seconds for the OpenAI client. Defaults to `10`. |
274
+ | `OPENAI_TIMEOUT` | No | Request timeout in seconds for model API calls. Defaults to `10`. |
187
275
  | `OPENAI_MAX_TRACEBACK_CHARS` | No | Total character budget for the traceback sent to the model. Application frames (your own code, as opposed to Django, the standard library, or installed packages) are always kept; library frames fill whatever budget remains, nearest the raise point first, with an `... N library frames omitted ...` line where frames are dropped. If the application frames alone exceed the budget, falls back to keeping the last N characters of the raw traceback. Defaults to `3000`. |
188
- | `EXPLAIN_ERRORS_PRESERVE_DEBUG_PAGE` | No | When `True` (the default), the middleware prints the explanation to stdout and returns `None`, so exception handling continues normally and Django renders its standard debug page. Set to `False` to instead return a JSON 500 response, which ends exception handling early (see Compatibility above). |
276
+ | `EXPLAIN_ERRORS_PRESERVE_DEBUG_PAGE` | No | When `True` (the default), the middleware returns `None` (after printing the explanation to stdout, unless `EXPLAIN_ERRORS_PRINT_STDOUT = False`), so exception handling continues normally and Django renders its debug page (with the explanation banner, controlled by `EXPLAIN_ERRORS_INJECT_DEBUG_PAGE`). Set to `False` to instead return a JSON 500 response, which ends exception handling early (see Compatibility above). |
277
+ | `EXPLAIN_ERRORS_INJECT_DEBUG_PAGE` | No | When `True` (the default), also injects the explanation as a banner into Django's debug page, in addition to stdout. Requires `EXPLAIN_ERRORS_PRESERVE_DEBUG_PAGE=True` (the default); see Debug Page Injection above. |
278
+ | `EXPLAIN_ERRORS_PRINT_STDOUT` | No | When `True` (the default), prints the explanation to stdout. Set to `False` to suppress it, for example when `EXPLAIN_ERRORS_INJECT_DEBUG_PAGE` already shows it in the browser. The failure message (when the model API call itself errors) always prints. For requests where nobody views the debug page (API clients, which get Django's plain-text error response, and `fetch`/HTMX requests, whose HTML response is never displayed), stdout is the only channel that shows the explanation, so turn this off only in browser-first workflows. |
189
279
  | `OPENAI_BASE_URL` (env or settings) | No | Base URL for any OpenAI-compatible API (for example Ollama at `http://localhost:11434/v1`). When set, a missing API key is replaced with a placeholder since local servers do not require one. |
190
280
  | `EXPLAIN_ERRORS_MAX_CALLS` | No | Together with `EXPLAIN_ERRORS_WINDOW_SECONDS`, caps API spend to at most this many explanations within a rolling window; once the cap is hit, further errors in that window are not sent for explanation until an earlier call ages out. Defaults to `5`. |
191
281
  | `EXPLAIN_ERRORS_WINDOW_SECONDS` | No | Length in seconds of the rolling window `EXPLAIN_ERRORS_MAX_CALLS` is measured against. Defaults to `60` (with the defaults, at most 5 explanations per 60-second window). |
@@ -299,7 +389,9 @@ also retrieves the most relevant chunks of your own project's source code
299
389
  from a local vector index and includes them in the prompt, so explanations
300
390
  can reference your actual functions and classes instead of guessing at them.
301
391
 
302
- This feature is opt-in and adds no dependencies or behavior unless enabled.
392
+ Recommended for most projects. It is opt-in only because setup takes three
393
+ steps (install the extra, build the index, enable it), and it adds no
394
+ dependencies or behavior until you do.
303
395
 
304
396
  ### Install the extra
305
397
 
@@ -322,7 +414,7 @@ python manage.py build_error_index
322
414
 
323
415
  This walks your project, chunks Python files by top-level function/class
324
416
  (and other text files by fixed-size line windows), embeds each chunk with
325
- the OpenAI embeddings API, and writes them to a local index file. Re-run it
417
+ the configured endpoint's embeddings API, and writes them to a local index file. Re-run it
326
418
  whenever your source changes meaningfully. Indexing is not automatic.
327
419
  Rebuilding is idempotent: it builds into a temp file and atomically replaces
328
420
  the previous index.
@@ -342,15 +434,14 @@ EXPLAIN_ERRORS_RAG_ENABLED = True
342
434
  | `EXPLAIN_ERRORS_RAG_ENABLED` | `False` | Master switch for the RAG layer. |
343
435
  | `EXPLAIN_ERRORS_RAG_INDEX_PATH` | `<BASE_DIR>/.explain_errors_index.db` | Path to the local vector index file. |
344
436
  | `EXPLAIN_ERRORS_RAG_TOP_K` | `4` | Number of chunks retrieved and injected into the prompt. |
345
- | `EXPLAIN_ERRORS_RAG_EMBED_MODEL` | `"text-embedding-3-small"` | OpenAI embedding model used for indexing and retrieval. |
437
+ | `EXPLAIN_ERRORS_RAG_EMBED_MODEL` | `"text-embedding-3-small"` | Embedding model used for indexing and retrieval. Must exist on the configured endpoint. |
346
438
  | `EXPLAIN_ERRORS_RAG_INCLUDE` | `None` (defaults to `BASE_DIR`) | List of directories to index. |
347
439
  | `EXPLAIN_ERRORS_RAG_EXCLUDE` | migrations, venvs, `node_modules`, static, media, `.git` | Directory names to skip while indexing. |
348
440
  | `EXPLAIN_ERRORS_RAG_MAX_PROMPT_CHARS` | `6000` | Combined character budget for the traceback + retrieved source sections of the prompt. |
349
441
 
350
442
  Every chunk of source code and every retrieval query is passed through the
351
443
  same `sanitize_traceback()` redaction used for tracebacks, which strips
352
- patterns that look like secrets, tokens, and emails before anything is sent
353
- to OpenAI or written to the index. It's a pattern-based filter, not a
444
+ patterns that look like secrets, tokens, and emails before anything is sent to the model API or written to the index. It's a pattern-based filter, not a
354
445
  guarantee: it catches recognizable secret shapes, not arbitrary sensitive
355
446
  data that doesn't match one.
356
447
 
@@ -380,6 +471,12 @@ required `author` foreign key. The traceback the model actually received
380
471
  was already truncated to `OPENAI_MAX_TRACEBACK_CHARS`, so it contains no
381
472
  application code at all, only Django/SQLite internals:
382
473
 
474
+ This example was recorded before 0.7.0, when tracebacks were trimmed to
475
+ their last N characters. Since 0.7.0 your application's frames are always
476
+ kept, so a traceback-only explanation would now see `clone_latest_post`
477
+ too. The measured results in "Does RAG actually help?" below were run
478
+ after that change.
479
+
383
480
  ```
384
481
  ...(truncated)...
385
482
  File ".../django/db/models/base.py", line 904, in save
@@ -486,5 +583,5 @@ Contributions are welcome! Please open an issue or submit a pull request for any
486
583
  ## Acknowledgements
487
584
 
488
585
  - [Django](https://www.djangoproject.com/)
489
- - [OpenAI](https://www.openai.com/)
586
+ - [OpenAI Python SDK](https://github.com/openai/openai-python)
490
587
  - [python-dotenv](https://github.com/theskumar/python-dotenv)
@@ -1,17 +1,23 @@
1
1
  # Django Explain Errors Middleware
2
2
 
3
3
  This Django middleware captures unhandled errors and exceptions, sends them
4
- to a language model for explanation, and prints the explanation to stdout
5
- when debug mode is enabled. It works with the OpenAI API out of the box, with
6
- Anthropic's Claude models through Anthropic's OpenAI-compatible endpoint, and
7
- with any other OpenAI-compatible endpoint (Ollama, LM Studio, Azure, or a
8
- corporate gateway) by setting a base URL, so explanations can run entirely on
9
- a local model if you prefer not to send code off your machine.
10
-
11
- It can optionally ground explanations in your own project source using a
12
- local vector index (RAG), so explanations reference the actual code that
13
- failed instead of staying generic (measured — see "Does RAG actually
14
- help?" below).
4
+ to a language model for explanation, and, when debug mode is enabled, shows
5
+ the explanation on Django's debug page directly under the exception
6
+ headline, as well as printing it to stdout. It works with the OpenAI API
7
+ out of the box, with Anthropic's Claude models through Anthropic's
8
+ OpenAI-compatible endpoint, and with any other OpenAI-compatible endpoint
9
+ (Ollama, LM Studio, Azure, or a corporate gateway) by setting a base URL,
10
+ so explanations can run entirely on a local model if you prefer not to send
11
+ code off your machine.
12
+
13
+ Enabling RAG is strongly recommended. With it, the middleware retrieves the
14
+ relevant parts of your own project source from a local vector index, so
15
+ explanations name the actual file and function that failed instead of
16
+ guessing. In the package's eval harness, RAG-grounded explanations won 35
17
+ of 43 blind comparisons, with the gap concentrated in pointing at the right
18
+ fix location and not inventing details (see "Does RAG actually help?"
19
+ below). It is off by default because it needs an optional extra and a
20
+ one-time index build.
15
21
 
16
22
  The middleware supports both synchronous (WSGI) and asynchronous (ASGI)
17
23
  views. It auto-detects the view chain at startup and routes requests through
@@ -19,11 +25,17 @@ the matching path, so no extra configuration is required for either server
19
25
  type. Tracebacks are sanitized before leaving the process, and API calls are
20
26
  rate limited.
21
27
 
28
+ ![Django debug page with the explanation banner under the exception headline](https://raw.githubusercontent.com/topunix/django-explain-errors/main/docs/images/debug-page-banner.png)
29
+
30
+ *Real `gpt-4o-mini` output with RAG enabled, recorded by the eval harness
31
+ on its `missing_fk` fixture.*
32
+
22
33
  ## Scope
23
34
 
24
35
  This package explains errors for a person, not for a coding agent to consume
25
- programmatically. The explanation is written for a human reader, in a terminal or an editor's
26
- integrated terminal, and the output format assumes that reader.
36
+ programmatically. The explanation is written for a human reader, on Django's
37
+ debug page in the browser or in a terminal, and the output format assumes
38
+ that reader.
27
39
 
28
40
  If a coding agent is doing the debugging, it does not need this. Agents read tracebacks directly,
29
41
  and tools that expose live runtime state (debugger-over-MCP servers, `mcp-django`) serve that case
@@ -34,9 +46,16 @@ Local development only. It requires `DEBUG = True` and is inert otherwise.
34
46
  ## Features
35
47
 
36
48
  - Captures Django errors and exceptions
49
+ - Shows the explanation on Django's debug page, directly under the
50
+ exception headline (`EXPLAIN_ERRORS_INJECT_DEBUG_PAGE`, on by default)
51
+ - Prints the explanation to stdout, for terminal workflows and logs
52
+ (`EXPLAIN_ERRORS_PRINT_STDOUT`, on by default)
53
+ - Optional JSON 500 response instead of the debug page
54
+ (`EXPLAIN_ERRORS_PRESERVE_DEBUG_PAGE = False`)
37
55
  - Explains errors using OpenAI, Anthropic's Claude models, or any other
38
56
  OpenAI-compatible endpoint (Ollama, LM Studio, Azure, gateways) via `OPENAI_BASE_URL`
39
- - Optional codebase-aware explanations (RAG) backed by a local sqlite-vec index (see the RAG section below)
57
+ - Codebase-aware explanations via RAG over a local sqlite-vec index
58
+ (recommended; see "Codebase-aware explanations" below)
40
59
  - Explanations in your language via `EXPLAIN_ERRORS_LANGUAGE`, with exception names,
41
60
  identifiers, and code kept in English
42
61
  - Redacts secrets, tokens, and emails from tracebacks before sending
@@ -53,13 +72,16 @@ pip install django-explain-errors
53
72
 
54
73
  2. **Add the middleware to your Django project**:
55
74
 
56
- - Open your `settings.py` file and add the middleware to the `MIDDLEWARE` list:
75
+ - Open your `settings.py` file and register the middleware only when `DEBUG` is on (see
76
+ Production Safety below for why):
57
77
 
58
78
  ```python
59
79
  MIDDLEWARE = [
60
80
  ...
61
- 'explain_errors.middleware.ExplainErrorsMiddleware',
62
81
  ]
82
+
83
+ if DEBUG:
84
+ MIDDLEWARE.append('explain_errors.middleware.ExplainErrorsMiddleware')
63
85
  ```
64
86
 
65
87
  In the default preserve mode, `process_exception` returns `None`, so exception handling
@@ -73,15 +95,39 @@ pip install django-explain-errors
73
95
 
74
96
  3. **Set up environment variables**:
75
97
 
76
- - Create a `.env` file in your project's root directory and add your OpenAI API key. Alternatively, you can set the API key in `settings.py`:
98
+ - Create a `.env` file in your project's root directory and add your API key. Alternatively, you can set it in `settings.py`:
77
99
 
78
100
  ```plaintext
79
- OPENAI_API_KEY=your_openai_api_key_here
101
+ OPENAI_API_KEY=your_api_key_here
80
102
  ```
81
103
 
82
104
  The API key is not required if you set `OPENAI_BASE_URL` to a local
83
105
  server such as Ollama, which does not authenticate requests.
84
106
 
107
+ ## Production Safety
108
+
109
+ This middleware is intended for local development only. When active, it sends exception
110
+ tracebacks to the configured LLM provider, which may include source code, file paths, and
111
+ local variable values. Keep it out of production.
112
+
113
+ **Primary safeguard:** register the middleware only when `DEBUG` is on, or only in your
114
+ development settings module:
115
+
116
+ ```python
117
+ # settings.py
118
+ if DEBUG:
119
+ MIDDLEWARE.append("explain_errors.middleware.ExplainErrorsMiddleware")
120
+ ```
121
+
122
+ See Installation above for where the middleware can sit in `MIDDLEWARE`.
123
+
124
+ **Secondary safeguard:** run Django's deployment checks in CI against your production settings.
125
+ This fails the build if `DEBUG = True` (`security.W018`):
126
+
127
+ ```bash
128
+ python manage.py check --deploy --fail-level WARNING
129
+ ```
130
+
85
131
  ## Usage
86
132
 
87
133
  1. **Ensure DEBUG is set to True**:
@@ -94,17 +140,59 @@ pip install django-explain-errors
94
140
 
95
141
  2. **Trigger an error in your Django application**:
96
142
 
97
- The middleware captures the error, sends it to the configured model for explanation, and prints the explanation to stdout. By default (`EXPLAIN_ERRORS_PRESERVE_DEBUG_PAGE=True`), it then lets exception handling continue normally, so Django (or whatever else is watching, such as `runserver_plus` or Sentry — see Compatibility below) renders exactly what it would without this middleware installed. Set `EXPLAIN_ERRORS_PRESERVE_DEBUG_PAGE = False` to instead get a JSON `500` response containing the error message and the explanation.
143
+ The middleware captures the error, sends it to the configured model for explanation, prints the explanation to stdout, and adds it as a banner on Django's debug page. By default (`EXPLAIN_ERRORS_PRESERVE_DEBUG_PAGE=True`), exception handling then continues normally, so Django (or whatever else is watching, such as `runserver_plus` or Sentry, see Compatibility below) renders its usual response. The only change is the banner on Django's own debug page. Set `EXPLAIN_ERRORS_INJECT_DEBUG_PAGE = False` to remove it, or `EXPLAIN_ERRORS_PRESERVE_DEBUG_PAGE = False` to instead get a JSON `500` response containing the error message and the explanation.
144
+
145
+ In the terminal, the explanation is printed with the model that produced it:
146
+
147
+ ```
148
+ Error explanation (gpt-4o-mini):
149
+ The view raised a ValueError because ...
150
+ ```
98
151
 
99
152
  ## Async Support
100
153
 
101
154
  The middleware exposes both `sync_capable = True` and `async_capable = True`. At initialization it inspects `get_response` to decide whether it is part of a sync or async chain:
102
155
 
103
156
  - Under WSGI (for example `runserver` with sync views), requests flow through the synchronous handler.
104
- - Under ASGI (for example with async views), requests are awaited through the async handler. The blocking OpenAI call is offloaded with `asgiref.sync.sync_to_async` so the event loop is not blocked.
157
+ - Under ASGI (for example with async views), requests are awaited through the async handler. The blocking model API call is offloaded with `asgiref.sync.sync_to_async` so the event loop is not blocked.
105
158
 
106
159
  No additional settings are needed. See Installation above for where to place the middleware in `MIDDLEWARE`.
107
160
 
161
+ ## Debug page injection
162
+
163
+ When Django renders its debug page for a 500, `explain_errors` also inserts a banner
164
+ containing the explanation directly under the exception headline, in addition to printing
165
+ it to stdout.
166
+
167
+ Controlled by `EXPLAIN_ERRORS_INJECT_DEBUG_PAGE`, default `True`. Injection happens only
168
+ when all of the following hold:
169
+
170
+ - `DEBUG` is `True`
171
+ - `EXPLAIN_ERRORS_INJECT_DEBUG_PAGE` is `True` (the default)
172
+ - `EXPLAIN_ERRORS_PRESERVE_DEBUG_PAGE` is `True` (the default). With
173
+ `EXPLAIN_ERRORS_PRESERVE_DEBUG_PAGE=False`, the JSON 500 path runs instead and there is
174
+ no debug page to inject into.
175
+ - an explanation was actually produced (not throttled, and the API call succeeded)
176
+
177
+ The banner appears only on the HTML debug page, styled inline (bordered box, light
178
+ background) so it reads on Django's page. The explanation is HTML-escaped first, then a small
179
+ Markdown subset (inline code, code blocks, bold, lists) is rendered as HTML. Nothing from the
180
+ model is ever marked safe.
181
+
182
+ **Fails open.** Any problem building or inserting the banner (a missing request, an
183
+ unexpected debug page layout, anything else) logs one warning and leaves Django's normal
184
+ debug page untouched. This code can never turn a working debug page into a broken one.
185
+
186
+ **Custom exception reporters.** If your project already sets a custom
187
+ `DEFAULT_EXCEPTION_REPORTER`, or something earlier in the request sets
188
+ `request.exception_reporter_class`, `explain_errors` leaves it alone and skips injection
189
+ (logged at debug level) rather than overriding it.
190
+
191
+ **Upgrading.** Turning this on, or upgrading to a version where it defaults on, changes
192
+ what Django's debug page looks like: a new section appears above the request metadata
193
+ table. If you rely on the debug page's exact markup (a scraper, a screenshot test), account
194
+ for this.
195
+
108
196
  ## Compatibility
109
197
 
110
198
  How this middleware interacts with other error-handling and debugging tools, in the default
@@ -112,10 +200,10 @@ preserve mode and with `EXPLAIN_ERRORS_PRESERVE_DEBUG_PAGE=False`:
112
200
 
113
201
  | Package | Preserve mode (default) | `EXPLAIN_ERRORS_PRESERVE_DEBUG_PAGE=False` |
114
202
  | ------- | ------------------------ | ------------------------------------------- |
115
- | Django Debug Toolbar | Works — Django renders its normal debug page, and Debug Toolbar injects into it. | Broken — the JSON 500 response has no HTML to inject into. |
203
+ | Django Debug Toolbar | Works — Django renders its debug page (with the explanation banner, unless `EXPLAIN_ERRORS_INJECT_DEBUG_PAGE = False`), and Debug Toolbar injects into it. | Broken — the JSON 500 response has no HTML to inject into. |
116
204
  | Sentry, Rollbar | Work — the exception propagates and Django re-raises it, so `got_request_exception` fires. | Broken — returning a response ends exception handling before `got_request_exception` fires. |
117
205
  | Django REST Framework | Partial — only exceptions DRF does not already handle itself reach this middleware. | Partial, same reason. |
118
- | Silk and other profiling panels | Timings are inflated by the OpenAI call, since `process_exception` blocks the request path. | Same. |
206
+ | Silk and other profiling panels | Timings are inflated by the model API call, since `process_exception` blocks the request path. | Same. |
119
207
  | CORS, GZip, WhiteNoise | No interaction. | No interaction. |
120
208
  | `runserver_plus` / Werkzeug debugger | Works — returning `None` re-raises the original exception, and `django-extensions` replaces Django's debug-page renderer with one that re-raises instead, so Werkzeug's WSGI wrapper catches it and shows the interactive debugger. | Broken — the JSON 500 response ends exception handling before it reaches `runserver_plus`'s exception hook, so the Werkzeug debugger never appears. |
121
209
 
@@ -139,9 +227,11 @@ developer is actually investigating.
139
227
  | `DEBUG` | Yes | The middleware is only active when `DEBUG=True`. When `False`, requests pass through untouched. |
140
228
  | `OPENAI_MODEL` | No | Model used for explanations. Defaults to `gpt-4o-mini`. |
141
229
  | `OPENAI_MAX_TOKENS` | No | Ceiling on tokens generated for the explanation, not a target — the system prompt itself asks for a concise answer. Defaults to `1000`; scales up automatically when `EXPLAIN_ERRORS_LANGUAGE` is set (see below), unless you set this explicitly, which always overrides the scaling. |
142
- | `OPENAI_TIMEOUT` | No | Request timeout in seconds for the OpenAI client. Defaults to `10`. |
230
+ | `OPENAI_TIMEOUT` | No | Request timeout in seconds for model API calls. Defaults to `10`. |
143
231
  | `OPENAI_MAX_TRACEBACK_CHARS` | No | Total character budget for the traceback sent to the model. Application frames (your own code, as opposed to Django, the standard library, or installed packages) are always kept; library frames fill whatever budget remains, nearest the raise point first, with an `... N library frames omitted ...` line where frames are dropped. If the application frames alone exceed the budget, falls back to keeping the last N characters of the raw traceback. Defaults to `3000`. |
144
- | `EXPLAIN_ERRORS_PRESERVE_DEBUG_PAGE` | No | When `True` (the default), the middleware prints the explanation to stdout and returns `None`, so exception handling continues normally and Django renders its standard debug page. Set to `False` to instead return a JSON 500 response, which ends exception handling early (see Compatibility above). |
232
+ | `EXPLAIN_ERRORS_PRESERVE_DEBUG_PAGE` | No | When `True` (the default), the middleware returns `None` (after printing the explanation to stdout, unless `EXPLAIN_ERRORS_PRINT_STDOUT = False`), so exception handling continues normally and Django renders its debug page (with the explanation banner, controlled by `EXPLAIN_ERRORS_INJECT_DEBUG_PAGE`). Set to `False` to instead return a JSON 500 response, which ends exception handling early (see Compatibility above). |
233
+ | `EXPLAIN_ERRORS_INJECT_DEBUG_PAGE` | No | When `True` (the default), also injects the explanation as a banner into Django's debug page, in addition to stdout. Requires `EXPLAIN_ERRORS_PRESERVE_DEBUG_PAGE=True` (the default); see Debug Page Injection above. |
234
+ | `EXPLAIN_ERRORS_PRINT_STDOUT` | No | When `True` (the default), prints the explanation to stdout. Set to `False` to suppress it, for example when `EXPLAIN_ERRORS_INJECT_DEBUG_PAGE` already shows it in the browser. The failure message (when the model API call itself errors) always prints. For requests where nobody views the debug page (API clients, which get Django's plain-text error response, and `fetch`/HTMX requests, whose HTML response is never displayed), stdout is the only channel that shows the explanation, so turn this off only in browser-first workflows. |
145
235
  | `OPENAI_BASE_URL` (env or settings) | No | Base URL for any OpenAI-compatible API (for example Ollama at `http://localhost:11434/v1`). When set, a missing API key is replaced with a placeholder since local servers do not require one. |
146
236
  | `EXPLAIN_ERRORS_MAX_CALLS` | No | Together with `EXPLAIN_ERRORS_WINDOW_SECONDS`, caps API spend to at most this many explanations within a rolling window; once the cap is hit, further errors in that window are not sent for explanation until an earlier call ages out. Defaults to `5`. |
147
237
  | `EXPLAIN_ERRORS_WINDOW_SECONDS` | No | Length in seconds of the rolling window `EXPLAIN_ERRORS_MAX_CALLS` is measured against. Defaults to `60` (with the defaults, at most 5 explanations per 60-second window). |
@@ -255,7 +345,9 @@ also retrieves the most relevant chunks of your own project's source code
255
345
  from a local vector index and includes them in the prompt, so explanations
256
346
  can reference your actual functions and classes instead of guessing at them.
257
347
 
258
- This feature is opt-in and adds no dependencies or behavior unless enabled.
348
+ Recommended for most projects. It is opt-in only because setup takes three
349
+ steps (install the extra, build the index, enable it), and it adds no
350
+ dependencies or behavior until you do.
259
351
 
260
352
  ### Install the extra
261
353
 
@@ -278,7 +370,7 @@ python manage.py build_error_index
278
370
 
279
371
  This walks your project, chunks Python files by top-level function/class
280
372
  (and other text files by fixed-size line windows), embeds each chunk with
281
- the OpenAI embeddings API, and writes them to a local index file. Re-run it
373
+ the configured endpoint's embeddings API, and writes them to a local index file. Re-run it
282
374
  whenever your source changes meaningfully. Indexing is not automatic.
283
375
  Rebuilding is idempotent: it builds into a temp file and atomically replaces
284
376
  the previous index.
@@ -298,15 +390,14 @@ EXPLAIN_ERRORS_RAG_ENABLED = True
298
390
  | `EXPLAIN_ERRORS_RAG_ENABLED` | `False` | Master switch for the RAG layer. |
299
391
  | `EXPLAIN_ERRORS_RAG_INDEX_PATH` | `<BASE_DIR>/.explain_errors_index.db` | Path to the local vector index file. |
300
392
  | `EXPLAIN_ERRORS_RAG_TOP_K` | `4` | Number of chunks retrieved and injected into the prompt. |
301
- | `EXPLAIN_ERRORS_RAG_EMBED_MODEL` | `"text-embedding-3-small"` | OpenAI embedding model used for indexing and retrieval. |
393
+ | `EXPLAIN_ERRORS_RAG_EMBED_MODEL` | `"text-embedding-3-small"` | Embedding model used for indexing and retrieval. Must exist on the configured endpoint. |
302
394
  | `EXPLAIN_ERRORS_RAG_INCLUDE` | `None` (defaults to `BASE_DIR`) | List of directories to index. |
303
395
  | `EXPLAIN_ERRORS_RAG_EXCLUDE` | migrations, venvs, `node_modules`, static, media, `.git` | Directory names to skip while indexing. |
304
396
  | `EXPLAIN_ERRORS_RAG_MAX_PROMPT_CHARS` | `6000` | Combined character budget for the traceback + retrieved source sections of the prompt. |
305
397
 
306
398
  Every chunk of source code and every retrieval query is passed through the
307
399
  same `sanitize_traceback()` redaction used for tracebacks, which strips
308
- patterns that look like secrets, tokens, and emails before anything is sent
309
- to OpenAI or written to the index. It's a pattern-based filter, not a
400
+ patterns that look like secrets, tokens, and emails before anything is sent to the model API or written to the index. It's a pattern-based filter, not a
310
401
  guarantee: it catches recognizable secret shapes, not arbitrary sensitive
311
402
  data that doesn't match one.
312
403
 
@@ -336,6 +427,12 @@ required `author` foreign key. The traceback the model actually received
336
427
  was already truncated to `OPENAI_MAX_TRACEBACK_CHARS`, so it contains no
337
428
  application code at all, only Django/SQLite internals:
338
429
 
430
+ This example was recorded before 0.7.0, when tracebacks were trimmed to
431
+ their last N characters. Since 0.7.0 your application's frames are always
432
+ kept, so a traceback-only explanation would now see `clone_latest_post`
433
+ too. The measured results in "Does RAG actually help?" below were run
434
+ after that change.
435
+
339
436
  ```
340
437
  ...(truncated)...
341
438
  File ".../django/db/models/base.py", line 904, in save
@@ -442,5 +539,5 @@ Contributions are welcome! Please open an issue or submit a pull request for any
442
539
  ## Acknowledgements
443
540
 
444
541
  - [Django](https://www.djangoproject.com/)
445
- - [OpenAI](https://www.openai.com/)
542
+ - [OpenAI Python SDK](https://github.com/openai/openai-python)
446
543
  - [python-dotenv](https://github.com/theskumar/python-dotenv)