Skip to content

Commit 3334ba2

Browse files
authored
Bug/gpt response compact (#994)
* refactor question builder for gpt feature * removing logic that prepends all applied tags to question builder * passing first tag as context to gptservice * setting context before sending the question * refactoring setup message * improving context * refactoring context for more appropriate responses * get matching tag or default for context * sending instructions along with question, instead of setup * prompt for shorter responses * values responsible for tweaking AI responses are not declared as constants, docs are also added for such values
1 parent 2148821 commit 3334ba2

File tree

3 files changed

+46
-31
lines changed

3 files changed

+46
-31
lines changed

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,8 +74,9 @@ public void onSlashCommand(SlashCommandInteractionEvent event) {
7474
public void onModalSubmitted(ModalInteractionEvent event, List<String> args) {
7575
event.deferReply().queue();
7676

77+
String context = "";
7778
Optional<String[]> optional =
78-
chatGptService.ask(event.getValue(QUESTION_INPUT).getAsString());
79+
chatGptService.ask(event.getValue(QUESTION_INPUT).getAsString(), context);
7980
if (optional.isPresent()) {
8081
userIdToAskedAtCache.put(event.getMember().getId(), Instant.now());
8182
}

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

Lines changed: 39 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,30 @@
2121
public class ChatGptService {
2222
private static final Logger logger = LoggerFactory.getLogger(ChatGptService.class);
2323
private static final Duration TIMEOUT = Duration.ofSeconds(90);
24+
25+
/** The maximum number of tokens allowed for the generated answer. */
2426
private static final int MAX_TOKENS = 3_000;
27+
28+
/**
29+
* This parameter reduces the likelihood of the AI repeating itself. A higher frequency penalty
30+
* makes the model less likely to repeat the same lines verbatim. It helps in generating more
31+
* diverse and varied responses.
32+
*/
33+
private static final double FREQUENCY_PENALTY = 0.5;
34+
35+
/**
36+
* This parameter controls the randomness of the AI's responses. A higher temperature results in
37+
* more varied, unpredictable, and creative responses. Conversely, a lower temperature makes the
38+
* model's responses more deterministic and conservative.
39+
*/
40+
private static final double TEMPERATURE = 0.8;
41+
42+
/**
43+
* n: This parameter specifies the number of responses to generate for each prompt. If n is more
44+
* than 1, the AI will generate multiple different responses to the same prompt, each one being
45+
* a separate iteration based on the input.
46+
*/
47+
private static final int MAX_NUMBER_OF_RESPONSES = 1;
2548
private static final String AI_MODEL = "gpt-3.5-turbo";
2649

2750
private boolean isDisabled = false;
@@ -42,18 +65,16 @@ public ChatGptService(Config config) {
4265

4366
openAiService = new OpenAiService(apiKey, TIMEOUT);
4467

45-
ChatMessage setupMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(),
46-
"""
47-
Please answer questions in 1500 characters or less. Remember to count spaces in the
48-
character limit. For code supplied for review, refer to the old code supplied rather than
49-
rewriting the code. Don't supply a corrected version of the code.\s""");
68+
ChatMessage setupMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), """
69+
For code supplied for review, refer to the old code supplied rather than
70+
rewriting the code. DON'T supply a corrected version of the code.\s""");
5071
ChatCompletionRequest systemSetupRequest = ChatCompletionRequest.builder()
5172
.model(AI_MODEL)
5273
.messages(List.of(setupMessage))
53-
.frequencyPenalty(0.5)
54-
.temperature(0.3)
74+
.frequencyPenalty(FREQUENCY_PENALTY)
75+
.temperature(TEMPERATURE)
5576
.maxTokens(50)
56-
.n(1)
77+
.n(MAX_NUMBER_OF_RESPONSES)
5778
.build();
5879

5980
// Sending the system setup message to ChatGPT.
@@ -68,26 +89,29 @@ public ChatGptService(Config config) {
6889
* @see <a href="https://platform.openai.com/docs/guides/chat/managing-tokens">ChatGPT
6990
* Tokens</a>.
7091
*/
71-
public Optional<String[]> ask(String question) {
92+
public Optional<String[]> ask(String question, String context) {
7293
if (isDisabled) {
7394
return Optional.empty();
7495
}
7596

7697
try {
77-
ChatMessage chatMessage =
78-
new ChatMessage(ChatMessageRole.USER.value(), Objects.requireNonNull(question));
98+
String instructions = "KEEP IT CONCISE, NOT MORE THAN 280 WORDS";
99+
String questionWithContext = "context: Category %s on a Java Q&A discord server. %s %s"
100+
.formatted(context, instructions, question);
101+
ChatMessage chatMessage = new ChatMessage(ChatMessageRole.USER.value(),
102+
Objects.requireNonNull(questionWithContext));
79103
ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
80104
.model(AI_MODEL)
81105
.messages(List.of(chatMessage))
82-
.frequencyPenalty(0.5)
83-
.temperature(0.3)
106+
.frequencyPenalty(FREQUENCY_PENALTY)
107+
.temperature(TEMPERATURE)
84108
.maxTokens(MAX_TOKENS)
85-
.n(1)
109+
.n(MAX_NUMBER_OF_RESPONSES)
86110
.build();
87111

88112
String response = openAiService.createChatCompletion(chatCompletionRequest)
89113
.getChoices()
90-
.get(0)
114+
.getFirst()
91115
.getMessage()
92116
.getContent();
93117

application/src/main/java/org/togetherjava/tjbot/features/help/HelpSystemHelper.java

Lines changed: 5 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,11 @@ RestAction<Message> constructChatGptAttempt(ThreadChannel threadChannel,
125125
String question = questionOptional.get();
126126
logger.debug("The final question sent to chatGPT: {}", question);
127127

128-
chatGPTAnswer = chatGptService.ask(question);
128+
ForumTag defaultTag = threadChannel.getAppliedTags().getFirst();
129+
ForumTag matchingTag = getCategoryTagOfChannel(threadChannel).orElse(defaultTag);
130+
131+
String context = matchingTag.getName();
132+
chatGPTAnswer = chatGptService.ask(question, context);
129133
if (chatGPTAnswer.isEmpty()) {
130134
return useChatGptFallbackMessage(threadChannel);
131135
}
@@ -178,20 +182,6 @@ private Optional<String> prepareChatGptQuestion(ThreadChannel threadChannel,
178182
.min(MAX_QUESTION_LENGTH - questionBuilder.length(), originalQuestion.length()));
179183

180184
questionBuilder.append(originalQuestion);
181-
182-
StringBuilder tagBuilder = new StringBuilder();
183-
int stringLength = questionBuilder.length();
184-
for (ForumTag tag : threadChannel.getAppliedTags()) {
185-
String tagName = tag.getName();
186-
stringLength += tagName.length();
187-
if (stringLength > MAX_QUESTION_LENGTH) {
188-
break;
189-
}
190-
tagBuilder.append(String.format("%s ", tagName));
191-
}
192-
193-
questionBuilder.insert(0, tagBuilder);
194-
195185
return Optional.of(questionBuilder.toString());
196186
}
197187

0 commit comments

Comments
 (0)