2
2
3
3
import io .github .kezhenxu94 .chatgpt .ChatGPT ;
4
4
import io .github .kezhenxu94 .chatgpt .Conversation ;
5
+ import io .github .kezhenxu94 .chatgpt .message .Message ;
6
+ import io .github .kezhenxu94 .chatgpt .message .Role ;
7
+ import org .springframework .shell .Availability ;
5
8
import org .springframework .shell .standard .ShellComponent ;
6
9
import org .springframework .shell .standard .ShellMethod ;
10
+ import org .springframework .shell .standard .ShellMethodAvailability ;
7
11
8
12
@ ShellComponent
9
13
public class ConversationCommands {
@@ -15,13 +19,26 @@ public ConversationCommands(ChatGPT chatGPT) {
15
19
this .chatGPT = chatGPT ;
16
20
}
17
21
18
- @ ShellMethod ("Load a conversation by ID" )
22
+ @ ShellMethod (
23
+ "Set the system message as an instruction to guide the ChatGPT in following conversations" )
24
+ @ ShellMethodAvailability ("isConversationNull" )
25
+ public String system (String system ) {
26
+ if (conversation == null ) {
27
+ conversation = chatGPT .newConversation (system );
28
+ } else if (conversation .messages ().stream ().allMatch (it -> it .role () != Role .SYSTEM )) {
29
+ conversation .messages ().add (0 , Message .ofSystem (system ));
30
+ }
31
+ return "System message set to: " + system ;
32
+ }
33
+
34
+ @ ShellMethod (
35
+ "Load a conversation by ID, if there is no conversation with the ID, a new one will be created with the ID" )
19
36
public String load (String id ) throws Exception {
20
37
conversation = chatGPT .loadConversation (id );
21
38
return "You are now at conversation: " + id ;
22
39
}
23
40
24
- @ ShellMethod ("Ask a question" )
41
+ @ ShellMethod ("Ask a question in the current conversation " )
25
42
public String ask (String question ) throws Exception {
26
43
if (conversation == null ) {
27
44
conversation = chatGPT .newConversation ();
@@ -30,4 +47,12 @@ public String ask(String question) throws Exception {
30
47
final var answer = conversation .ask (question );
31
48
return answer .content ().trim ();
32
49
}
50
+
51
+ Availability isConversationNull () {
52
+ return conversation == null
53
+ || conversation .messages ().stream ().allMatch (it -> it .role () != Role .SYSTEM )
54
+ ? Availability .available ()
55
+ : Availability .unavailable (
56
+ "you are already in a conversation, system message can only be set in new conversation." );
57
+ }
33
58
}
0 commit comments