Java 調用ChatGPT API實例(text-davinci-003)

1、獲取調用ChatGPT的key

登錄官網https://platform.openai.com/account/api-keysAPI生成一個key(請求token)

2、官方API請求示例查看

請求:

curl https://api.openai.com/v1/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{"model": "text-davinci-003", "prompt": "Say this is a test", "temperature": 0, "max_tokens": 7}'

響應:

{
    "id": "cmpl-GERzeJQ4lvqPk8SkZu4XMIuR",
    "object": "text_completion",
    "created": 1586839808,
    "model": "text-davinci:003",
    "choices": [
        {
            "text": "\n\nThis is indeed a test",
            "index": 0,
            "logprobs": null,
            "finish_reason": "length"
        }
    ],
    "usage": {
        "prompt_tokens": 5,        // 提問使用token數
        "completion_tokens": 7,    // 回答使用token數
        "total_tokens": 12         // 總計token數
    }
}

3、Java調用

    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper om=new ObjectMapper();
        List<String> str=new ArrayList<String>();
        str.add(" Human:");
        str.add(" AI:");
  
        SendChatGPTVO s=new SendChatGPTVO("text-davinci-003",
        "使用python写一个识别猫猫的程序的步骤",
        2048,0,1,0f,0.6f,str);
        
        RestTemplate restTemplate=new RestTemplate();
        HttpHeaders xheaders = new HttpHeaders();
        xheaders.setBearerAuth("sk-**********************");
        xheaders.setContentType(MediaType.APPLICATION_JSON);  
        String params = om.writeValueAsString(s);
        
        HttpEntity<String> requestEntity = new HttpEntity<String>(params,xheaders);
        
        JSONObject result = restTemplate.postForObject("https://api.openai.com/v1/completions", requestEntity, JSONObject.class);
        
        
        System.out.println("result:"+result);
    }

4、參數說明  

GPT3模型接口,模型名称为“text-davinci-003”,调用费用为0.02美元/1000tokens,折合下来差不多0.1元400~500字。这个字数包括问题和返回结果字数。

GPT3模型调用方式如下,输入主要有7个参数:

model:模型名称,text-davinci-003

prompt:问题或待补全内容,例如“how are you”。

temperature:控制结果随机性,0.0表示结果固定,随机性大可以设置为0.9。

max_tokens:最大返回字数(包括问题和答案),通常汉字占两个token。假设设置成100,如果prompt问题中有40个汉字,那么返回结果中最多包括10个汉字。

top_p:设置为1即可。

frequency_penalty:设置为0即可。

presence_penalty:设置为0即可。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值