Skip to content

Commit de82979

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

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

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

Lines changed: 7 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,12 @@ 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).flatMap(
143+
it -> Mono.error(
144+
new RuntimeException("Response exception, Status: [" + resp.statusCode() + "], Body:[" + it + "]")
145+
)
146+
)
147+
)
143148
.build();
144149
}
145150

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

Lines changed: 18 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,20 @@ 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())
87+
.isInstanceOf(RuntimeException.class)
88+
.hasMessageStartingWith("Response exception, Status: [");
89+
}
90+
7391
}

0 commit comments

Comments
 (0)