API Reference

Core API

eTracer: An enhanced Python tracer

copyright:

2025, Emmanuel King Kasulani

license:

Apache License 2.0, see LICENSE for more details.

A utility package that provides enhanced debugging for Python stack traces. It hijacks the default exception handling process to provide clearer, more readable stack traces with AI-powered explanations and suggested fixes.

class etracer.Tracer(ai_client=None, printer=None, cache=None, progress_indicator=None)[source]

Bases: object

Main tracer class that handles exception interception and formatting.

Parameters:
analyze(func)[source]

Decorator to catch and format exceptions in a function.

Parameters:

func (Callable) – The function to decorate

Returns:

Wrapped function with exception handling

Return type:

Callable

analyze_exception(exception)[source]

Explicitly analyze an exception that’s been caught.

Parameters:

exception (Exception) – The caught exception

Return type:

None

analyzer()[source]

Context manager to catch and format exceptions.

Returns:

A context manager object that can be used with the ‘with’ statement.

Return type:

Any

Usage:
with etracer.analyzer:

# code that might raise exceptions

disable()[source]

Disable the tracer and restore the original excepthook.

Return type:

None

enable(verbosity=2, enable_ai=False, api_key=None, model=None, base_url=None)[source]

Enable the tracer by replacing the default excepthook.

Parameters:
  • verbosity (int) – How much detail to show (0=minimal, 1=normal, 2=detailed)

  • enable_ai (bool) – Whether to use AI for error analysis

  • api_key (str | None) – API key for AI analysis

  • model (str | None) – AI model to use for analysis

  • base_url (str | None) – Base URL for the AI API

Return type:

None

exception_handler(exc_type, exc_value, exc_traceback)[source]

Custom exception handler to replace sys.excepthook.

Parameters:
  • exc_type (Type[BaseException]) – The exception type

  • exc_value (BaseException) – The exception value/message

  • exc_traceback (TracebackType | None) – The traceback object

Return type:

None

etracer.enable(verbosity=2, enable_ai=False, api_key=None, model=None, base_url=None)

Enable the tracer by replacing the default excepthook.

Parameters:
  • verbosity (int) – How much detail to show (0=minimal, 1=normal, 2=detailed)

  • enable_ai (bool) – Whether to use AI for error analysis

  • api_key (str | None) – API key for AI analysis

  • model (str | None) – AI model to use for analysis

  • base_url (str | None) – Base URL for the AI API

Return type:

None

etracer.disable()

Disable the tracer and restore the original excepthook.

Return type:

None

etracer.analyze(func)

Decorator to catch and format exceptions in a function.

Parameters:

func (Callable) – The function to decorate

Returns:

Wrapped function with exception handling

Return type:

Callable

etracer.analyze_exception(exception)

Explicitly analyze an exception that’s been caught.

Parameters:

exception (Exception) – The caught exception

Return type:

None

etracer.set_printer(printer)[source]

Set a custom printer for the tracer.

Parameters:

printer (PrinterInterface)

Return type:

None

class etracer.Frame(*, filename, lineno, function, lines, code_snippet, locals)[source]

Bases: BaseModel

Model for a single traceback frame.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Parameters:
  • filename (str)

  • lineno (int)

  • function (str)

  • lines (List[Tuple[int, str]])

  • code_snippet (str)

  • locals (Dict[str, Any])

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

filename: str
lineno: int
function: str
lines: List[Tuple[int, str]]
code_snippet: str
locals: Dict[str, Any]
class etracer.DataForAnalysis(*, exception_type, exception_message, frames, most_relevant_frame)[source]

Bases: BaseModel

Model for structured error data to be sent for AI analysis.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Parameters:
  • exception_type (str)

  • exception_message (str)

  • frames (List[Frame])

  • most_relevant_frame (Frame)

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

exception_type: str
exception_message: str
frames: List[Frame]
most_relevant_frame: Frame
class etracer.AiAnalysis(*, explanation, suggested_fix)[source]

Bases: BaseModel

Model for AI analysis response.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Parameters:
  • explanation (str)

  • suggested_fix (str)

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

