Home >Java >javaTutorial >Communicating JAVA with GeminiAI
If you program in Java and have never 'played' with GeminiAI, this article will be a great introductory guide, here I will present in a very simple way how to send requests to Gemini and return JSON, like a Rest API. ??
What am I using? ?
Start a simple project using the spring launcher, and include the following dependencies in your POM
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.36</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.18.2</version> </dependency>
These dependencies will enable the use of Lombok, RestTemplate and ObjectMapper.
Lombok: to avoid repetitive codes (famous boilerplates) and to improve the readability of our code
RestTemplate: to make the http request to the GeminiAI API
ObjectMapper: to convert the Gemini api return into JSON
Let's configure the RestTemplate in our Java project, for this we create a class with the @Configuration annotation and the Bean to define it:
@Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } }
Let's create a service class to communicate with GeminiAI, this class will be responsible for all communication and processing of Gemini's response, and should look like this:
@Service public class TalkService { private final RestTemplate restTemplate; private final ObjectMapper objectMapper; @Value("${gemini.ai.api.url}") private String geminiApiUrl; @Value("${gemini.ai.api.key}") private String geminiApiKey; public TalkService(RestTemplate restTemplate, ObjectMapper objectMapper) { this.restTemplate = restTemplate; this.objectMapper = objectMapper; } public String callGeminiAI(TalkRequest input) { String url = geminiApiUrl + geminiApiKey; GeminiRequest request = new GeminiRequest(); GeminiRequest.Content content = new GeminiRequest.Content(); GeminiRequest.Part part = new GeminiRequest.Part(); part.setText(input.getChat()); content.setParts(Collections.singletonList(part)); request.setContents(Collections.singletonList(content)); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<GeminiRequest> entity = new HttpEntity<>(request, headers); ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class); try { GeminiResponse geminiAIResponse = objectMapper.readValue(response.getBody(), GeminiResponse.class); if (geminiAIResponse.getCandidates() != null && !geminiAIResponse.getCandidates().isEmpty()) { GeminiResponse.Candidate candidate = geminiAIResponse.getCandidates().get(0); if (candidate.getContent() != null && candidate.getContent().getParts() != null && !candidate.getContent().getParts().isEmpty()) { return candidate.getContent().getParts().get(0).getText(); } } } catch (Exception e) { e.printStackTrace(); } return "Falha ao processar resposta da API"; } }
Note that in this class we are using the POJO's GeminiRequest and GeminiResponse, below is the code to create them
GeminiRequest
@Getter @Setter @AllArgsConstructor @NoArgsConstructor public class GeminiRequest { private List<Content> contents; @Getter @Setter @AllArgsConstructor @NoArgsConstructor public static class Content { private List<Part> parts; } @Getter @Setter @AllArgsConstructor @NoArgsConstructor public static class Part { private String text; } }
GeminiResponse
@Getter @Setter @AllArgsConstructor @NoArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class GeminiResponse { private List<Candidate> candidates; private UsageMetadata usageMetadata; private String modelVersion; @Getter @Setter @AllArgsConstructor @NoArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public static class Candidate { private Content content; private String finishReason; private double avgLogprobs; } @Getter @Setter @AllArgsConstructor @NoArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public static class Content { private List<Part> parts; } @Getter @Setter @AllArgsConstructor @NoArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public static class Part { private String text; } @Getter @Setter @AllArgsConstructor @NoArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public static class UsageMetadata { private int promptTokenCount; private int candidatesTokenCount; private int totalTokenCount; } }
Now let's create a controller to listen to a Rest request and process it through our Service
@RestController @RequestMapping("v1") public class TalkController { private final TalkService talkService; @Autowired public TalkController(final TalkService talkService) { this.talkService = talkService; } @PostMapping("/chat-gemini") public TalkResponse talk(@RequestBody TalkRequest talkRequest) { TalkResponse response = new TalkResponse(); response.setResponse(talkService.callGeminiAI(talkRequest)); return response; } }
Our controller also has POJO's, check out their code below
TalkRequest
@Getter @Setter @AllArgsConstructor public class TalkRequest { private String chat; }
TalkResponse
@Getter @Setter @AllArgsConstructor @NoArgsConstructor public class TalkResponse { private String response; }
You will need to inform the GeminiAI access endpoint and also your access key. I stored this information in the properties file, since we are talking about a simple test. Check the properties file with the necessary variables
spring.application.name=NOME_DA_SUA_APLICACAO gemini.ai.api.url=https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key= gemini.ai.api.key=SUA_CHAVE_DE_ACESSO
We already have communication with GeminiAI, now we can test our application using postman, to do this start your application in Intellij and execute the request in postman as shown in the image below:
CONCLUSION ✔
The purpose of this article was to introduce Java programmers to connecting GeminiAI with a Java application, creating infinite new possibilities for use. I hope you enjoyed it, see you next time! ?
The above is the detailed content of Communicating JAVA with GeminiAI. For more information, please follow other related articles on the PHP Chinese website!