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? ?
- Java 17
- Intelligence Community 2024.1.1
- Postman Card
- GeminiAI access key
LET'S START?
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
CONFIGURING THE RESTTEMPLATE
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(); } }
CREATING THE SERVICE
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; } }
CREATING A CONTROLLER
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; }
CONFIGURING VARIABLES IN PROPERTIES
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
LET'S TEST IT??
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Start Spring using IntelliJIDEAUltimate version...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...
