You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Langchain4J调用自定义Base URL的Anthropic模型时授权头缺失报错

Langchain4J对接企业自定义Base URL:Anthropic模型授权头缺失问题排查

环境信息

  • Langchain4J版本:0.36.2
  • Java版本:21
  • 部署场景:企业自定义Base URL的OpenAI与Anthropic模型,其中OpenAI模型可正常调用,Anthropic模型抛出授权头缺失错误

正常运行的OpenAI模型代码

// 此代码可正常运行无报错
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.model.output.Response;
import dev.langchain4j.model.chat.ChatMessage;
import dev.langchain4j.model.input.Prompt;

public class OpenAIChatExample {

    public static void main(String[] args) {
        
        String clientId = "myclientid";
        String clientSecret = "myclientsecret";
        
        TokenAuthenticator authenticator = new TokenAuthenticator(clientId, clientSecret);

        
        ChatLanguageModel model = OpenAiChatModel.builder()
                .baseUrl("https://mycustombaseurl")
                .apiKey(authenticator.getValidToken())
                .modelName("gpt-4o") 
                .build();

        try {
            
            String response = model.generate("What is LLM?");
            System.out.println("Simple Response: " + response);


        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
            e.printStackTrace();
        }
    }    
}

运行失败的Anthropic模型代码

// 此代码抛出错误:"Required Authorization header is missing"
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.anthropic.AnthropicChatModel;
import dev.langchain4j.model.output.Response;
import dev.langchain4j.model.chat.ChatMessage;
import dev.langchain4j.model.input.Prompt;

public class AnthropicChatExample {

    public static void main(String[] args) {
        
        String clientId = "myclientid";
        String clientSecret = "myclientsecret";
        
        TokenAuthenticator authenticator = new TokenAuthenticator(clientId, clientSecret);

        
        AnthropicChatModel model = AnthropicChatModel.builder()
                .baseUrl("https://mycustombaseurl")
                .apiKey(authenticator.getValidToken())
                .modelName("claude-3-5-sonnet") 
                .build();

        try {
            
            String response = model.generate("What is LLM?");
            System.out.println("Simple Response: " + response);


        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
            e.printStackTrace();
        }
    }    
}

报错信息

Caused by: dev.langchain4j.model.anthropic.internal.client.AnthropicHttpException: {"Error": "Required Authorization header is missing"}

build.gradle配置

plugins {
    id 'java'
}

group = 'org.example'
version = '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    testImplementation platform('org.junit:junit-bom:5.10.0')
    testImplementation 'org.junit.jupiter:junit-jupiter'
    implementation 'dev.langchain4j:langchain4j:0.36.2'
    implementation 'dev.langchain4j:langchain4j-core:0.36.2'
    implementation 'dev.langchain4j:langchain4j-open-ai:0.36.2'
    implementation group: 'dev.langchain4j', name: 'langchain4j-anthropic', version: '0.36.2'
    implementation 'dev.langchain4j:langchain4j-embeddings-all-minilm-l6-v2:0.36.2'
    implementation 'org.apache.httpcomponents.client5:httpclient5:5.2.1'
    implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2'
}

test {
    useJUnitPlatform()
}

排查分析与解决方案

可能原因

  1. Langchain4J Anthropic客户端版本bug:0.36.2版本的langchain4j-anthropic模块在自定义Base URL场景下,未正确将配置的apiKey注入到请求的Authorization头中,与OpenAI客户端的请求头构造逻辑存在差异。
  2. 企业网关授权格式要求差异:部分企业网关对Anthropic接口的授权头格式要求与原生Anthropic不同(原生为Bearer <token>),但OpenAI网关兼容当前token格式,导致Anthropic请求被拦截。

解决方案

方案1:手动配置自定义HttpClient,强制添加授权头

通过自定义Apache HttpClient拦截器,手动注入Authorization头,绕过Langchain4J Anthropic客户端的默认头构造逻辑:

import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.message.BasicHeader;

public class AnthropicChatExample {

    public static void main(String[] args) {
        
        String clientId = "myclientid";
        String clientSecret = "myclientsecret";
        TokenAuthenticator authenticator = new TokenAuthenticator(clientId, clientSecret);
        String validToken = authenticator.getValidToken();

        // 构建自定义HttpClient,添加Authorization头拦截器
        HttpClient httpClient = HttpClients.custom()
                .addRequestInterceptorFirst((request, context) -> {
                    request.addHeader(new BasicHeader("Authorization", "Bearer " + validToken));
                    return null;
                })
                .build();

        AnthropicChatModel model = AnthropicChatModel.builder()
                .baseUrl("https://mycustombaseurl")
                .httpClient(httpClient)
                .modelName("claude-3-5-sonnet")
                .build();

        try {
            String response = model.generate("What is LLM?");
            System.out.println("Simple Response: " + response);
        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
            e.printStackTrace();
        }
    }    
}

方案2:升级Langchain4J版本

检查Langchain4J更新日志,确认后续版本是否修复了自定义Base URL下Anthropic授权头的问题,尝试升级到最新稳定版本(如0.37+)后重新测试。

方案3:验证企业网关授权要求

联系企业网关管理员,确认Anthropic接口所需的授权头格式:

  • 是否需要使用X-API-Key而非Authorization?
  • token是否需要添加特定前缀(如ApiKey 而非Bearer )?
    若格式不同,可在自定义HttpClient中调整头的名称和值。

内容的提问来源于stack exchange,提问作者Sabari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 06:24:59