文章目录
- 步骤1:配置代理
- 步骤2:添加依赖
- 步骤3:编写Constants类
- 步骤4:实现问答交互
- 步骤5:实现图片生成
步骤1:配置代理
有些魔法是需要做配置的。否则无法正确实现代码测试。这里以我使用的工具为例说明。
步骤2:添加依赖
在pom.xml文件中添加:
<dependency><groupId>com.theokanning.openai-gpt3-java</groupId><artifactId>client</artifactId><version>0.8.1</version>
</dependency>
步骤3:编写Constants类
- Constants类中,声明自己的API Key
public class Constants {
//大家填写自己的key,这个是瞎写的,没有用的
public static final String OPENAPI_TOKEN = "sk-JPPwaelHv5QwdN3CL97UKLMbo7XIJDRy";
}
其中,查看API Key的位置:
https://platform.openai.com/account/api-keys
余额查询:
https://platform.openai.com/account/usage
步骤4:实现问答交互
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);}
}
步骤5:实现图片生成
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"));}}
}
pom.xml文件中需要增加依赖:
<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>