Skip to content

Fix NPE in AnthropicApi StreamHelper #3755

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

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.ai.anthropic.api.AnthropicApi.ChatCompletionResponse;
import org.springframework.ai.anthropic.api.AnthropicApi.ContentBlock;
import org.springframework.ai.anthropic.api.AnthropicApi.ContentBlock.Type;
Expand Down Expand Up @@ -56,6 +59,8 @@
*/
public class StreamHelper {

private static final Logger logger = LoggerFactory.getLogger(StreamHelper.class);

public boolean isToolUseStart(StreamEvent event) {
if (event == null || event.type() == null || event.type() != EventType.CONTENT_BLOCK_START) {
return false;
Expand Down Expand Up @@ -216,7 +221,11 @@ else if (event.type().equals(EventType.MESSAGE_STOP)) {
}
else {
// Any other event types that should propagate upwards without content
if (contentBlockReference.get() == null) {
contentBlockReference.set(new ChatCompletionResponseBuilder());
}
contentBlockReference.get().withType(event.type().name()).withContent(List.of());
logger.warn("Unhandled event type: {}", event.type().name());
}

return contentBlockReference.get().build();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package org.springframework.ai.anthropic.api;

import java.util.concurrent.atomic.AtomicReference;

import org.junit.jupiter.api.Test;

import org.springframework.ai.anthropic.api.StreamHelper.ChatCompletionResponseBuilder;

import static org.assertj.core.api.Assertions.assertThat;

/**
* @author Ilayaperumal Gopinathan
*/
class StreamHelperTest {

@Test
void testErrorEventTypeWithEmptyContentBlock() {
AnthropicApi.ErrorEvent errorEvent = new AnthropicApi.ErrorEvent(AnthropicApi.EventType.ERROR,
new AnthropicApi.ErrorEvent.Error("error", "error message"));
AtomicReference<ChatCompletionResponseBuilder> contentBlockReference = new AtomicReference<>();
StreamHelper streamHelper = new StreamHelper();
AnthropicApi.ChatCompletionResponse response = streamHelper.eventToChatCompletionResponse(errorEvent,
contentBlockReference);
assertThat(response).isNotNull();
}

}