Skip to content

Commit

Permalink
refact
Browse files Browse the repository at this point in the history
  • Loading branch information
PlexPt committed Jul 4, 2024
1 parent 4d829e5 commit 6b3d47d
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 13 deletions.
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,7 @@ implementation group: 'com.github.plexpt', name: 'chatgpt', version: '4.4.0'
.temperature(0.9)
.build();
ChatCompletionResponse response = chatGPT.chatCompletion(chatCompletion);
Message res = response.getChoices().get(0).getMessage();
System.out.println(res);
System.out.println(response.toPlainString());

```
### 函数调用(Function Call)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
import com.fasterxml.jackson.annotation.JsonProperty;
import com.plexpt.chatgpt.entity.billing.Usage;
import lombok.Data;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;

/**
* chat答案类
Expand All @@ -25,4 +27,31 @@ public class ChatCompletionResponse {
private Usage usage;
Object logprobs;


public String toPlainString() {
if (CollectionUtils.isEmpty(this.getChoices())) {
return "";
}


return Optional.ofNullable(this.getChoices())
.map(e -> e.get(0))
.map(ChatChoice::getMessage)
.map(Message::getContent)
.orElse("");
}

public String toPlainStringStream() {
if (CollectionUtils.isEmpty(this.getChoices())) {
return "";
}


return Optional.ofNullable(this.getChoices())
.map(e -> e.get(0))
.map(ChatChoice::getDelta)
.map(Message::getContent)
.orElse("");
}

}
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package com.plexpt.chatgpt.listener;

import com.plexpt.chatgpt.entity.chat.ChatChoice;
import com.plexpt.chatgpt.entity.chat.ChatCompletionResponse;
import com.plexpt.chatgpt.entity.chat.Message;
import com.plexpt.chatgpt.util.fastjson.JSON;
import lombok.Getter;
import lombok.Setter;
Expand All @@ -11,8 +9,8 @@
import okhttp3.Response;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;

Expand Down Expand Up @@ -73,15 +71,11 @@ public void onEvent(EventSource eventSource, String id, String type, String data
}

ChatCompletionResponse response = JSON.parseObject(data, ChatCompletionResponse.class);
// 读取Json
List<ChatChoice> choices = response.getChoices();
if (choices == null || choices.isEmpty()) {
return;
}
Message delta = choices.get(0).getDelta();
String text = delta.getContent();

if (text != null) {
String text = response.toPlainStringStream();

if (!StringUtils.isEmpty(text)) {

lastMessage += text;

onMsg(text);
Expand Down

0 comments on commit 6b3d47d

Please sign in to comment.