Skip to content
Open
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 @@ -524,6 +524,9 @@ private List<Part> toParts(AiMessage aiMessage) {
});
return parts;
} else {
if (aiMessage.text() == null) {
return List.of();
}
Part part = Part.builder().text(aiMessage.text()).build();
return List.of(part);
Comment on lines +527 to 531
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

While the logic is correct, this block can be made slightly more efficient and readable by avoiding the repeated call to aiMessage.text(). Storing the result in a local variable first makes the code cleaner and more concise.

Suggested change
if (aiMessage.text() == null) {
return List.of();
}
Part part = Part.builder().text(aiMessage.text()).build();
return List.of(part);
String text = aiMessage.text();
if (text == null) {
return List.of();
}
return List.of(Part.builder().text(text).build());

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -688,4 +688,28 @@ void testGenerateContentWithStructuredResponseJsonSchema() {
final UserMessage userMessage = (UserMessage) capturedRequest.messages().get(0);
assertThat(userMessage.singleText()).isEqualTo("Give me information about John Doe");
}

@Test
@DisplayName("Should handle null AiMessage text without throwing NPE")
void testGenerateContentWithNullAiMessageText() {
// Given
final LlmRequest llmRequest =
LlmRequest.builder().contents(List.of(Content.fromParts(Part.fromText("Hello")))).build();

final ChatResponse chatResponse = mock(ChatResponse.class);
final AiMessage aiMessage = mock(AiMessage.class);
when(aiMessage.text()).thenReturn(null);
when(aiMessage.hasToolExecutionRequests()).thenReturn(false);
when(chatResponse.aiMessage()).thenReturn(aiMessage);
when(chatModel.chat(any(ChatRequest.class))).thenReturn(chatResponse);

// When
final Flowable<LlmResponse> responseFlowable = langChain4j.generateContent(llmRequest, false);
final LlmResponse response = responseFlowable.blockingFirst();

// Then - no NPE thrown, and content has no text parts
assertThat(response).isNotNull();
assertThat(response.content()).isPresent();
assertThat(response.content().get().parts().orElse(List.of())).isEmpty();
}
}