How to Add Extra Request Headers When Invoking a Model
I want to invoke an OpenAI-compatible model, but I need to add some specific custom request headers.
I created the options by calling GenerateOptions.builder().additionalOption("header1","value1").build(). I passed these options to OpenAIChatModel, then passed the OpenAIChatModel to ReActAgent, and finally executed the agent by calling ReActAgent.call().
However, upon debugging, I discovered that the request header was not successfully added. Is this an issue with my usage, or is it a bug in the framework? How should I resolve this?
PS: It appears that the header is successfully added when using OpenAIChatModel.stream, but I need to use ReActAgent. Could you please help investigate?
- You can pass custom
defaultOptionswhen constructing theOpenAIChatModel. - Currently, the implementation at the Model layer indeed does not map
additionalOptionsto the headers. We need to consider whether to useadditionalOptionsfor header mapping or to use a different key for this purpose. regarding this issue, would you be interested in contributing to the project to help address this?
1.您好,我在创建OpenAIChatModel的时候自定义了defaultOptions ,示例代码如下,但这种方式貌似无法在调用大模型时添加header。 2.谢谢您邀请我参与该项目建设,我还是非常乐意参与其中,但因我开发水平有限,恐无法提供一些有用的帮助,但我可尽己所能的参与其中进行问题分析处理,谢谢~
public static void main(String[] args) {
String apiKey = "xxx";
GenerateOptions generateOptions = GenerateOptions.builder()
.additionalOption("header1", "value1")
.build();
OpenAIChatModel chatModel = OpenAIChatModel.builder()
.apiKey(apiKey)
.baseUrl("http://localhost:8080/test")
.modelName("xxx")
.defaultOptions(generateOptions)
.build();
// 创建测试消息
Msg msg = Msg.builder()
.role(MsgRole.USER)
.content(TextBlock.builder()
.text("你好,什么是Java?")
.build())
.build();
// 创建 ReActAgent
ReActAgent agent = ReActAgent.builder()
.name("Assistant")
.model(chatModel)
.sysPrompt("你是一个人工智能助手,可以帮助用户回答相关问题")
.build();
// 调用智能体
Msg response = agent.call(msg).block();
System.out.println(response.getTextContent());
}
我这边更倾向在OpenAIChatModel中新增一个httpHeaders字段来存储请求头,这样更加见名知意。我在原本的代码上修改了一版,可以在构建OpenAIChatModel时传入请求头。
public class OpenAIChatModel extends ChatModelBase {
private static final Logger log = LoggerFactory.getLogger(OpenAIChatModel.class);
private final String baseUrl;
private final String apiKey;
private final String modelName;
private final ChatModel model;
private final boolean streamEnabled;
private final OpenAIClient client;
private final GenerateOptions defaultOptions;
private Map<String, String> httpHeaders = new HashMap<>();
private final Formatter<ChatCompletionMessageParam, Object, ChatCompletionCreateParams.Builder>
formatter;
/**
* Creates a new OpenAI chat model instance.
*
* @param baseUrl the base URL for OpenAI API (null for default)
* @param apiKey the API key for authentication (null for no authentication)
* @param modelName the model name to use (e.g., "gpt-4", "gpt-3.5-turbo")
* @param streamEnabled whether streaming should be enabled
* @param defaultOptions default generation options
* @param formatter the message formatter to use (null for default OpenAI formatter)
*/
public OpenAIChatModel(
String baseUrl,
String apiKey,
String modelName,
boolean streamEnabled,
GenerateOptions defaultOptions,
Map<String,String> httpHeaders,
Formatter<ChatCompletionMessageParam, Object, ChatCompletionCreateParams.Builder>
formatter) {
this.baseUrl = baseUrl;
this.apiKey = apiKey;
this.modelName = modelName;
this.model = ChatModel.of(modelName);
this.streamEnabled = streamEnabled;
this.defaultOptions =
defaultOptions != null ? defaultOptions : GenerateOptions.builder().build();
this.httpHeaders = httpHeaders;
this.formatter = formatter != null ? formatter : new OpenAIChatFormatter();
// Initialize OpenAI client
OpenAIOkHttpClient.Builder clientBuilder = OpenAIOkHttpClient.builder();
if (apiKey != null) {
clientBuilder.apiKey(apiKey);
}
if (baseUrl != null) {
clientBuilder.baseUrl(baseUrl);
}
// Set unified AgentScope User-Agent (overrides OpenAI SDK default)
clientBuilder.putHeader("User-Agent", Version.getUserAgent());
if(httpHeaders.size() > 0){
for (String key : httpHeaders.keySet()) {
clientBuilder.putHeader(key,httpHeaders.get(key));
}
}
this.client = clientBuilder.build();
}
/**
* Stream chat completion responses from OpenAI's API.
*
* <p>This method internally handles message formatting using the configured formatter.
* It supports both streaming and non-streaming modes based on the streamEnabled setting.
*
* <p>Supports timeout and retry configuration through GenerateOptions:
* <ul>
* <li>Request timeout: Cancels the request if it exceeds the specified duration</li>
* <li>Retry config: Automatically retries failed requests with exponential backoff</li>
* </ul>
*
* @param messages AgentScope messages to send to the model
* @param tools Optional list of tool schemas (null or empty if no tools)
* @param options Optional generation options (null to use defaults)
* @return Flux stream of chat responses
*/
@Override
protected Flux<ChatResponse> doStream(
List<Msg> messages, List<ToolSchema> tools, GenerateOptions options) {
Instant startTime = Instant.now();
log.debug(
"OpenAI stream: model={}, messages={}, tools_present={}",
model,
messages != null ? messages.size() : 0,
tools != null && !tools.isEmpty());
Flux<ChatResponse> responseFlux =
Flux.deferContextual(
(reactorCtx) ->
TracerRegistry.get()
.runWithContext(
reactorCtx,
() -> {
try {
// Build chat completion request
ChatCompletionCreateParams.Builder
paramsBuilder =
ChatCompletionCreateParams
.builder()
.model(model);
// Use formatter to convert Msg to OpenAI
// ChatCompletionMessageParam
List<ChatCompletionMessageParam>
formattedMessages =
formatter.format(messages);
for (ChatCompletionMessageParam param :
formattedMessages) {
paramsBuilder.addMessage(param);
}
// Add tools if provided
if (tools != null && !tools.isEmpty()) {
formatter.applyTools(
paramsBuilder, tools);
}
// Apply generation options via formatter
formatter.applyOptions(
paramsBuilder,
options,
defaultOptions);
// Apply tool choice if available
applyToolChoiceIfAvailable(
paramsBuilder, options);
// Create the request
ChatCompletionCreateParams params =
paramsBuilder.build();
if (streamEnabled) {
// Make streaming API call
StreamResponse<ChatCompletionChunk>
streamResponse =
client.chat()
.completions()
.createStreaming(
params);
// Convert the SDK's Stream to Flux
return Flux.fromStream(
streamResponse.stream())
.publishOn(
Schedulers
.boundedElastic())
.map(
chunk ->
formatter
.parseResponse(
chunk,
startTime))
.filter(Objects::nonNull)
.doFinally(
signalType -> {
try {
streamResponse
.close();
} catch (
Exception
ignored) {
}
});
} else {
// For non-streaming, make a single call
// and return as Flux
ChatCompletion completion =
client.chat()
.completions()
.create(params);
ChatResponse response =
formatter.parseResponse(
completion, startTime);
return Flux.just(response);
}
} catch (Exception e) {
return Flux.error(
new ModelException(
"Failed to stream OpenAI"
+ " API: "
+ e.getMessage(),
e,
modelName,
"openai"));
}
}));
// Apply timeout and retry if configured
return ModelUtils.applyTimeoutAndRetry(
responseFlux, options, defaultOptions, modelName, "openai", log);
}
/**
* Gets the model name for logging and identification.
*
* @return the model name
*/
@Override
public String getModelName() {
return modelName;
}
/**
* Gets the base URL for OpenAI API.
*
* @return the base URL
* */
public String getBaseUrl() {
return baseUrl;
}
/**
* Apply tool choice configuration if available in options.
*
* @param paramsBuilder OpenAI request parameters builder
* @param options Generation options containing tool choice
*/
private void applyToolChoiceIfAvailable(
ChatCompletionCreateParams.Builder paramsBuilder, GenerateOptions options) {
GenerateOptions opt = options != null ? options : defaultOptions;
if (opt.getToolChoice() != null) {
formatter.applyToolChoice(paramsBuilder, opt.getToolChoice());
}
}
/**
* Creates a new builder for OpenAIChatModel.
*
* @return a new Builder instance
*/
public static Builder builder() {
return new Builder();
}
public static class Builder {
private String baseUrl;
private String apiKey;
private String modelName;
private boolean streamEnabled = true;
private GenerateOptions defaultOptions = null;
private Map<String, String> httpHeaders = new HashMap<>();
private Formatter<ChatCompletionMessageParam, Object, ChatCompletionCreateParams.Builder>
formatter;
/**
* Sets the base URL for OpenAI API.
*
* @param baseUrl the base URL (null for default OpenAI API)
* @return this builder instance
*/
public Builder baseUrl(String baseUrl) {
this.baseUrl = baseUrl;
return this;
}
/**
* Sets the API key for authentication.
*
* @param apiKey the API key (null for no authentication)
* @return this builder instance
*/
public Builder apiKey(String apiKey) {
this.apiKey = apiKey;
return this;
}
/**
* Sets the model name to use.
*
* @param modelName the model name (e.g., "gpt-4", "gpt-3.5-turbo")
* @return this builder instance
*/
public Builder modelName(String modelName) {
this.modelName = modelName;
return this;
}
/**
* Sets whether streaming should be enabled.
*
* @param streamEnabled true to enable streaming, false for non-streaming
* @return this builder instance
*/
public Builder stream(boolean streamEnabled) {
this.streamEnabled = streamEnabled;
return this;
}
/**
* Sets the default generation options.
*
* @param options the default options to use
* @return this builder instance
*/
public Builder defaultOptions(GenerateOptions options) {
this.defaultOptions = options;
return this;
}
public Builder defaultHeaders(Map<String,String> httpHeaders) {
this.httpHeaders = httpHeaders;
return this;
}
/**
* Sets the message formatter to use.
*
* @param formatter the formatter (null for default OpenAI formatter)
* @return this builder instance
*/
public Builder formatter(
Formatter<ChatCompletionMessageParam, Object, ChatCompletionCreateParams.Builder>
formatter) {
this.formatter = formatter;
return this;
}
/**
* Builds the OpenAIChatModel instance.
*
* <p>This method ensures that the defaultOptions always has proper executionConfig
* applied: - If no defaultOptions are provided, uses MODEL_DEFAULTS for
* executionConfig - If defaultOptions are provided but executionConfig is null, merges
* user-provided options with MODEL_DEFAULTS
*
* <p>Uses ModelUtils.ensureDefaultExecutionConfig() to apply defaults consistently across
* all model implementations.
*
* @return configured OpenAIChatModel instance
*/
public OpenAIChatModel build() {
GenerateOptions effectiveOptions =
ModelUtils.ensureDefaultExecutionConfig(defaultOptions);
return new OpenAIChatModel(
baseUrl, apiKey, modelName, streamEnabled, effectiveOptions, httpHeaders, formatter);
}
}
}
改了一版 GenerateOptions https://github.com/agentscope-ai/agentscope-java/pull/119 ,可以看一下这个修改是不是可用
我这边测试不通过,发现以有个问题,请帮忙确认问题是否属实: ReActAgent#prepareAndStream()方法,会创建一个默认的GenerateOptions,当执行到OpenAIToolsHelper#applyOptions方法时(96行),该options会覆盖掉defaultOptions,导致创建OpenAIChatModel时指定的defaultOptions无效。
我这边测试不通过,发现以有个问题,请帮忙确认问题是否属实: ReActAgent#prepareAndStream()方法,会创建一个默认的GenerateOptions,当执行到OpenAIToolsHelper#applyOptions方法时(96行),该options会覆盖掉defaultOptions,导致创建OpenAIChatModel时指定的defaultOptions无效。
更新了一下,现在会聚合所有的数据,麻烦再测试下
测试了一下,可以正常添加参数了,感谢~ 另外想问下,通过这种方式构建的ReActAgent,貌似构建后header就是固定的。假如我想每次发起的http请求,给大模型传递的header都不一样,该怎么处理呢,是需要每次都创建一个新的ReActAgent,不能复用同一个对象吗?
测试了一下,可以正常添加参数了,感谢~ 另外想问下,通过这种方式构建的ReActAgent,貌似构建后header就是固定的。假如我想每次发起的http请求,给大模型传递的header都不一样,该怎么处理呢,是需要每次都创建一个新的ReActAgent,不能复用同一个对象吗?
在 AgentScope 的设计理念中,ReActAgent 对象是并发不安全的,多个用户之间不能共享 Agent 对象。另外每次都 header 不一样的原因方便说一下吗?
我们调用的模型的apikey是应用纬度的,模型侧要求应用侧上送用户id