开发喵星球

Java快速接入ChatGPT API实现聊天、生成图像

Java快速接入ChatGPT API实现聊天、生成图像

申请API秘钥

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

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

image-20240320132138515

image-20240320132201695

发请求

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

<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.10.0</version>
</dependency>
 
<!-- 非springboot, 使用以下依赖 -->
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.5.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.5.2</version>
</dependency>
 
<!-- springboot, 使用以下依赖 版本号跟你的父项目保持一致-->
<!--        <dependency>-->
<!--            <groupId>org.springframework.boot</groupId>-->
<!--            <artifactId>spring-boot-starter-json</artifactId>-->
<!--        </dependency>-->

发请求响应文本

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

import java.io.Serializable;
import java.util.List;
 
/**
 * api请求的参数
 */
public class Text implements Serializable {
 
    private static final long serialVersionUID = 1L;
    /**
     * model : gpt-3.5-turbo messages : [{"role":"user","content":"Say this is a test!"}] temperature : 0.7
     */
 
    private String model;
    private double temperature;
    private List<MessagesBean> messages;
 
    public String getModel() {
        return model;
    }
 
    public void setModel(String model) {
        this.model = model;
    }
 
    public double getTemperature() {
        return temperature;
    }
 
    public void setTemperature(double temperature) {
        this.temperature = temperature;
    }
 
    public List<MessagesBean> getMessages() {
        return messages;
    }
 
    public void setMessages(List<MessagesBean> messages) {
        this.messages = messages;
    }
 
    public static class MessagesBean implements Serializable {
        private static final long serialVersionUID = 1L;
        /**
         * role : user content : Say this is a test!
         */
 
        private String role;
        private String content;
 
        public MessagesBean(String user, String content) {
            this.role = user;
            this.content = content;
        }
 
        public String getRole() {
            return role;
        }
 
        public void setRole(String role) {
            this.role = role;
        }
 
        public String getContent() {
            return content;
        }
 
        public void setContent(String content) {
            this.content = content;
        }
    }
}

发请求:

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.Collections;
 
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
 
import okhttp3.*;
 
public class Test {
    /** API秘钥 添加自己的秘钥 */
    private static final String KEY = "";
    /** url */
    private static final String URL = "https://api.openai.com/v1/chat/completions";
    /** 配置代理服务的ip 根据自己实际情况配置 */
    private static final String HOST = "127.0.0.1";
    /** 配置代理服务的端口 根据自己实际情况配置 */
    private static final int PORT = 7890;
 
    public static void main(String[] args) throws JsonProcessingException {
        // 输入内容
        String content = "您好";
        // 创建 ObjectMapper 用于解析 JSON
        ObjectMapper objectMapper = new ObjectMapper();
        Text text = new Text();
        // 设置模型
        text.setModel("gpt-3.5-turbo");
        // 值越小,生成的文本越可信,但也越无创造性 值越大,生成的文本越有创造性,但也越不可信 范围:0.0-1.0
        text.setTemperature(0.7);
        text.setMessages(Collections.singletonList(new Text.MessagesBean("user", content)));
        // 配置代理
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(HOST, PORT));
        // 创建 OkHttpClient
        OkHttpClient client = new OkHttpClient.Builder().proxy(proxy).build();
        // 创建请求体,携带 JSON 参数
        RequestBody requestBody = RequestBody.create(objectMapper.writeValueAsString(text),
            MediaType.parse("application/json; charset=utf-8"));
        // 创建请求
        Request request =
            new Request.Builder().url(URL).addHeader("Authorization", "Bearer ".concat(KEY)).post(requestBody).build();
        // 发送请求并处理响应
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            // 解析json 获取结果
            JsonNode jsonNode = objectMapper.readTree(response.body().string());
            System.out.println(jsonNode.get("choices").get(0).get("message").get("content").asText());
        } catch (IOException e) {
            e.printStackTrace();
        }
 
    }
}

image-20240320132449696

发请求响应图像

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

import java.io.Serializable;


public class Images implements Serializable {
 
    private static final long serialVersionUID = 1L;
    /**
     * prompt : A cute baby sea otter n : 2 size : 1024x1024
     */
 
    private String prompt;
    private int n;
    private String size;
 
    public String getPrompt() {
        return prompt;
    }
 
    public void setPrompt(String prompt) {
        this.prompt = prompt;
    }
 
    public int getN() {
        return n;
    }
 
    public void setN(int n) {
        this.n = n;
    }
 
    public String getSize() {
        return size;
    }
 
    public void setSize(String size) {
        this.size = size;
    }
}

发请求:

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
 
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
 
import okhttp3.*;
 
public class TestImg {
    /** API秘钥 添加自己的秘钥 */
    private static final String KEY = "";
    /** url */
    private static final String URL = "https://api.openai.com/v1/images/generations";
    /** 配置代理服务的ip 根据自己实际情况配置 */
    private static final String HOST = "127.0.0.1";
    /** 配置代理服务的端口 根据自己实际情况配置 */
    private static final int PORT = 7890;
 
    public static void main(String[] args) throws JsonProcessingException {
        // 输入内容
        String content = "生成一只功夫熊猫";
        // 创建 ObjectMapper 用于解析 JSON
        ObjectMapper objectMapper = new ObjectMapper();
        Images images = new Images();
        // 生成图像的描述
        images.setPrompt(content);
        // 生成图像的数量
        images.setN(1);
        // 生成图像的尺寸
        images.setSize("1024x1024");
        // 配置代理
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(HOST, PORT));
        // 创建 OkHttpClient
        OkHttpClient client = new OkHttpClient.Builder().proxy(proxy).build();
        // 创建请求体,携带 JSON 参数
        RequestBody requestBody = RequestBody.create(objectMapper.writeValueAsString(images),
            MediaType.parse("application/json; charset=utf-8"));
        // 创建请求
        Request request =
            new Request.Builder().url(URL).addHeader("Authorization", "Bearer ".concat(KEY)).post(requestBody).build();
        // 发送请求并处理响应
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            // 解析json 获取结果
            JsonNode jsonNode = objectMapper.readTree(response.body().string());
            System.out.println(jsonNode.get("data").get(0).get("url").asText());
        } catch (IOException e) {
            e.printStackTrace();
        }
 
    }
}

image-20240320132600035

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

image-20240320132637411

   
分类:玩技术 作者:荡荡, 浩浩 发表于:2024-03-20 13:31:10 阅读量:87
<<   >>


powered by kaifamiao