likes
comments
collection
share

搞定ChatGPT的API使用,2分钟应该够了!

作者站长头像
站长
· 阅读数 3

开发环境

  • Idea - v2023
  • Java JDK 17
    • OkHttp - v4.10.0
    • FastJson - v1.2.78
  • Golang - v1.9

前言

ChatGPT最近异常火爆,大部分同学想必都已经体验过网页版的ChatGPT,这里跟大家介绍一下如何通过API的方式,访问ChatGPT,实现文字互动的基本功能。

ChatGPT API地址

访问地址:platform.openai.com/docs/api-re…

API使用前要看的(特别注意)

当我们注册完一个ChatGPT账户后,其实OpenAI送了我们一个价值18美刀的额度,你要先看下自己的额度,注意别用的太猛!

OpenAI费用计算方式: 晒下我的额度,并附上访问地址:platform.openai.com/account/usa…

搞定ChatGPT的API使用,2分钟应该够了!

第一步:创建API-Key

首先必须在你的OpenAI账户中创建用户调用API的Key,也是每个接口必传参数。

创建地址:platform.openai.com/account/api…

创建后的截图

搞定ChatGPT的API使用,2分钟应该够了!

第二部:使用文本方式交互API - 接口地址

文本方式交互也是我们目前最经常看到的,就和Web网页版是一样的。小编这里放一下自己的代码,我用Golang和Java分别实现调用API的操作,大家需要的话,可以直接使用。

Java代码

public class ChatGPTApiClient {

    public static void main(String[] args) throws Exception {
        String endPoint = "https://api.openai.com/v1/chat/completions";
        String apiKey = "输入你自己的API-Key";

        OkHttpClient client = new OkHttpClient.Builder()
                .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 7890)))
                .build();

        List<Map<String, String>> messages = new ArrayList<>();
        messages.add(Map.of("role", "user", "content", "这是我第一次使用API!"));

        Map<String, Object> reqBody = new HashMap<>();
        reqBody.put("model", "gpt-3.5-turbo");
        reqBody.put("messages", messages);
        reqBody.put("temperature", 0.7);

        RequestBody requestBody = RequestBody.create(JSON.toJSONBytes(reqBody), MediaType.parse("application/json"));

        Request request = new Request.Builder()
                .url(endPoint)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer " + apiKey)
                .post(requestBody)
                .build();

        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            System.out.println("Response:" + response.body().string());
        } else {
            System.out.println("Error:" + response.code() + " " + response.message());
        }
    }
}
调用API后返回的结果
{
    "id": "chatcmpl-6vM23oRLInRE68HE7oEsHhR1rqaGz",
    "object": "chat.completion",
    "created": 1679127407,
    "model": "gpt-3.5-turbo-0301",
    "usage": {
        "prompt_tokens": 16,
        "completion_tokens": 90,
        "total_tokens": 106
    },
    "choices": [
        {
            "message": {
                "role": "assistant",
                "content": "\n\n欢迎使用API!API是一种编程接口,可以让您的应用程序与其他应用程序或服务进行交互。使用API可以帮助您快速开发应用程序,并使您的应用程序更加功能强 大和易于使用。如果您需要任何帮助或支持,请随时联系我们!"
            },
            "finish_reason": "stop",
            "index": 0
        }
    ]
}

Golang代码

package main

import (
	"encoding/json"
	"fmt"
	"github.com/go-resty/resty/v2"
)

func main() {
	endPoint := "https://api.openai.com/v1/chat/completions"
	apiKey := "输入你自己的API-Key"

	client := resty.New()
	client.SetProxy("http://127.0.0.1:7890")
	//请求报文体
	messages := []map[string]string{{"role": "user", "content": "这是我第一次使用API!"}}

	reqBody := make(map[string]interface{})
	reqBody["model"] = "gpt-3.5-turbo"
	reqBody["messages"] = messages
	reqBody["temperature"] = 0.7

	reqJSON, _ := json.Marshal(reqBody)

	resp, err := client.R().
		SetHeader("Content-Type", "application/json").
		SetHeader("Authorization", fmt.Sprintf("Bearer %s", apiKey)).
		SetBody(reqJSON).
		Post(endPoint)

	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println("Response:", resp.String())
}

语音、图像和其他接口

有了上述文本接口作为参考,其他接口那还不是信手捏来!

总结

利用ChatGPT API我们可以灵活的自己搞个服务玩起来了,前提条件是,不要用国内的网络,代码中我用了Proxy(代理),想必大家都懂得!存在其他问题的小伙伴,欢迎留言讨论!

参考文献