haystack icon indicating copy to clipboard operation
haystack copied to clipboard

[Proposal] Support callable api token providers for Chat Generators

Open HamzaDLM opened this issue 6 months ago • 2 comments

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.

HamzaDLM avatar May 13 '26 19:05 HamzaDLM

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:

  1. Recreate the client before each request when api_key is callable — simple, but loses connection pooling.
  2. 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.

sachinn854 avatar May 22 '26 10:05 sachinn854

We have an idea how to address this issue and I am closing this as a duplicate of deepset-ai/haystack-private#448

julian-risch avatar May 22 '26 13:05 julian-risch