[Proposal] Support callable api token providers for Chat Generators
Is your feature request related to a problem? Please describe. Chat generators (e.g. OpenAIChatGenerator) do not support rotating/short-lived API tokens since they construct the clients (OpenAI and AsyncOpenAI) at the init level.
Describe the solution you'd like Support for api_key to accept a callable that handles token refresh.
Describe alternatives you've considered Wrapping the OpenAIChatGenerator class and replacing the OpenAI and AsyncOpenAI clients with fresh tokens.
Hi! I was looking into this issue and wanted to share some findings before anyone starts implementing.
On serialization:
This seems solvable — Haystack already has serialize_callable / deserialize_callable utilities
used for streaming_callback in the same class. The same pattern could apply to a callable api_key.
A design concern worth discussing:
Currently the OpenAI client is built once at __init__ with the token baked in:
client_kwargs = {"api_key": api_key.resolve_value(), ...}
self.client = OpenAI(**client_kwargs)
If api_key is a callable, a fresh token is needed before each request — but the existing client
already has the old token stored internally. Two possible approaches come to mind:
- Recreate the client before each request when
api_keyis callable — simple, but loses connection pooling. - Use OpenAI SDK's per-request options to inject a fresh token without rebuilding the client.
Wanted to flag this early so the right approach can be decided before implementation.
We have an idea how to address this issue and I am closing this as a duplicate of deepset-ai/haystack-private#448