Java语言可以使用我的开源SDK进行调用更加简单,快捷,高效。
SDK更多特性参考我的这篇文章: https://www.unfbx.com/index.php/archives/208
项目主页:https://github.com/Grt1228/chatgpt-java 目前已收获1600+的star

一、获取api key

参考这个文章:https://blog.csdn.net/zgpeace/article/details/128800788

二、Postman模拟请求

Method:post
Urlhttps://api.openai.com/v1/completions
Header:Authorization:Bearer 申请的api key
Request Body:

{
    "prompt": "Java Stream list to map",  //问题
    "model": "text-davinci-003",          //支持三种模型:davinci,text-davinci-002,text-davinci-003
    "max_tokens": 1024,
    "temperature": 0.9,
    "stop": [
        "#"
    ],
    "top_p": 1,
    "n": 1
}

Response

{
    "id": "cmpl-6iIsfO7KhsVTyyNdEBbUZognKCRHc",
    "object": "text_completion",
    "created": 1676017029,
    "model": "text-davinci-003",
    "choices": [
        {
            "text": " example\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\npublic class StreamListToMapExample { \n\n  public static void main(String[] args) {\n\n    //create a list of objects\n    List<Person> list = new ArrayList<>();\n    list.add(new Person(1,\"John\",\"Doe\"));\n    list.add(new Person(2,\"Chris\",\"Evans\"));\n    list.add(new Person(3,\"Robert\",\"Downey\"));\n\n    // create a stream from list\n    Map<Integer,String> map = list.stream().collect(Collectors.toMap(Person::getId,Person::getFullName));\n    System.out.println(map);\n\n  }\n    \n  static class Person {\n    private int id;\n    private String firstName;\n    private String lastName;\n\n    public Person(int id, String firstName, String lastName) {\n        this.id = id;\n        this.firstName = firstName;\n        this.lastName = lastName;\n    }\n\n    public int getId() {\n        return id;\n    }\n\n    public String getFirstName() {\n        return firstName;\n    }\n\n    public String getLastName() {\n        return lastName;\n    }\n\n    public String getFullName() {\n        return firstName + \" \" + lastName;\n    }\n  }\n}",
            "index": 0,
            "logprobs": null,
            "finish_reason": "stop"
        }
    ],
    "usage": {
        "prompt_tokens": 5,
        "completion_tokens": 345,
        "total_tokens": 350
    }
}
文章目录