当前位置:   article > 正文

【Java】快速接入ChatGPT API实现聊天、生成图像_chatgpt image api

chatgpt image api

目录

申请API秘钥

发请求

发请求响应文本 

发请求响应图像


申请API秘钥

访问https://platform.openai.com/

 登录后点击右上角的头像,如图:

获取到秘钥后接下来就开始搞代码啦~ 


发请求

添加发请求和解析响应的maven依赖

  1. <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
  2. <dependency>
  3. <groupId>com.squareup.okhttp3</groupId>
  4. <artifactId>okhttp</artifactId>
  5. <version>4.10.0</version>
  6. </dependency>
  7. <!-- 非springboot, 使用以下依赖 -->
  8. <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
  9. <dependency>
  10. <groupId>com.fasterxml.jackson.core</groupId>
  11. <artifactId>jackson-core</artifactId>
  12. <version>2.5.2</version>
  13. </dependency>
  14. <dependency>
  15. <groupId>com.fasterxml.jackson.core</groupId>
  16. <artifactId>jackson-databind</artifactId>
  17. <version>2.5.2</version>
  18. </dependency>
  19. <dependency>
  20. <groupId>com.fasterxml.jackson.core</groupId>
  21. <artifactId>jackson-annotations</artifactId>
  22. <version>2.5.2</version>
  23. </dependency>
  24. <!-- springboot, 使用以下依赖 版本号跟你的父项目保持一致-->
  25. <!-- <dependency>-->
  26. <!-- <groupId>org.springframework.boot</groupId>-->
  27. <!-- <artifactId>spring-boot-starter-json</artifactId>-->
  28. <!-- </dependency>-->

发请求响应文本 

添加一个实体, 用于设置发请求的参数:

  1. import java.io.Serializable;
  2. import java.util.List;
  3. /**
  4. * api请求的参数
  5. *
  6. * @author 提笔忘字的帝国
  7. */
  8. public class Text implements Serializable {
  9. private static final long serialVersionUID = 1L;
  10. /**
  11. * model : gpt-3.5-turbo messages : [{"role":"user","content":"Say this is a test!"}] temperature : 0.7
  12. */
  13. private String model;
  14. private double temperature;
  15. private List<MessagesBean> messages;
  16. public String getModel() {
  17. return model;
  18. }
  19. public void setModel(String model) {
  20. this.model = model;
  21. }
  22. public double getTemperature() {
  23. return temperature;
  24. }
  25. public void setTemperature(double temperature) {
  26. this.temperature = temperature;
  27. }
  28. public List<MessagesBean> getMessages() {
  29. return messages;
  30. }
  31. public void setMessages(List<MessagesBean> messages) {
  32. this.messages = messages;
  33. }
  34. public static class MessagesBean implements Serializable {
  35. private static final long serialVersionUID = 1L;
  36. /**
  37. * role : user content : Say this is a test!
  38. */
  39. private String role;
  40. private String content;
  41. public MessagesBean(String user, String content) {
  42. this.role = user;
  43. this.content = content;
  44. }
  45. public String getRole() {
  46. return role;
  47. }
  48. public void setRole(String role) {
  49. this.role = role;
  50. }
  51. public String getContent() {
  52. return content;
  53. }
  54. public void setContent(String content) {
  55. this.content = content;
  56. }
  57. }
  58. }

发请求:

  1. import java.io.IOException;
  2. import java.net.InetSocketAddress;
  3. import java.net.Proxy;
  4. import java.util.Collections;
  5. import com.fasterxml.jackson.core.JsonProcessingException;
  6. import com.fasterxml.jackson.databind.JsonNode;
  7. import com.fasterxml.jackson.databind.ObjectMapper;
  8. import okhttp3.*;
  9. /**
  10. * @author 提笔忘字的帝国
  11. */
  12. public class Test {
  13. /** API秘钥 添加自己的秘钥 */
  14. private static final String KEY = "";
  15. /** url */
  16. private static final String URL = "https://api.openai.com/v1/chat/completions";
  17. /** 配置代理服务的ip 根据自己实际情况配置 */
  18. private static final String HOST = "127.0.0.1";
  19. /** 配置代理服务的端口 根据自己实际情况配置 */
  20. private static final int PORT = 7890;
  21. public static void main(String[] args) throws JsonProcessingException {
  22. // 输入内容
  23. String content = "您好";
  24. // 创建 ObjectMapper 用于解析 JSON
  25. ObjectMapper objectMapper = new ObjectMapper();
  26. Text text = new Text();
  27. // 设置模型
  28. text.setModel("gpt-3.5-turbo");
  29. // 值越小,生成的文本越可信,但也越无创造性 值越大,生成的文本越有创造性,但也越不可信 范围:0.0-1.0
  30. text.setTemperature(0.7);
  31. text.setMessages(Collections.singletonList(new Text.MessagesBean("user", content)));
  32. // 配置代理
  33. Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(HOST, PORT));
  34. // 创建 OkHttpClient
  35. OkHttpClient client = new OkHttpClient.Builder().proxy(proxy).build();
  36. // 创建请求体,携带 JSON 参数
  37. RequestBody requestBody = RequestBody.create(objectMapper.writeValueAsString(text),
  38. MediaType.parse("application/json; charset=utf-8"));
  39. // 创建请求
  40. Request request =
  41. new Request.Builder().url(URL).addHeader("Authorization", "Bearer ".concat(KEY)).post(requestBody).build();
  42. // 发送请求并处理响应
  43. try (Response response = client.newCall(request).execute()) {
  44. if (!response.isSuccessful()) {
  45. throw new IOException("Unexpected code " + response);
  46. }
  47. // 解析json 获取结果
  48. JsonNode jsonNode = objectMapper.readTree(response.body().string());
  49. System.out.println(jsonNode.get("choices").get(0).get("message").get("content").asText());
  50. } catch (IOException e) {
  51. e.printStackTrace();
  52. }
  53. }
  54. }

