首页 > 编程语言 >使用 Java 代码调用 openAI 的 ChatGPT API

使用 Java 代码调用 openAI 的 ChatGPT API

时间:2023-05-29 14:34:33浏览次数:49  
标签:Java restTemplate boot RestTemplate springframework API openAI Spring org

前提:在 https://beta.openai.com/account/api-keys 注册一个自己的 API key.

要在Java Spring Framework中使用OpenAI API,您需要使用一个能够处理HTTP请求的库。其中一个流行的库是Spring RestTemplate库。RestTemplate是一个强大而灵活的库,可以轻松地发送HTTP请求并处理响应。

首先,您需要将Spring RestTemplate库添加到您的项目中。您可以通过将以下依赖项添加到您的build.gradle文件中来实现:

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

spring-boot-starter-web依赖项包含了RestTemplate库,以及构建使用Spring进行Web应用程序所需的其他依赖项。

添加依赖项之后,您需要在应用程序中配置RestTemplate。您可以在Spring配置类或直接在应用程序类中创建一个RestTemplate bean。以下是创建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();
    }
}

上面的示例中,@Configuration注解表示该类包含Spring配置。restTemplate()方法上的@Bean注解创建了一个RestTemplate bean,可以自动装配到其他类中以进行HTTP请求。

配置好RestTemplate之后,您可以使用它向OpenAI API发送HTTP请求。您可以使用getForObject()或postForObject()等方法发送GET或POST请求。以下是使用RestTemplate进行GET请求的示例:

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;
    }
}

在上面的示例中,通过构造函数注入了RestTemplate bean到OpenAIService类中。在getOpenAIResponse()方法中,您可以根据需要自定义URL、请求参数、头部信息,并处理响应。

请记得将"https://api.openai.com/v1/your-endpoint"替换为您想要与OpenAI API通信的实际URL。

以上就是在Java Spring Framework项目中使用Spring RestTemplate库与OpenAI API交互的方法。

更详细的操作,请参考这篇文章

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 实现:

@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();
 }
}

标签:Java,restTemplate,boot,RestTemplate,springframework,API,openAI,Spring,org
From: https://www.cnblogs.com/sap-jerry/p/17440330.html

相关文章

  • linphone-KeepAliveReceiver.java文件分析
    说明Purposeofthisreceiveristodisablekeepaliveswhenscreenisoff解释这个接收器的目的是屏幕关闭的时候进行保活。<—翻译的准确性,等更加深刻的分析源码时更正,或者读者自己在下面评论也可以。介绍此类为接收器,接收外部传来的广播。KeepAliveReceiver.java/**Purpos......
  • linphone-BootReceiver.java文件分析
    说明这是个在android发送开机广播的时候调用的类功能主要就是为了在开机的时候启动LinphoneService开启后台服务。其中有一个.linphonerc的文件,这个文件应该是LpConfig的对应的配置文件。如果有错请更正。BootReceiver.javapublicclassBootReceiverextendsBroadcastReceiver{......
  • linphone-PresenceNote.java文件分析
    说明这个没什么好说的,一个普通的的类。UML类图PresenceNoteImpl.javapackageorg.linphone.core;publicclassPresenceNoteImplimplementsPresenceNote{privatelongmNativePtr;protectedPresenceNoteImpl(longnativePtr){mNativePtr=nativePtr;......
  • linphone-Tunnelconfig.java文件分析
    说明此类的主要作用主要是配置Host,port等。功能设置获取Host设置获取Port设置获取RemoteUdpMirrorPort获取设置maximumamountoftimeUML类图TunnelConfig.javapackageorg.linphone.core;publicclassTunnelConfigImplimplementsTunnelConfig{longmNativePtr;pr......
  • linphone-PresencePerson.java文件分析
    说明同上一张PresenceService和PresenceActivity的分析,但是不明白的是,为啥PresencePerson函数跟PresenceModel的函数很类似。唯一我现在能想到的原因是,每个Person主要存储。《—-放弃了,往后看吧。UML类图PresencePersonImpl.javapackageorg.linphone.core;publicclassPresenc......
  • linphone-PresenceActivity.java文件分析
    说明此类的对象供PresenceModel使用UML类图PresenceActivityImpl.javapackageorg.linphone.core;publicclassPresenceActivityImplimplementsPresenceActivity{privatelongmNativePtr;protectedPresenceActivityImpl(longnativePtr){mNativePtr=......
  • 什么是 JavaScript 里的循环引用(circular references)
    JavaScript的循环引用(circularreferences)是指在对象之间存在相互引用的情况,形成一个闭环,导致对象无法被完全释放和垃圾回收。循环引用发生在当一个对象的属性或成员引用另一个对象,并且这个被引用的对象又直接或间接地引用回原始对象,从而形成一个循环。当存在循环引用时,JavaScrip......
  • 详谈Java中Properties配置类怎么用
    本文将为大家详细讲解Java中Properties配置类怎么用,这是我们进行开发时经常用到的知识点,也是大家在学习Java中很重要的一个知识点,更是我们在面试时有可能会问到的问题!文章较长,干货满满,建议大家收藏慢慢学习。文末有本文重点总结,主页有全系列文章分享。技术类问题,欢迎大家和我们一......
  • 译文:理解Java中的弱引用
    不久之前,我面试了一些求职Java高级开发工程师的应聘者。我常常会面试他们说,“你能给我介绍一些Java中得弱引用吗?”,如果面试者这样说,“嗯,是不是垃圾回收有关的?”,我就会基本满意了,我并不期待回答是一篇诘究本末的论文描述。然而事与愿违,我很吃惊的发现,在将近20多个有着平均5年开发经......
  • Java:Double Brace Initialization
    在我刚刚接触现在这个产品的时候,我就在我们的代码中接触到了对DoubleBraceInitialization的使用。那段代码用来初始化一个集合:1finalSet<String>exclusions=newHashSet<String>(){{2add(‘Alice’);3add(‘Bob’);4add(‘Marine’);5}};......