-
Notifications
You must be signed in to change notification settings - Fork 1.3k
feat(anthropic): support bearer token authentication #3038
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
qiyu-lu
wants to merge
1
commit into
agentscope-ai:main
Choose a base branch
from
qiyu-lu:feat/anthropic-bearer-auth
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
166 changes: 166 additions & 0 deletions
166
...t/java/io/agentscope/extensions/model/anthropic/AnthropicChatModelAuthenticationTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,166 @@ | ||
| /* | ||
| * Copyright 2024-2026 the original author or authors. | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
| package io.agentscope.extensions.model.anthropic; | ||
|
|
||
| import static org.junit.jupiter.api.Assertions.assertEquals; | ||
| import static org.junit.jupiter.api.Assertions.assertNotNull; | ||
|
|
||
| import io.agentscope.core.message.Msg; | ||
| import io.agentscope.core.message.MsgRole; | ||
| import io.agentscope.core.message.TextBlock; | ||
| import io.agentscope.core.model.ChatResponse; | ||
| import java.io.IOException; | ||
| import java.time.Duration; | ||
| import java.util.List; | ||
| import java.util.concurrent.TimeUnit; | ||
| import okhttp3.mockwebserver.MockResponse; | ||
| import okhttp3.mockwebserver.MockWebServer; | ||
| import okhttp3.mockwebserver.RecordedRequest; | ||
| import org.junit.jupiter.api.AfterEach; | ||
| import org.junit.jupiter.api.BeforeEach; | ||
| import org.junit.jupiter.api.Tag; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.junit.jupiter.params.ParameterizedTest; | ||
| import org.junit.jupiter.params.provider.CsvSource; | ||
|
|
||
| /** Verifies authentication headers through the real SDK against a local HTTP server. */ | ||
| @Tag("integration") | ||
| class AnthropicChatModelAuthenticationTest { | ||
|
|
||
| private static final String MESSAGE_RESPONSE = | ||
| """ | ||
| { | ||
| "id": "msg_gateway", "type": "message", "role": "assistant", | ||
| "model": "claude-sonnet-4.5", | ||
| "content": [{"type": "text", "text": "Hello"}], | ||
| "stop_reason": "end_turn", "stop_sequence": null, | ||
| "usage": {"input_tokens": 1, "output_tokens": 1} | ||
| } | ||
| """; | ||
|
|
||
| private static final String STREAM_RESPONSE = | ||
| """ | ||
| event: message_start | ||
| data: {"type":"message_start","message":{"id":"msg_gateway","type":"message","role":"assistant","model":"claude-sonnet-4.5","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"output_tokens":0}}} | ||
|
|
||
| event: content_block_start | ||
| data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}} | ||
|
|
||
| event: content_block_delta | ||
| data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello"}} | ||
|
|
||
| event: content_block_stop | ||
| data: {"type":"content_block_stop","index":0} | ||
|
|
||
| event: message_delta | ||
| data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":1}} | ||
|
|
||
| event: message_stop | ||
| data: {"type":"message_stop"} | ||
|
|
||
| """; | ||
|
|
||
| private MockWebServer server; | ||
|
|
||
| @BeforeEach | ||
| void setUp() throws IOException { | ||
| server = new MockWebServer(); | ||
| server.start(); | ||
| } | ||
|
|
||
| @AfterEach | ||
| void tearDown() throws IOException { | ||
| server.close(); | ||
| } | ||
|
|
||
| @ParameterizedTest | ||
| @CsvSource({ | ||
| "false, , test-gateway-token", | ||
| "true, , test-gateway-token", | ||
| "false, test-api-key, ", | ||
| "true, test-api-key, ", | ||
| "false, test-api-key, test-gateway-token", | ||
| "true, test-api-key, test-gateway-token" | ||
| }) | ||
| void shouldSendConfiguredAuthenticationHeaders( | ||
| boolean streaming, String apiKey, String authToken) throws Exception { | ||
| AnthropicChatModel model = | ||
| AnthropicChatModel.builder() | ||
| .baseUrl(server.url("/anthropic/").toString()) | ||
| .apiKey(apiKey) | ||
| .authToken(authToken) | ||
| .modelName("claude-sonnet-4.5") | ||
| .stream(streaming) | ||
| .build(); | ||
|
|
||
| assertExchange(model, streaming, apiKey, authToken); | ||
| } | ||
|
|
||
| @Test | ||
| void shouldPreserveApiKeyAuthenticationWithExistingConstructor() throws Exception { | ||
| AnthropicChatModel model = | ||
| new AnthropicChatModel( | ||
| server.url("/anthropic/").toString(), | ||
| "test-api-key", | ||
| "claude-sonnet-4.5", | ||
| false, | ||
| null, | ||
| null, | ||
| null, | ||
| null); | ||
|
|
||
| assertExchange(model, false, "test-api-key", null); | ||
| } | ||
|
|
||
| private void assertExchange( | ||
| AnthropicChatModel model, boolean streaming, String apiKey, String authToken) | ||
| throws Exception { | ||
| server.enqueue( | ||
| new MockResponse() | ||
| .setHeader( | ||
| "Content-Type", | ||
| streaming ? "text/event-stream" : "application/json") | ||
| .setBody(streaming ? STREAM_RESPONSE : MESSAGE_RESPONSE)); | ||
|
|
||
| List<String> text = | ||
| model.stream( | ||
| List.of( | ||
| Msg.builder() | ||
| .role(MsgRole.USER) | ||
| .textContent("Hello") | ||
| .build()), | ||
| null, | ||
| null) | ||
| .flatMapIterable(ChatResponse::getContent) | ||
| .ofType(TextBlock.class) | ||
| .map(TextBlock::getText) | ||
| .collectList() | ||
| .block(Duration.ofSeconds(10)); | ||
|
|
||
| assertEquals(List.of("Hello"), text); | ||
| RecordedRequest request = server.takeRequest(1, TimeUnit.SECONDS); | ||
| assertNotNull(request); | ||
| assertEquals("POST", request.getMethod()); | ||
| assertEquals("/anthropic/v1/messages", request.getPath()); | ||
| assertEquals( | ||
| apiKey == null ? List.of() : List.of(apiKey), | ||
| request.getHeaders().values("X-Api-Key")); | ||
| assertEquals( | ||
| authToken == null ? List.of() : List.of("Bearer " + authToken), | ||
| request.getHeaders().values("Authorization")); | ||
| assertEquals(1, server.getRequestCount()); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The javadoc says that if both
apiKeyandauthTokenare set the SDK sends both headers, and the builder just forwards them. Silently sending two conflicting credentials is the kind of thing that produces a confusing 401 from the gateway; for an Anthropic-compatible proxy with a staticAuthorizationheader this is also a footgun in the Spring starter wiring. Consider rejecting the combination inbuild()(or ignoringapiKeywhenauthTokenis present and logging a warning) so the effective credential is unambiguous.