chatGPT - java 实例

1.导包

        <!-- openai gpt3 -->
        
            com.theokanning.openai-gpt3-java
            api
            0.11.0
        
        
            com.theokanning.openai-gpt3-java
            client
            0.11.0
        
        
            com.theokanning.openai-gpt3-java
            service
            0.11.0
        

2.java程序

import com.alibaba.fastjson.JSONObject;
import com.theokanning.openai.completion.CompletionRequest;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.nio.charset.StandardCharsets;


public class OpenAiApi {
    public static String OpenAiAnswerer(CompletionRequest request, String openAiApiKey) {

        // 代理IP
        String proxyHost = "127.0.0.1";
        // 代理端口
        int proxyPort = 7890;
        // 请求地址
        String url = "https://api.openai.com/v1/completions";
        // json为请求体
        String json = JSONObject.toJSONString(request);
        String result = "";
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(proxy);
            connection.setRequestProperty("Authorization", "Bearer " + openAiApiKey);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            byte[] requestBodyBytes = json.getBytes(StandardCharsets.UTF_8);
            try (OutputStream outputStream = connection.getOutputStream()) {
                outputStream.write(requestBodyBytes, 0, requestBodyBytes.length);
            }
            try (InputStream inputStream = connection.getInputStream()) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                result = response.toString();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

}

3.测试运行

    public static void main(String[] args){
        showModels();
    }

    /**
     * 显示模型
     * 根据不同的功能和语言选择合适的模型,可以在官网的模型概述中查看
     * https://platform.openai.com/docs/models/overview
     */
    public static void showModels(){
        CompletionRequest completionRequest = CompletionRequest.builder()
                .model("text-davinci-003")
                .prompt("今天天气怎么样?")
                .temperature(0.5)
                .build();
        String result = OpenAiApi.OpenAiAnswerer(completionRequest, "使用自己的apiKey替代");
        System.out.println(result);
    }

4.运行结果
{
“id”: “cmpl-7Ew6fGetJbXrKnYXlpTI4HfDaVMTK”,
“object”: “text_completion”,
“created”: 1683794309,
“model”: “text-davinci-003”,
“choices”: [
{
“text”: “\n\n今天的天气情况不”,
“index”: 0,
“logprobs”: null,
“finish_reason”: “length”
}
],
“usage”: {
“prompt_tokens”: 15,
“completion_tokens”: 14,
“total_tokens”: 29
}
}

你可能感兴趣的:(java,chatgpt,开发语言)