Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Add Request/Response Interceptor Pattern
Overview
This PR introduces a flexible interceptor pattern to the OpenAI Python client, allowing users to intercept and modify requests before they are sent and responses after they are received. This enables powerful use cases like logging, retrying, metrics collection, and custom request/response manipulation.
Key Components
Core Interceptor Framework
InterceptorRequest
: Data class containing request details (method, URL, headers, params, body)InterceptorResponse
: Generic data class for response data (status code, headers, body, original request)Interceptor
: Abstract base class defining the interceptor interfaceInterceptorChain
: Manages a sequence of interceptors, executing them in orderExample Implementations
Added example interceptors demonstrating practical use cases:
LoggingInterceptor
: Provides detailed request/response loggingRetryInterceptor
: Implements exponential backoff retry logic for 5xx errorsUsage Example
client = OpenAI( interceptors=[ LoggingInterceptor(), RetryInterceptor(max_retries=3, initial_delay=1.0) ])
Benefits
Testing
examples/interceptor.py
Future Improvements
Breaking Changes
None. This is a new feature that maintains backward compatibility.