OpenAI提供了一個(gè)REST API,可以通過(guò)Java調(diào)用。可以使用Java的HttpClient類來(lái)發(fā)送HTTP請(qǐng)求,以調(diào)用OpenAI API。具體步驟如下:
1. 創(chuàng)建一個(gè)HttpClient對(duì)象,用于發(fā)送HTTP請(qǐng)求。
2. 構(gòu)造一個(gè)HttpPost對(duì)象,指定OpenAI API的URL。
3. 將請(qǐng)求參數(shù)添加到HttpPost對(duì)象中。
4. 使用HttpClient發(fā)送請(qǐng)求,并獲取響應(yīng)。
5. 從響應(yīng)中提取所需的結(jié)果。
pom:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>OpenAi</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>adapter-rxjava2</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-jackson</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
</dependencies>
</project>
public class OpenAI {
public static void main(String[] args){
OpenAiService service = new OpenAiService("你的KEY");
CompletionRequest completionRequest = CompletionRequest.builder()
.prompt("女朋友生氣了怎么辦")
.model("text-davinci-002")
.maxTokens(1000)
.temperature(0.2)
.build();
service.createCompletion(completionRequest).getChoices().forEach(System.out::println);
}
}

還需要引入上面兩個(gè)jar,jar從github.com/liuhenghui/openai-java 獲取。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-518449.html
ChatGPT 國(guó)內(nèi)體驗(yàn)地址 https://www.1bit.asia文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-518449.html
到了這里,關(guān)于java怎么調(diào)用openai接口的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!