Skip to content

Expose attempt metadata on completion:error and completion:last_attempt hooks #2222

@aress31

Description

@aress31

Summary

completion:error and completion:last_attempt currently only receive the raised exception, but not retry metadata such as attempt_number.

This makes it hard to build clean logging around retries. In particular, a client cannot distinguish:

  • an intermediate retryable API error
  • the final failed attempt

without keeping extra local state or reconstructing retry behavior externally.

Current behavior

Hook signatures appear to be:

  • completion:kwargs -> handler(*args, **kwargs)
  • completion:response -> handler(response)
  • completion:error -> handler(error)
  • completion:last_attempt -> handler(error)

Internally, retry logic already has access to attempt.retry_state.attempt_number, but that metadata is not forwarded to the error hooks.

Desired behavior

Please expose retry metadata to completion:error and completion:last_attempt, for example one of:

  1. Add keyword metadata to those hooks:

    • handler(error, *, attempt_number: int, max_attempts: int | None, is_last_attempt: bool)
  2. Or pass _instructor_meta consistently, similar to completion:kwargs

  3. Or add a structured event object instead of a bare exception

Use case

I’m integrating Instructor into a CLI and want to:

  • log retryable API errors at lower severity for intermediate attempts
  • suppress duplicate "API error" logs when the final completion:last_attempt hook will fire immediately after
  • render better retry UX without maintaining my own shadow retry counter

Right now, the only clean workaround is local state or waiting for the final InstructorRetryException, which loses hook-time context.

Notes

The retry implementation already tracks:

  • attempt.retry_state.attempt_number
  • failed_attempts
  • n_attempts on InstructorRetryException

So this seems like the metadata already exists internally and would mainly need to be surfaced through the hook API.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requesthelp wantedExtra attention is neededpythonPull requests that update python code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions