Article directory
Step 1: Configure the proxy
Some magic requires configuration. Otherwise, code testing cannot be implemented correctly. Here are the tools I use as an example.
Step 2: Add dependencies
Add in pom.xml file:
<dependency>
<groupId>com.theokanning.openai-gpt3-java</groupId>
<artifactId>client</artifactId>
<version>0.8.1</version>
</dependency>
Step 3: Write the Constants class
- In the Constants class, declare your own API Key
public class Constants {
//大家填写自己的key,这个是瞎写的,没有用的
public static final String OPENAPI_TOKEN = "sk-JPPwaelHv5QwdN3CL97UKLMbo7XIJDRy";
}
Among them, check the location of API Key:
https://platform.openai.com/account/api-keys
Balance query:
https://platform.openai.com/account/usage
Step 4: Implement Q&A interaction
package com.atguigu.demo;
import com.atguigu.Constants;
import com.theokanning.openai.OpenAiService;
import com.theokanning.openai.completion.CompletionRequest;
public class Demo1 {
public static void main(String[] args) {
String info1 = "Q: 能不能我写一封简短的情话,使用诗经的语言风格?A:";
info(info1);
}
public static void info(String promptInfo){
//注意:参数2用于设置超时时间
OpenAiService service = new OpenAiService(Constants.OPENAPI_TOKEN,5000);
CompletionRequest completionRequest = CompletionRequest.builder()
.model("text-davinci-003") //使用的模型
.prompt(promptInfo) //生成提示
.temperature(0D) //创新采样
.maxTokens(1000) //Token大小设置
.topP(1D) //情绪采样。[0,1]:从悲观到乐观
.frequencyPenalty(0D) //频率处罚系数。用来设置文本中出现重复词汇时的处罚参数
.presencePenalty(0D) //重复处罚系数
.build();
service.createCompletion(completionRequest)
.getChoices()
.forEach(System.out::println);
}
}
Step 5: Implement image generation
package com.atguigu.demo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.Constants;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
public class Demo2 {
public static void main(String[] args) throws IOException {
String json = "{" +
"\"prompt\":\"古装将军\"," +
"\"n\":1," +
"\"size\":\"1024x1024\"," +
"\"response_format\":\"url\"" +
"}";
show(json);
}
public static void show(String json) throws IOException{
Document document =
Jsoup.connect("https://api.openai.com/v1/images/generations")
.header("Authorization", "Bearer " + Constants.OPENAPI_TOKEN)
.header("Content-Type", "application/json")
.ignoreHttpErrors(true)
.ignoreContentType(true)
.requestBody(json)
.post();
JSONObject jsonObject = JSON.parseObject(document.body().text());
JSONArray data = jsonObject.getJSONArray("data");
for (int i = 0; i < data.size(); i++) {
JSONObject temp = data.getJSONObject(i);
System.out.println(temp.get("url"));
}
}
}
Dependencies need to be added to the pom.xml file:
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.14.3</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>