Skip to content

Commit 34926aa

Browse files
committed
Fix issue with using unsubscribed response body in exception message
Signed-off-by: jitokim <[email protected]>
1 parent 5e1f681 commit 34926aa

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

models/spring-ai-anthropic/src/main/java/org/springframework/ai/anthropic/api/AnthropicApi.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151
* @author Christian Tzolov
5252
* @author Mariusz Bernacki
5353
* @author Thomas Vitale
54+
* @author Jihoon Kim
5455
* @since 1.0.0
5556
*/
5657
public class AnthropicApi {
@@ -138,8 +139,9 @@ public AnthropicApi(String baseUrl, String anthropicApiKey, String anthropicVers
138139
this.webClient = webClientBuilder.baseUrl(baseUrl)
139140
.defaultHeaders(jsonContentHeaders)
140141
.defaultStatusHandler(HttpStatusCode::isError,
141-
resp -> Mono.just(new RuntimeException("Response exception, Status: [" + resp.statusCode()
142-
+ "], Body:[" + resp.bodyToMono(java.lang.String.class) + "]")))
142+
resp -> resp.bodyToMono(String.class)
143+
.flatMap(it -> Mono.error(new RuntimeException(
144+
"Response exception, Status: [" + resp.statusCode() + "], Body:[" + it + "]"))))
143145
.build();
144146
}
145147

models/spring-ai-anthropic/src/test/java/org/springframework/ai/anthropic/api/AnthropicApiIT.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,11 @@
3030
import org.springframework.http.ResponseEntity;
3131

3232
import static org.assertj.core.api.Assertions.assertThat;
33+
import static org.assertj.core.api.Assertions.assertThatThrownBy;
3334

3435
/**
3536
* @author Christian Tzolov
37+
* @author Jihoon Kim
3638
*/
3739
@EnabledIfEnvironmentVariable(named = "ANTHROPIC_API_KEY", matches = ".+")
3840
public class AnthropicApiIT {
@@ -70,4 +72,19 @@ void chatCompletionStream() {
7072
bla.stream().forEach(r -> System.out.println(r));
7173
}
7274

75+
@Test
76+
void chatCompletionStreamError() {
77+
AnthropicMessage chatCompletionMessage = new AnthropicMessage(List.of(new ContentBlock("Tell me a Joke?")),
78+
Role.USER);
79+
AnthropicApi api = new AnthropicApi("FAKE_KEY_FOR_ERROR_RESPONSE");
80+
81+
Flux<ChatCompletionResponse> response = api.chatCompletionStream(new ChatCompletionRequest(
82+
AnthropicApi.ChatModel.CLAUDE_3_OPUS.getValue(), List.of(chatCompletionMessage), null, 100, 0.8, true));
83+
84+
assertThat(response).isNotNull();
85+
86+
assertThatThrownBy(() -> response.collectList().block()).isInstanceOf(RuntimeException.class)
87+
.hasMessageStartingWith("Response exception, Status: [");
88+
}
89+
7390
}

0 commit comments

Comments
 (0)