如果你用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中文網其他相關文章!