laravel icon indicating copy to clipboard operation
laravel copied to clipboard

Feature Request: Add support for per-request custom headers

Open larskoole opened this issue 5 months ago • 2 comments

Feature Request

Problem

Currently, the Laravel facade doesn't provide a way to set custom headers for individual requests. Headers can only be set globally when the client is instantiated in the ServiceProvider. This limitation makes it difficult to add request-specific headers for solutions like AI Gateway from Cloudflare: https://developers.cloudflare.com/ai-gateway/configuration/caching/#per-request-caching

Proposed Solution

Add a withHeaders() method that can be chained before accessing resources like chat(), completions(), etc.

Ideal API:

use OpenAI\Laravel\Facades\OpenAI;

$result = OpenAI::withHeaders([
    'x-custom-header' => 'custom-value',
    'cf-aig-skip-cache' => true,
])
->chat()
->create([
    'model' => 'o3',
    'messages' => [
        ['role' => 'user', 'content' => 'Hello!'],
    ],
]);

Benefits

  • Enables request-specific headers without creating multiple client instances
  • Maintains the clean facade API while adding flexibility
  • Useful for logging, tracing, authentication, and other middleware scenarios

Current Workaround

Users currently need to create separate client instances with custom HTTP clients, which is verbose and doesn't integrate well with the Laravel facade pattern.

larskoole avatar Jul 22 '25 08:07 larskoole

I like the idea, but we have an issue at the moment that the facade already has the client built at that point. Since we are a PSR-18 generic implementation - how can you "on-the-fly" attach a header?

I'll have to do some brainstorming.

iBotPeaches avatar Jul 22 '25 19:07 iBotPeaches

Since we had an issue that prevent us from globally applying the Beta/v2 - Assistant header I had to write something to apply specific headers to specific endpoints only. Unfortunately its not exposed to user-land yet, but this does set the bones to allow this: https://github.com/openai-php/client/pull/688

iBotPeaches avatar Oct 02 '25 10:10 iBotPeaches