Skip to main content

SmartCatch 🚨🤖

AI-powered exception handling for Python.
SmartCatch wraps your code in a smart try/catch that, when an unexpected error slips through, automatically:

  1. Explains exactly which line caused the error and why.
  2. Generates a ready-to-paste fix snippet you can drop straight into your code.
  3. Advises on how to prevent that class of error in the future.

It uses the OpenAI API (zero extra dependencies — pure stdlib) and works as a decorator, a context manager, or a global exception hook.


Installation

pip install smartcatch

Set your OpenAI key once (or pass it via SmartCatchConfig):

export OPENAI_API_KEY="sk-..."

Quick start

1 — Decorator

from smartcatch import smartcatch

@smartcatch
def load_config(path):
    with open(path) as f:
        return json.load(f)   # FileNotFoundError? JSONDecodeError? SmartCatch handles it.

load_config("settings.json")

2 — Context manager

from smartcatch import SmartCatchContext

with SmartCatchContext():
    result = int(user_input) / divisor   # ZeroDivisionError? ValueError? Caught + explained.

3 — Global hook (catch everything)

Put this at the very top of your main.py or entry point:

import smartcatch
smartcatch.install_global_handler()

# … rest of your app …

Any unhandled exception anywhere in the process will be analysed automatically.


What the output looks like

════════════════════════════════════════════════════════════════════════
  🚨  SMARTCATCH — Unexpected Error Detected
════════════════════════════════════════════════════════════════════════

  Exception : ZeroDivisionError: division by zero

────────────────────────────────────────────────────────────────────────
  📌  What happened
────────────────────────────────────────────────────────────────────────

  Division by zero occurred on line 12 of app.py.

────────────────────────────────────────────────────────────────────────
  🔍  Root cause
────────────────────────────────────────────────────────────────────────

  The variable `divisor` is 0 at line 12 because no guard is in place
  before the division `value / divisor`.

────────────────────────────────────────────────────────────────────────
  🛠️   Ready-to-integrate fix
────────────────────────────────────────────────────────────────────────

    # Guard against zero divisor before performing division
    if divisor == 0:
        raise ValueError("divisor must not be zero")
    result = value / divisor

────────────────────────────────────────────────────────────────────────
  💡  Prevention advice
────────────────────────────────────────────────────────────────────────

  Always validate numeric inputs before performing arithmetic. Consider
  using a helper function that raises a descriptive error on bad values.

════════════════════════════════════════════════════════════════════════

Configuration

All behaviour is controlled via SmartCatchConfig:

from smartcatch import SmartCatchConfig, smartcatch, SmartCatchContext, install_global_handler

cfg = SmartCatchConfig(
    api_key="sk-...",          # or set OPENAI_API_KEY env var
    model="gpt-4o",            # any OpenAI chat model
    max_source_lines=30,       # lines of source context sent to the model
    show_fix=True,             # print the fix snippet
    show_explanation=True,     # print the root-cause explanation
    reraise=True,              # re-raise after analysis (default True)
    output_file="errors.log",  # write report to a file instead of stderr
    silent=False,              # suppress all output (useful with output_file)
)

@smartcatch(config=cfg)
def my_function():
    ...

with SmartCatchContext(config=cfg):
    ...

install_global_handler(config=cfg)

Catch only specific exception types

@smartcatch(catch=(ValueError, KeyError))
def parse(data):
    ...

with SmartCatchContext(catch=(IOError,)):
    ...

How it works

  1. The handler intercepts the exception before Python unwinds the stack.
  2. It extracts the full traceback + annotated source lines around each frame using linecache.
  3. It sends that context to gpt-4o via a single structured prompt that demands a JSON response.
  4. The JSON is parsed into an AnalysisResult and printed (or written to a file).
  5. The original exception is re-raised (unless reraise=False).

No third-party libraries are required — only urllib, json, traceback, and linecache from the Python standard library.

License

MIT

Metadata

Release files for smartcatch 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for smartcatch 0.1.0
File Size Uploaded Provenance
smartcatch-0.1.0.tar.gz 3.8 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for smartcatch 0.1.0
File Interpreter ABI Platform
smartcatch-0.1.0-py3-none-any.whl Python 3 none any Details

Total release size: 7.0 kB

Release files / smartcatch-0.1.0.tar.gz

Download URL smartcatch-0.1.0.tar.gz
Size 3.8 kB
Tags Source
SHA-256 checksum
How to use checksums
f6bc2c4c78f6427c594160bd037096d3fedabd2cfd8ae70616e731f476026998
BLAKE2b-256 checksum
How to use checksums
fb80c735c94d57feb0f44ed18b59a1a85ba8470026376ae0c40169020154383c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.14.2

Release files / smartcatch-0.1.0-py3-none-any.whl

Download URL smartcatch-0.1.0-py3-none-any.whl
Size 3.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
54c7a4a24642feffa48f21a7484e2d70a8039f53ca6115947c426fee5c65ed5b
BLAKE2b-256 checksum
How to use checksums
4a29071996410b8ed610f130ee747fc075f2f860f6287a14c094ec116f7fc770
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.14.2

Security for smartcatch 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page