当前位置:   article > 正文

java利用jdk11和jdk15新特性零依赖优雅调用GPT-4o,附golang实现对比_java怎么接入gpt4o

java怎么接入gpt4o

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

背景

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

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

所以有利用油猴脚本跳过

有自己调用接口的

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

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

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

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

jdk17来帮忙

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

主要用到的特性有两个

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

话不多说,直接看代码

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

源码如下

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();
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

goalng实现

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))
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小桥流水78/article/detail/962842
推荐阅读
相关标签
  

闽ICP备14008679号