赞
踩
Spring Boot可以通过HTTP客户端调用Open AI的API接口,具体步骤如下:
目录
2.创建一个Spring Boot项目,并添加相关的依赖,例如
3.创建一个Java类作为Open AI的HTTP客户端,例如
4.在Spring Boot的配置文件中添加Open AI的API密钥
5.在Spring Boot的控制器中调用Open AI的API接口,例如
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-validation</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-jpa</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-security</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-thymeleaf</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.data</groupId>
- <artifactId>spring-data-rest-webmvc</artifactId>
- </dependency>
- package com.example.demo.service;
-
- import java.net.URI;
-
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.http.HttpHeaders;
- import org.springframework.http.MediaType;
- import org.springframework.http.RequestEntity;
- import org.springframework.http.ResponseEntity;
- import org.springframework.stereotype.Service;
- import org.springframework.web.client.RestTemplate;
-
- @Service
- public class OpenAiApiService {
-
- @Value("${openai.api.key}")
- private String apiKey;
-
- private RestTemplate restTemplate;
-
- public OpenAiApiService() {
- restTemplate = new RestTemplate();
- }
-
- public String generateText(String prompt) {
- String apiUrl = "https://api.openai.com/v1/engines/davinci-codex/completions";
-
- HttpHeaders headers = new HttpHeaders();
- headers.setContentType(MediaType.APPLICATION_JSON);
- headers.setBearerAuth(apiKey);
-
- String requestBody = "{\"prompt\": \"" + prompt + "\", \"max_tokens\": 60}";
-
- RequestEntity<String> requestEntity = RequestEntity
- .post(URI.create(apiUrl))
- .headers(headers)
- .body(requestBody);
-
- ResponseEntity<String> responseEntity = restTemplate.exchange(requestEntity, String.class);
- return responseEntity.getBody();
- }
- }
- openai:
- api:
- key: YOUR_API_KEY_HERE
- package com.example.demo.controller;
-
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestBody;
- import org.springframework.web.bind.annotation.RestController;
-
- import com.example
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。