发请求响应图像

添加一个实体, 用于设置发请求的参数:

  1. import java.io.Serializable;
  2. /**
  3. * api请求的参数
  4. *
  5. * @author 提笔忘字的帝国
  6. */
  7. public class Images implements Serializable {
  8. private static final long serialVersionUID = 1L;
  9. /**
  10. * prompt : A cute baby sea otter n : 2 size : 1024x1024
  11. */
  12. private String prompt;
  13. private int n;
  14. private String size;
  15. public String getPrompt() {
  16. return prompt;
  17. }
  18. public void setPrompt(String prompt) {
  19. this.prompt = prompt;
  20. }
  21. public int getN() {
  22. return n;
  23. }
  24. public void setN(int n) {
  25. this.n = n;
  26. }
  27. public String getSize() {
  28. return size;
  29. }
  30. public void setSize(String size) {
  31. this.size = size;
  32. }
  33. }

 发请求:

  1. import java.io.IOException;
  2. import java.net.InetSocketAddress;
  3. import java.net.Proxy;
  4. import com.fasterxml.jackson.core.JsonProcessingException;
  5. import com.fasterxml.jackson.databind.JsonNode;
  6. import com.fasterxml.jackson.databind.ObjectMapper;
  7. import okhttp3.*;
  8. /**
  9. * @author 提笔忘字的帝国
  10. */
  11. public class TestImg {
  12. /** API秘钥 添加自己的秘钥 */
  13. private static final String KEY = "";
  14. /** url */
  15. private static final String URL = "https://api.openai.com/v1/images/generations";
  16. /** 配置代理服务的ip 根据自己实际情况配置 */
  17. private static final String HOST = "127.0.0.1";
  18. /** 配置代理服务的端口 根据自己实际情况配置 */
  19. private static final int PORT = 7890;
  20. public static void main(String[] args) throws JsonProcessingException {
  21. // 输入内容
  22. String content = "生成一只功夫熊猫";
  23. // 创建 ObjectMapper 用于解析 JSON
  24. ObjectMapper objectMapper = new ObjectMapper();
  25. Images images = new Images();
  26. // 生成图像的描述
  27. images.setPrompt(content);
  28. // 生成图像的数量
  29. images.setN(1);
  30. // 生成图像的尺寸
  31. images.setSize("1024x1024");
  32. // 配置代理
  33. Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(HOST, PORT));
  34. // 创建 OkHttpClient
  35. OkHttpClient client = new OkHttpClient.Builder().proxy(proxy).build();
  36. // 创建请求体,携带 JSON 参数
  37. RequestBody requestBody = RequestBody.create(objectMapper.writeValueAsString(images),
  38. MediaType.parse("application/json; charset=utf-8"));
  39. // 创建请求
  40. Request request =
  41. new Request.Builder().url(URL).addHeader("Authorization", "Bearer ".concat(KEY)).post(requestBody).build();
  42. // 发送请求并处理响应
  43. try (Response response = client.newCall(request).execute()) {
  44. if (!response.isSuccessful()) {
  45. throw new IOException("Unexpected code " + response);
  46. }
  47. // 解析json 获取结果
  48. JsonNode jsonNode = objectMapper.readTree(response.body().string());
  49. System.out.println(jsonNode.get("data").get(0).get("url").asText());
  50. } catch (IOException e) {
  51. e.printStackTrace();
  52. }
  53. }
  54. }

 可以看到响应回来的是一个图像的链接, 点击查看链接即可, 下图是生成回来的图像

emmmm, 跟我想象的不一样, 可能是我描述不够清晰, 今天就到这啦~


 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/129120
推荐阅读
相关标签