explanation: str
suggested_fix: str
class etracer.CacheData(*, timestamp, explanation, suggested_fix)[source]

Bases: BaseModel

Model for cached AI analysis data.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Parameters:
  • timestamp (float)

  • explanation (str)

  • suggested_fix (str)

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

timestamp: float
explanation: str
suggested_fix: str
class etracer.AnalysisGetterInterface(*args, **kwargs)[source]

Bases: Protocol

Interface for getting AI-powered analysis.

get_analysis(system_prompt, user_prompt)[source]

Get AI-powered analysis for the provided error data.

Parameters:
  • system_prompt (str) – System prompt for AI context

  • user_prompt (str) – User prompt for AI analysis

Returns:

AiAnalysis object with explanation and suggested fix

Return type:

AiAnalysis

class etracer.CacheInterface(*args, **kwargs)[source]

Bases: Protocol

Interface for caching functionality.

get(key)[source]

Get a value from the cache.

Parameters:

key (str) – The cache key

Returns:

The cached value or None if not found

Return type:

CacheData | None

set(key, value)[source]

Set a value in the cache.

Parameters:
  • key (str) – The cache key

  • value (CacheData) – The value to cache

Return type:

None

class etracer.PrinterInterface(*args, **kwargs)[source]

Bases: Protocol

Interface for printing messages with verbosity control.

print(message, verbosity=1)[source]

Print a message with verbosity control.

Parameters:
  • message (str) – The message to print

  • verbosity (int) – The minimum verbosity level required to print this message

Return type:

None

set_verbosity(verbosity)[source]

Set the verbosity level for printing messages. :param verbosity: The new verbosity level

Parameters:

verbosity (int)

Return type:

None

class etracer.ProgressIndicatorInterface(*args, **kwargs)[source]

Bases: Protocol

Interface for progress indicators.

start()[source]

Start a spinner animation in a separate thread.

Return type:

None

stop()[source]

Stop the spinner animation.

Return type:

None

class etracer.TimerInterface(*args, **kwargs)[source]

Bases: Protocol

Interface for timing operations.

elapsed()[source]

Get elapsed time since the timer was started.

Returns:

Elapsed time in seconds

Return type:

float

Tracer

etracer: Enhanced Python tracer with AI-powered error analysis

class etracer.tracer.Tracer(ai_client=None, printer=None, cache=None, progress_indicator=None)[source]

Bases: object

Main tracer class that handles exception interception and formatting.

Parameters:
analyze_exception(exception)[source]

Explicitly analyze an exception that’s been caught.

Parameters:

exception (Exception) – The caught exception

Return type:

None

analyze(func)[source]

Decorator to catch and format exceptions in a function.

Parameters:

func (Callable) – The function to decorate

Returns:

Wrapped function with exception handling

Return type:

Callable

analyzer()[source]

Context manager to catch and format exceptions.

Returns:

A context manager object that can be used with the ‘with’ statement.

Return type:

Any

Usage:
with etracer.analyzer:

# code that might raise exceptions

enable(verbosity=2, enable_ai=False, api_key=None, model=None, base_url=None)[source]

Enable the tracer by replacing the default excepthook.

Parameters:
  • verbosity (int) – How much detail to show (0=minimal, 1=normal, 2=detailed)

  • enable_ai (bool) – Whether to use AI for error analysis

  • api_key (str | None) – API key for AI analysis

  • model (str | None) – AI model to use for analysis

  • base_url (str | None) – Base URL for the AI API

Return type:

None

disable()[source]

Disable the tracer and restore the original excepthook.

Return type:

None

exception_handler(exc_type, exc_value, exc_traceback)[source]

Custom exception handler to replace sys.excepthook.

Parameters:
  • exc_type (Type[BaseException]) – The exception type

  • exc_value (BaseException) – The exception value/message

  • exc_traceback (TracebackType | None) – The traceback object

Return type:

None

etracer.tracer.enable(verbosity=2, enable_ai=False, api_key=None, model=None, base_url=None)

Enable the tracer by replacing the default excepthook.

