Skip to content

Commit df0a823

Browse files
committed
wip: base code for gpt-formatter
1 parent 6c3cc81 commit df0a823

File tree

5 files changed

+92
-27
lines changed

5 files changed

+92
-27
lines changed

application/src/main/java/org/togetherjava/tjbot/features/Features.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,9 +88,9 @@ public static Collection<Feature> createFeatures(JDA jda, Database database, Con
8888
ModAuditLogWriter modAuditLogWriter = new ModAuditLogWriter(config);
8989
ScamHistoryStore scamHistoryStore = new ScamHistoryStore(database);
9090
GitHubReference githubReference = new GitHubReference(config);
91-
CodeMessageHandler codeMessageHandler =
92-
new CodeMessageHandler(blacklistConfig.special(), jshellEval);
9391
ChatGptService chatGptService = new ChatGptService(config);
92+
CodeMessageHandler codeMessageHandler =
93+
new CodeMessageHandler(blacklistConfig.special(), jshellEval, chatGptService);
9494
HelpSystemHelper helpSystemHelper = new HelpSystemHelper(config, database, chatGptService);
9595

9696
// NOTE The system can add special system relevant commands also by itself,
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package org.togetherjava.tjbot.features.basic;
2+
3+
import org.togetherjava.tjbot.features.chatgpt.ChatGptService;
4+
5+
import java.util.Optional;
6+
7+
public final class ChatGPTFormatter {
8+
private final ChatGptService chatGptService;
9+
10+
public ChatGPTFormatter(ChatGptService chatGptService) {
11+
this.chatGptService = chatGptService;
12+
}
13+
14+
public Optional<String> format(CharSequence code) {
15+
return chatGptService.formatCode(code);
16+
}
17+
}

application/src/main/java/org/togetherjava/tjbot/features/chatgpt/ChatGptService.java

Lines changed: 59 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -100,28 +100,8 @@ public Optional<String> ask(String question, String context) {
100100
String instructions = "KEEP IT CONCISE, NOT MORE THAN 280 WORDS";
101101
String questionWithContext = "context: Category %s on a Java Q&A discord server. %s %s"
102102
.formatted(context, instructions, question);
103-
ChatMessage chatMessage = new ChatMessage(ChatMessageRole.USER.value(),
104-
Objects.requireNonNull(questionWithContext));
105-
ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
106-
.model(AI_MODEL)
107-
.messages(List.of(chatMessage))
108-
.frequencyPenalty(FREQUENCY_PENALTY)
109-
.temperature(TEMPERATURE)
110-
.maxTokens(MAX_TOKENS)
111-
.n(MAX_NUMBER_OF_RESPONSES)
112-
.build();
113-
114-
String response = openAiService.createChatCompletion(chatCompletionRequest)
115-
.getChoices()
116-
.getFirst()
117-
.getMessage()
118-
.getContent();
119-
120-
if (response == null) {
121-
return Optional.empty();
122-
}
123-
124-
return Optional.of(response);
103+
104+
return getMessageResponse(questionWithContext);
125105
} catch (OpenAiHttpException openAiHttpException) {
126106
logger.warn(
127107
"There was an error using the OpenAI API: {} Code: {} Type: {} Status Code: {}",
@@ -133,4 +113,61 @@ public Optional<String> ask(String question, String context) {
133113
}
134114
return Optional.empty();
135115
}
116+
117+
public Optional<String> formatCode(CharSequence code) {
118+
if (isDisabled) {
119+
return Optional.empty();
120+
}
121+
122+
String payload = String.format(
123+
"""
124+
If you happen to find any code in the container below, FORMAT \
125+
IT regardless of the programming language you find. MAKE IT HUMANLY READABLE. \
126+
If you don't find any, then your only answer should say empty. Output with no \
127+
introduction, no explanation, no ``` stuff, only code. Double check that \
128+
your response is correct. The code provided might not be readable.
129+
130+
--- BEGIN CODE ---
131+
%s
132+
--- END CODE ---
133+
""",
134+
code);
135+
Optional<String> response = getMessageResponse(payload);
136+
137+
if (response.isEmpty() || response.get().equalsIgnoreCase("empty")) {
138+
return Optional.empty();
139+
}
140+
141+
return response;
142+
}
143+
144+
private Optional<String> getMessageResponse(String message) {
145+
ChatMessage chatMessage =
146+
new ChatMessage(ChatMessageRole.USER.value(), Objects.requireNonNull(message));
147+
ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
148+
.model(AI_MODEL)
149+
.messages(List.of(chatMessage))
150+
.frequencyPenalty(FREQUENCY_PENALTY)
151+
.temperature(TEMPERATURE)
152+
.maxTokens(MAX_TOKENS)
153+
.n(MAX_NUMBER_OF_RESPONSES)
154+
.build();
155+
156+
logger.debug("GPT tx payload: {}", message);
157+
158+
String response = openAiService.createChatCompletion(chatCompletionRequest)
159+
.getChoices()
160+
.getFirst()
161+
.getMessage()
162+
.getContent();
163+
164+
if (response == null) {
165+
logger.debug("Got empty response");
166+
return Optional.empty();
167+
}
168+
169+
logger.debug("GPT rx: {}", response);
170+
171+
return Optional.of(response);
172+
}
136173
}

application/src/main/java/org/togetherjava/tjbot/features/code/CodeMessageHandler.java

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import org.togetherjava.tjbot.features.MessageReceiverAdapter;
1818
import org.togetherjava.tjbot.features.UserInteractionType;
1919
import org.togetherjava.tjbot.features.UserInteractor;
20+
import org.togetherjava.tjbot.features.chatgpt.ChatGptService;
2021
import org.togetherjava.tjbot.features.componentids.ComponentIdGenerator;
2122
import org.togetherjava.tjbot.features.componentids.ComponentIdInteractor;
2223
import org.togetherjava.tjbot.features.jshell.JShellEval;
@@ -49,6 +50,7 @@ public final class CodeMessageHandler extends MessageReceiverAdapter implements
4950

5051
private final ComponentIdInteractor componentIdInteractor;
5152
private final Map<String, CodeAction> labelToCodeAction;
53+
private final ChatGptService chatGptService;
5254

5355
/**
5456
* Memorizes the ID of the bots code-reply message that a message belongs to. That way, the
@@ -68,11 +70,13 @@ public final class CodeMessageHandler extends MessageReceiverAdapter implements
6870
* disabled
6971
* @param jshellEval used to execute java code and build visual result
7072
*/
71-
public CodeMessageHandler(FeatureBlacklist<String> blacklist, JShellEval jshellEval) {
73+
public CodeMessageHandler(FeatureBlacklist<String> blacklist, JShellEval jshellEval,
74+
ChatGptService chatGptService) {
7275
componentIdInteractor = new ComponentIdInteractor(getInteractionType(), getName());
76+
this.chatGptService = chatGptService;
7377

7478
List<CodeAction> codeActions = blacklist
75-
.filterStream(Stream.of(new FormatCodeCommand(), new EvalCodeCommand(jshellEval)),
79+
.filterStream(Stream.of(new FormatCodeCommand(chatGptService), new EvalCodeCommand(jshellEval)),
7680
codeAction -> codeAction.getClass().getName())
7781
.toList();
7882

application/src/main/java/org/togetherjava/tjbot/features/code/FormatCodeCommand.java

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import net.dv8tion.jda.api.EmbedBuilder;
44
import net.dv8tion.jda.api.entities.MessageEmbed;
55

6+
import org.togetherjava.tjbot.features.basic.ChatGPTFormatter;
7+
import org.togetherjava.tjbot.features.chatgpt.ChatGptService;
68
import org.togetherjava.tjbot.features.utils.CodeFence;
79
import org.togetherjava.tjbot.formatter.Formatter;
810

@@ -13,6 +15,11 @@
1315
*/
1416
final class FormatCodeCommand implements CodeAction {
1517
private final Formatter formatter = new Formatter();
18+
private final ChatGPTFormatter chatGPTFormatter;
19+
20+
public FormatCodeCommand(ChatGptService service) {
21+
this.chatGPTFormatter = new ChatGPTFormatter(service);
22+
}
1623

1724
@Override
1825
public String getLabel() {
@@ -34,6 +41,6 @@ public MessageEmbed apply(CodeFence codeFence) {
3441
}
3542

3643
private String formatCode(CharSequence code) {
37-
return formatter.format(code);
44+
return chatGPTFormatter.format(code).orElse(formatter.format(code));
3845
}
3946
}

0 commit comments

Comments
 (0)