Skip to content

Commit 27354cd

Browse files
committed
Fix possible npes in openai response processing
1 parent 78cd3e9 commit 27354cd

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

models/spring-ai-openai/src/main/java/org/springframework/ai/openai/OpenAiChatModel.java

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
import org.springframework.ai.chat.messages.UserMessage;
3232
import org.springframework.ai.chat.metadata.ChatGenerationMetadata;
3333
import org.springframework.ai.chat.metadata.ChatResponseMetadata;
34+
import org.springframework.ai.chat.metadata.EmptyUsage;
3435
import org.springframework.ai.chat.metadata.RateLimit;
3536
import org.springframework.ai.chat.model.AbstractToolCallSupport;
3637
import org.springframework.ai.chat.model.ChatModel;
@@ -163,7 +164,7 @@ public ChatResponse call(Prompt prompt) {
163164
List<Generation> generations = choices.stream().map(choice -> {
164165
// @formatter:off
165166
Map<String, Object> metadata = Map.of(
166-
"id", chatCompletion.id(),
167+
"id", chatCompletion.id() != null ? chatCompletion.id() : "",
167168
"role", choice.message().role() != null ? choice.message().role().name() : "",
168169
"finishReason", choice.finishReason() != null ? choice.finishReason().name() : "");
169170
// @formatter:on
@@ -265,12 +266,12 @@ private Generation buildGeneration(Choice choice, Map<String, Object> metadata)
265266
private ChatResponseMetadata from(OpenAiApi.ChatCompletion result, RateLimit rateLimit) {
266267
Assert.notNull(result, "OpenAI ChatCompletionResult must not be null");
267268
var builder = ChatResponseMetadata.builder()
268-
.withId(result.id())
269-
.withUsage(OpenAiUsage.from(result.usage()))
270-
.withModel(result.model())
269+
.withId(result.id() != null ? result.id() : "")
270+
.withUsage(result.usage() != null ? OpenAiUsage.from(result.usage()) : new EmptyUsage())
271+
.withModel(result.model() != null ? result.model() : "")
271272
.withRateLimit(rateLimit)
272-
.withKeyValue("created", result.created())
273-
.withKeyValue("system-fingerprint", result.systemFingerprint());
273+
.withKeyValue("created", result.created() != null ? result.created() : 0L)
274+
.withKeyValue("system-fingerprint", result.systemFingerprint() != null ? result.systemFingerprint() : "");
274275
if (rateLimit != null) {
275276
builder.withRateLimit(rateLimit);
276277
}

0 commit comments

Comments
 (0)