Parameters:
  • verbosity (int) – How much detail to show (0=minimal, 1=normal, 2=detailed)

  • enable_ai (bool) – Whether to use AI for error analysis

  • api_key (str | None) – API key for AI analysis

  • model (str | None) – AI model to use for analysis

  • base_url (str | None) – Base URL for the AI API

Return type:

None

etracer.tracer.disable()

Disable the tracer and restore the original excepthook.

Return type:

None

etracer.tracer.analyze(func)

Decorator to catch and format exceptions in a function.

Parameters:

func (Callable) – The function to decorate

Returns:

Wrapped function with exception handling

Return type:

Callable

etracer.tracer.analyze_exception(exception)

Explicitly analyze an exception that’s been caught.

Parameters:

exception (Exception) – The caught exception

Return type:

None

etracer.tracer.set_printer(printer)[source]

Set a custom printer for the tracer.

Parameters:

printer (PrinterInterface)

Return type:

None

Models

class etracer.models.Frame(*, filename, lineno, function, lines, code_snippet, locals)[source]

Bases: BaseModel

Model for a single traceback frame.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Parameters:
  • filename (str)

  • lineno (int)

  • function (str)

  • lines (List[Tuple[int, str]])

  • code_snippet (str)

  • locals (Dict[str, Any])

filename: str
lineno: int
function: str
lines: List[Tuple[int, str]]
code_snippet: str
locals: Dict[str, Any]
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class etracer.models.DataForAnalysis(*, exception_type, exception_message, frames, most_relevant_frame)[source]

Bases: BaseModel

Model for structured error data to be sent for AI analysis.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Parameters:
  • exception_type (str)

  • exception_message (str)

  • frames (List[Frame])

  • most_relevant_frame (Frame)

exception_type: str
exception_message: str
frames: List[Frame]
most_relevant_frame: Frame
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class etracer.models.AiAnalysis(*, explanation, suggested_fix)[source]

Bases: BaseModel

Model for AI analysis response.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Parameters:
  • explanation (str)

  • suggested_fix (str)

explanation: str
suggested_fix: str
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class etracer.models.CacheData(*, timestamp, explanation, suggested_fix)[source]

Bases: BaseModel

Model for cached AI analysis data.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Parameters:
  • timestamp (float)

  • explanation (str)

  • suggested_fix (str)

timestamp: float
explanation: str
suggested_fix: str
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

Interfaces

Interface definitions for etracer.

This module contains all protocol classes that define interfaces for the package. These interfaces provide contracts that implementations must follow.

class etracer.interfaces.PrinterInterface(*args, **kwargs)[source]

Bases: Protocol

Interface for printing messages with verbosity control.

print(message, verbosity=1)[source]

Print a message with verbosity control.

Parameters:
  • message (str) – The message to print

  • verbosity (int) – The minimum verbosity level required to print this message

Return type:

None

set_verbosity(verbosity)[source]

Set the verbosity level for printing messages. :param verbosity: The new verbosity level

Parameters:

verbosity (int)

Return type:

None

class etracer.interfaces.CacheInterface(*args, **kwargs)[source]

Bases: Protocol

Interface for caching functionality.

set(key, value)[source]

Set a value in the cache.

Parameters:
  • key (str) – The cache key

  • value (CacheData) – The value to cache

Return type:

None

get(key)[source]

Get a value from the cache.

Parameters:

key (str) – The cache key

Returns:

The cached value or None if not found

Return type:

CacheData | None

class etracer.interfaces.AnalysisGetterInterface(*args, **kwargs)[source]

Bases: Protocol

Interface for getting AI-powered analysis.

get_analysis(system_prompt, user_prompt)[source]

Get AI-powered analysis for the provided error data.

Parameters:
  • system_prompt (str) – System prompt for AI context

  • user_prompt (str) – User prompt for AI analysis

Returns:

AiAnalysis object with explanation and suggested fix

Return type:

AiAnalysis

class etracer.interfaces.ProgressIndicatorInterface(*args, **kwargs)[source]

Bases: Protocol

Interface for progress indicators.

start()[source]

Start a spinner animation in a separate thread.

Return type:

None

stop()[source]

Stop the spinner animation.

Return type:

