Use Java code to call openAI's ChatGPT API

Premise: register your own API key at https://beta.openai.com/account/api-keys.

To use the OpenAI API with the Java Spring Framework, you need to use a library capable of handling HTTP requests. One of the popular libraries is the Spring RestTemplate library. RestTemplate is a powerful and flexible library that makes it easy to send HTTP requests and process responses.

First, you need to add the Spring RestTemplate library to your project. You can do this by adding the following dependencies to your build.gradle file:

dependencies {
    
    
    // 其他依赖...
    implementation 'org.springframework.boot:spring-boot-starter-web'
}

The spring-boot-starter-web dependency contains the RestTemplate library, as well as other dependencies needed to build web applications using Spring.

After adding dependencies, you need to configure RestTemplate in your application. You can create a RestTemplate bean in Spring configuration class or directly in application class. Here is an example of creating a RestTemplate bean:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class AppConfig {
    
    

    @Bean
    public RestTemplate restTemplate() {
    
    
        return new RestTemplate();
    }
}

In the example above, the @Configuration annotation indicates that the class contains Spring configuration. The @Bean annotation on the restTemplate() method creates a RestTemplate bean that can be autowired into other classes for HTTP requests.

After configuring the RestTemplate, you can use it to send HTTP requests to the OpenAI API. You can send GET or POST requests using methods like getForObject() or postForObject(). Here is an example of a GET request using RestTemplate:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class OpenAIService {
    
    

    private final RestTemplate restTemplate;

    @Autowired
    public OpenAIService(RestTemplate restTemplate) {
    
    
        this.restTemplate = restTemplate;
    }

    public String getOpenAIResponse() {
    
    
        String apiUrl = "https://api.openai.com/v1/your-endpoint";
        // 设置任何必要的请求参数或头部信息

        // 发送GET请求并接收响应
        String response = restTemplate.getForObject(apiUrl, String.class);

        return response;
    }
}

In the above example, the RestTemplate bean is injected into the OpenAIService class through the constructor. In the getOpenAIResponse() method, you can customize the URL, request parameters, header information, and process the response as required.

Remember to replace "https://api.openai.com/v1/your-endpoint" with the actual URL you want to communicate with the OpenAI API.

The above is how to use the Spring RestTemplate library to interact with the OpenAI API in the Java Spring Framework project.

For more detailed operations, please refer to this article .

Contents of build.gradle:

plugins {
    
    
 id 'java'
 id 'org.springframework.boot' version '3.0.1'
 id 'io.spring.dependency-management' version '1.1.0'
}

group = 'com.openai'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'

repositories {
    
    
 mavenCentral()
}

dependencies {
    
    
 implementation 'org.springframework.boot:spring-boot-starter-web'
 testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

tasks.named('test') {
    
    
 useJUnitPlatform()
}

Java implementation:

@Component
public class OpenAi
{
    
    
 private static final String OPENAI_URL = "https://api.openai.com/v1/images/generations";

 private final String apiKey = "<your-api-key";
 private final RestTemplate restTemplate = new RestTemplate();

 public String generateImages(String prompt, float temperature, int maxTokens, String stop, final int logprobs, final boolean echo)
 {
    
    
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.APPLICATION_JSON);
  headers.set("Authorization", "Bearer " + apiKey);

  // We are including only some of the parameters to the json request
  String requestJson = "{\"prompt\":\"" + prompt + "\",\"n\":" + n + "}";

  HttpEntity<String> request = new HttpEntity<>(requestJson, headers);
  ResponseEntity<String> response = restTemplate.postForEntity(OPENAI_URL, request, String.class);
  return response.getBody();
 }
}

おすすめ

転載: blog.csdn.net/i042416/article/details/130702819