Home Java javaTutorial Communicating JAVA with GeminiAI

Communicating JAVA with GeminiAI

Jan 09, 2025 am 06:45 AM

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>
Copy after login

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();
    }
}
Copy after login

 

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";
    }
}
Copy after login

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;
    }
}
Copy after login

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;
    }
}
Copy after login

 

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;
    }
}
Copy after login

Our controller also has POJO's, check out their code below

TalkRequest

@Getter
@Setter
@AllArgsConstructor
public class TalkRequest {
    private String chat;
}
Copy after login

TalkResponse

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class TalkResponse {
    private String response;
}

Copy after login

 

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
Copy after login

 

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:

Comunicando JAVA com o GeminiAI


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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

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. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

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...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

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...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

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

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

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...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

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...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

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...

See all articles