None

class etracer.interfaces.TimerInterface(*args, **kwargs)[source]

Bases: Protocol

Interface for timing operations.

elapsed()[source]

Get elapsed time since the timer was started.

Returns:

Elapsed time in seconds

Return type:

float

Utilities

AI Client

AI client implementation for etracer.

class etracer.utils.ai_client.AIConfig[source]

Bases: object

Configuration for AI integration.

configure(api_key=None, base_url=None, model=None, timeout=None, enabled=None, use_cache=None)[source]

Configure the AI settings.

Parameters:
  • api_key (str | None)

  • base_url (str | None)

  • model (str | None)

  • timeout (int | None)

  • enabled (bool | None)

  • use_cache (bool | None)

Return type:

None

class etracer.utils.ai_client.AIClient(config)[source]

Bases: AnalysisGetterInterface

Client for making API requests to the AI service.

Parameters:

config (AIConfig)

get_analysis(system_prompt, user_prompt)[source]

Get AI-powered analysis for the provided error data.

Parameters:
  • system_prompt (str) – System prompt for AI context

  • user_prompt (str) – User prompt for AI analysis

Returns:

AiAnalysis object with explanation and suggested fix

Return type:

AiAnalysis

Cache

Cache implementations for etracer.

class etracer.utils.cache.CacheConfig[source]

Bases: object

Configuration for cache settings.

configure(cache_ttl=None, use_cache=None)[source]

Configure the cache settings.

Parameters:
  • cache_ttl (int | None)

  • use_cache (bool | None)

Return type:

None

class etracer.utils.cache.FileBasedCache(config, cache_dir='/home/runner/work/etracer/etracer/docs/.tracer_cache')[source]

Bases: CacheInterface

File-based cache implementation for storing AI responses.

Parameters:
set(key, value)[source]

Set a value in the cache.

Parameters:
  • key (str) – The cache key

  • value (CacheData) – The value to cache

Return type:

None

get(key)[source]

Get a value from the cache.

Parameters:

key (str) – The cache key

Returns:

The cached value or None if not found or expired

Return type:

CacheData | None

Printer

Printer implementations for etracer.

class etracer.utils.printer.Colors[source]

Bases: object

HEADER = '\x1b[95m'
BLUE = '\x1b[94m'
CYAN = '\x1b[96m'
GREEN = '\x1b[92m'
WARNING = '\x1b[93m'
FAIL = '\x1b[91m'
ENDC = '\x1b[0m'
BOLD = '\x1b[1m'
UNDERLINE = '\x1b[4m'
class etracer.utils.printer.ConsolePrinter(verbosity=2)[source]

Bases: PrinterInterface

Default printer implementation that prints to the console.

Initialize the printer with a verbosity level.

Parameters:

verbosity (int) – The verbosity level (0=minimal, 1=normal, 2=detailed)

print(message, verbosity=1)[source]

Print a message if the verbosity level is high enough.

Parameters:
  • message (str) – The message to print

  • verbosity (int) – The minimum verbosity level required to print this message

Return type:

None

set_verbosity(verbosity)[source]

Set the verbosity level.

Parameters:

verbosity (int) – The new verbosity level

Return type:

None

Spinner

Progress indicators for etracer.

class etracer.utils.spinner.Spinner(stop_event, output=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, message='Processing')[source]

Bases: ProgressIndicatorInterface

Spinner animation for indicating progress in a separate thread.

Initialize the spinner with a stop event and output stream. :param stop_event: Threading event to signal when to stop the spinner :param output: Output stream (default: sys.stdout) :param message: Message to display next to the spinner

Parameters:
  • stop_event (Event)

  • output (TextIO)

  • message (str)

start()[source]

Start a spinner animation in a separate thread.

Return type:

None

stop()[source]

Stop the spinner animation.

Return type:

None

Timer

Timer utilities for etracer.

class etracer.utils.timer.Timer[source]

Bases: TimerInterface

Timer for measuring elapsed time with context manager support.

Initialize the timer.

elapsed()[source]

Get elapsed time since the timer was started.

Returns:

Elapsed time in seconds

Return type:

float