如果你用 Java 编程并且从未“玩过”GeminiAI,那么这篇文章将是一个很好的入门指南,在这里我将以一种非常简单的方式展示如何向 Gemini 发送请求并返回 JSON,就像 Rest API 一样。 ??
我在用什么? ?
使用 spring 启动器启动一个简单的项目,并在 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>
这些依赖项将支持使用 Lombok、RestTemplate 和 ObjectMapper。
Lombok:避免重复代码(著名的样板)并提高代码的可读性
RestTemplate:向 GeminiAI API 发出 http 请求
ObjectMapper:将 Gemini api 返回转换为 JSON
让我们在 Java 项目中配置 RestTemplate,为此我们创建一个带有 @Configuration 注解的类并使用 Bean 来定义它:
@Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } }
让我们创建一个服务类来与 GeminiAI 进行通信,该类将负责 Gemini 响应的所有通信和处理,并且应该如下所示:
@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"; } }
请注意,在这个类中我们使用了 POJO 的 GeminiRequest 和 GeminiResponse,下面是创建它们的代码
Gemini请求
@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; } }
现在让我们创建一个控制器来监听 Rest 请求并通过我们的 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; } }
我们的控制器也有 POJO,请查看下面的代码
谈话请求
@Getter @Setter @AllArgsConstructor public class TalkRequest { private String chat; }
TalkResponse
@Getter @Setter @AllArgsConstructor @NoArgsConstructor public class TalkResponse { private String response; }
您需要告知GeminiAI访问端点以及您的访问密钥。我将此信息存储在属性文件中,因为我们正在讨论一个简单的测试。使用必要的变量检查属性文件
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
我们已经与 GeminiAI 进行了通信,现在我们可以使用 postman 测试我们的应用程序,为此,在 Intellij 中启动您的应用程序并在 postman 中执行请求,如下图所示:
结论 ✔
本文的目的是向 Java 程序员介绍如何将 GeminiAI 与 Java 应用程序连接起来,创造无限新的使用可能性。希望您喜欢,我们下次再见! ?
以上是与GeminiAI沟通JAVA的详细内容。更多信息请关注PHP中文网其他相关文章!