掘金 后端 ( ) • 2024-05-16 09:55

这里是小奏,觉得文章不错可以关注公众号小奏技术

背景

目前GPT-4o官方不支持所有使用,所以各路大神各显神通

因为只对前端进行了限制。

所以有利用油猴脚本跳过

有自己调用接口的

如果要使用java来实现http调用,放在低版本的jdk

实现起来非常麻烦,主要有几点

  1. 原生的http api非常难用
  2. 不支持模板字符串,所以写json会非常丑陋

所以java 0依赖如何优雅实现GPT-4o的调用呢?还是挺有意思的

jdk17来帮忙

本次我们使用的jdk版本是17

主要用到的特性有两个

  1. jdk15的模板字符串
  2. jdk11的新HttpClient api

话不多说,直接看代码

image.png

整体来看是不是很简单优雅

源码如下

public static void main(String[] args) {
        String openaiApiKey = System.getenv("OPENAI_API_KEY");
        //文本块 需要jdk15+才支持
        String body = """
            {
                "model": "gpt-4o",
                "messages":
                 [
                    {
                        "role": "user",
                        "content": "hello world"
                    }
                ]
            }
            """;
        // jdk11+
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.openai.com/v1/chat/completions"))
            .header("Content-Type", "application/json")
            .header("Authorization", "Bearer " + openaiApiKey)
            .POST(HttpRequest.BodyPublishers.ofString(body)).build();

        HttpClient client = HttpClient.newHttpClient();
        try {
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            System.out.println(response.body());
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

goalng实现

image.png

func main() {
	openaiApiKey := os.Getenv("OPENAI_API_KEY")

	body := map[string]interface{}{
		"model": "gpt-4o",
		"messages": []map[string]string{
			{
				"role":    "user",
				"content": "hello world",
			},
		},
	}

	bodyBytes, err := json.Marshal(body)
	if err != nil {
		fmt.Println("Error marshalling JSON:", err)
		return
	}

	req, err := http.NewRequest("POST", "https://api.openai.com/v1/chat/completions", bytes.NewBuffer(bodyBytes))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}

	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+openaiApiKey)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {

		}
	}(resp.Body)

	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response body:", err)
		return
	}
	fmt.Println(string(respBody))
}

这么看java也挺优雅的哈哈,golang我比较菜,不确定是否有更优雅的实现哈哈