2828import com .sap .cloud .sdk .cloudplatform .connectivity .Header ;
2929import com .sap .cloud .sdk .cloudplatform .connectivity .HttpDestination ;
3030import java .io .IOException ;
31+ import java .util .ArrayList ;
32+ import java .util .List ;
3133import java .util .stream .Stream ;
3234import javax .annotation .Nonnull ;
3335import javax .annotation .Nullable ;
@@ -50,6 +52,7 @@ public final class OpenAiClient {
5052 @ Nullable private String systemPrompt = null ;
5153
5254 @ Nonnull private final Destination destination ;
55+ @ Nonnull private final List <Header > customHeaders = new ArrayList <>();
5356
5457 /**
5558 * Create a new OpenAI client for the given foundation model, using the default resource group.
@@ -139,11 +142,10 @@ public OpenAiClient withSystemPrompt(@Nonnull final String systemPrompt) {
139142 @ Beta
140143 @ Nonnull
141144 public OpenAiClient withHeader (@ Nonnull final String key , @ Nonnull final String value ) {
142- final var newDestination =
143- DefaultHttpDestination .fromDestination (this .destination )
144- .header (new Header (key , value ))
145- .build ();
146- return new OpenAiClient (newDestination );
145+ final var newClient = new OpenAiClient (this .destination );
146+ newClient .customHeaders .addAll (this .customHeaders );
147+ newClient .customHeaders .add (new Header (key , value ));
148+ return newClient ;
147149 }
148150
149151 /**
@@ -414,7 +416,7 @@ private <T> T execute(
414416 @ Nonnull final Object payload ,
415417 @ Nonnull final Class <T > responseType ) {
416418 final var request = new HttpPost (path );
417- serializeAndSetHttpEntity (request , payload );
419+ serializeAndSetHttpEntity (request , payload , this . customHeaders );
418420 return executeRequest (request , responseType );
419421 }
420422
@@ -424,15 +426,18 @@ private <D extends StreamedDelta> Stream<D> executeStream(
424426 @ Nonnull final Object payload ,
425427 @ Nonnull final Class <D > deltaType ) {
426428 final var request = new HttpPost (path );
427- serializeAndSetHttpEntity (request , payload );
429+ serializeAndSetHttpEntity (request , payload , this . customHeaders );
428430 return streamRequest (request , deltaType );
429431 }
430432
431433 private static void serializeAndSetHttpEntity (
432- @ Nonnull final BasicClassicHttpRequest request , @ Nonnull final Object payload ) {
434+ @ Nonnull final BasicClassicHttpRequest request ,
435+ @ Nonnull final Object payload ,
436+ @ Nonnull final List <Header > customHeaders ) {
433437 try {
434438 final var json = JACKSON .writeValueAsString (payload );
435439 request .setEntity (new StringEntity (json , ContentType .APPLICATION_JSON ));
440+ customHeaders .forEach (h -> request .addHeader (h .getName (), h .getValue ()));
436441 } catch (final JsonProcessingException e ) {
437442 throw new OpenAiClientException ("Failed to serialize request parameters" , e )
438443 .setHttpRequest (request );
0 commit comments