Skip to content

Commit

Permalink
Merge pull request #314 from Broscorp-net/spring-ai-integration
Browse files Browse the repository at this point in the history
Integrated spring ai
  • Loading branch information
Vlad-Ukr authored Feb 5, 2024
2 parents 6710c5e + 2c09a04 commit aa4ec44
Show file tree
Hide file tree
Showing 8 changed files with 51 additions and 91 deletions.
17 changes: 16 additions & 1 deletion bot/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -170,15 +170,30 @@
<artifactId>spring-plugin-core</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
<version>0.8.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.community-tools</groupId>
<artifactId>message-service</artifactId>
<version>2-SNAPSHOT</version>
<scope>compile</scope>
</dependency>

</dependencies>

<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>

<build>
<plugins>
<plugin>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
import java.time.LocalDate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.statemachine.StateMachine;
import org.springframework.stereotype.Service;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ public class RegisterCommand extends Command {
private String newbieRoleName;

public RegisterCommand(CommandData commandData,
GitHubService gitHubService,
UserRepository userRepository,
@Lazy MessageService<?> messageService,
OptionData... options) {
GitHubService gitHubService,
UserRepository userRepository,
@Lazy MessageService<?> messageService,
OptionData... options) {
super(commandData, options);
this.gitHubService = gitHubService;
this.userRepository = userRepository;
Expand All @@ -44,15 +44,15 @@ public RegisterCommand(CommandData commandData,
/**
* Basic constructor for the class, specifies command data and injects required beans.
*
* @param gitHubService checks if provided username is correct
* @param gitHubService checks if provided username is correct
* @param userRepository repository for access to user's entity
* @param messageService messaging in discord
*/
public RegisterCommand(GitHubService gitHubService,
UserRepository userRepository,
MessageService<?> messageService) {
UserRepository userRepository,
MessageService<?> messageService) {
super(new CommandData("register", "Saves your GitHub username"),
new OptionData(OptionType.STRING, "username", "Your GitHub username"));
new OptionData(OptionType.STRING, "username", "Your GitHub username"));
this.gitHubService = gitHubService;
this.userRepository = userRepository;
this.messageService = messageService;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,17 @@ public class DiscordGitHubMappingService {
private final UserRepository userRepository;

/**
* Searches for users within provided GitHub usernames
* and returns map of GitHub-Discord usernames.
* Searches for users within provided GitHub usernames and returns map of GitHub-Discord
* usernames.
*
* @param githubUsernames List of GitHub usernames
*
* @return Map of GitHub-Discord usernames
*/
public Map<String, String> getDiscordGithubUsernames(List<String> githubUsernames) {
return userRepository.findByGitNameIn(githubUsernames).stream()
.collect(Collectors.toMap(User::getGitName, u -> Objects.requireNonNull(
messageService.retrieveById(u.getUserId()))));
.collect(Collectors.toMap(User::getGitName, u -> Objects.requireNonNull(
messageService.retrieveById(u.getUserId()))));
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,82 +1,26 @@
package com.community.tools.service.openai;

import com.community.tools.dto.OpenAiRequestDto;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.ai.chat.ChatClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class OpenAiService {
@Value("${openai.url}")
private String url;
@Value("${openai.token}")
private String apiKey;
@Value("${openai.model}")
private String model;
@Value("${openai.temperature}")
private double temperature;

/**
* This is the main method in service which processes prompt.
*
* @param prompt users request to the openai api
* @return ready-to-use string response from AI
*/
public String processPrompt(String prompt) {
try {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(apiKey);
headers.setContentType(MediaType.APPLICATION_JSON);

OpenAiRequestDto requestDto = new OpenAiRequestDto(model, prompt, temperature);

RequestEntity<OpenAiRequestDto> requestEntity =
new RequestEntity<>(requestDto, headers, HttpMethod.POST, URI.create(url));
private final ChatClient chatClient;

ResponseEntity<String> responseEntity = restTemplate.exchange(requestEntity, String.class);

String jsonResponse = responseEntity.getBody();
String raw = extractMessageFromJsonResponse(jsonResponse);
return getStringWithLineSeparators(raw);
} catch (IOException e) {
throw new UncheckedIOException("Failed to communicate with OpenAI service", e);
}
public OpenAiService(ChatClient chatClient) {
this.chatClient = chatClient;
}

/**
* This private method formatting string form json-looking to normal.
* Processes the user's request by sending a prompt to the OpenAI API through the ChatClient.
*
* @param response json string
* @return raw string, example: "This is example list//n1)...//n..."
*/
private String extractMessageFromJsonResponse(String response) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(response);
return jsonNode
.get("choices").get(0)
.get("message").get("content").asText();
}

/**
* This private method replaces //n to /n in string.
* @param prompt The user's request to be sent to the OpenAI API.
* @return A string response generated by the AI, ready for use.
*
* @param raw raw string with //n
* @return ready-to-use string
* @see ChatClient#call(String) The underlying method responsible for making the API call.
*/
private String getStringWithLineSeparators(String raw) {
final String regex = "\\\\n";
final String newSeparator = System.lineSeparator();
return raw.replaceAll(regex, newSeparator);
public String processPrompt(String prompt) {
return chatClient.call(prompt);
}
}
10 changes: 6 additions & 4 deletions bot/src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,12 @@ email.login=Bro.Bot.email@gmail.com
email.password=Broscorp123Com
email.notification.enabled=false

openai.token=${OPEN_AI_TOKEN}
openai.url=https://api.openai.com/v1/chat/completions
openai.model=gpt-3.5-turbo
openai.temperature=0.1

spring.ai.openai.api-key=${OPEN_AI_TOKEN}
spring.ai.openai.chat.options.temperature=0.1
spring.ai.openai.chat.options.model=gpt-3.5-turbo
spring.ai.openai.chat.options.response-format=text


#notification
text.channel=notifications
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ public JDA jda() {
.map(Command::getCommandData)
.collect(Collectors.toList());
jda.updateCommands()
.addCommands(commandData)
.queue();
.addCommands(commandData)
.queue();
jda.awaitReady();
return jda;
} catch (LoginException | InterruptedException exception) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
@Data
@Profile("discord")
public class DiscordService implements MessageService<MessageEmbed> {

private final Button buttonWithEmbed = Button.primary("buttonEmbed", "Button");
private JDA jda;
private DiscordMessagingService discordMessagingService;
Expand Down Expand Up @@ -177,8 +178,8 @@ public String getIdByChannelName(String channelName) {
/**
* Adds a role to a user within a guild.
*
* @param guildId id of a guild
* @param userId id of a user
* @param guildId id of a guild
* @param userId id of a user
* @param roleName role's name
*/
@Override
Expand All @@ -192,8 +193,8 @@ public void addRoleToUser(String guildId, String userId, String roleName) {
/**
* Removes a role from a user within a guild.
*
* @param guildId id of a guild
* @param userId id of a user
* @param guildId id of a guild
* @param userId id of a user
* @param roleName role's name
*/
@Override
Expand All @@ -208,7 +209,6 @@ public void removeRole(String guildId, String userId, String roleName) {
* Calls JDA and retrieves user's name by id.
*
* @param userId id of a user
*
* @return user's discord name
*/
@Override
Expand Down

0 comments on commit aa4ec44

Please sign in to comment.