Java对接chatgpt进行聊天问答接口
public static void chatgpt() throws IOException { // ChatGPT API endpoint String apiUrl = "https://api.openai.com/v1/chat/completions"; // Your API key String apiKey = "API_KEY"; // Request payload (max_tokens越大,回答内容越长,其它参数也是必须的) String payload = "{\"model\": \"gpt-3.5-turbo\",\"messages\": [{\"role\": \"user\", \"content\": \"Can you tell me a small story?\"}], \"max_tokens\": 1500}"; // Create connection URL url = new URL(apiUrl); HttpURLConnection connection; // Proxy configuration (if using a proxy) String proxyHost = "127.0.0.1"; int proxyPort = 7890; Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); connection = (HttpURLConnection) url.openConnection(proxy); // Set connection properties connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Authorization", "Bearer " + apiKey); connection.setDoOutput(true); // Set connection and read timeouts (in milliseconds) 回答的内容越长,读取的时间越长 int connectionTimeout = 50000; // 50 seconds int readTimeout = 50000; // 50 seconds connection.setConnectTimeout(connectionTimeout); connection.setReadTimeout(readTimeout); // Send request DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes(payload); outputStream.flush(); outputStream.close(); // Check response code int responseCode = connection.getResponseCode(); URL url1 = connection.getURL(); String responseMessage = connection.getResponseMessage(); if (responseCode == HttpURLConnection.HTTP_OK) { // Get response BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); System.out.println("响应数据:"); // Process response System.out.println(response.toString()); } else { // Handle error response System.out.println("Error response code: " + responseCode); System.out.println("Error response url: " + url1); System.out.println("Error response responseMessage: " + responseMessage); } }
打印结果:
响应数据:
{"id":"chatcmpl-7HT72eFZbl3DRwopnE40KqJlMNu4w","object":"chat.completion","created":1684397840,"model":"gpt-3.5-turbo-0301","usage":{"prompt_tokens":20,"completion_tokens":9,"total_tokens":29},"choices":[{"message":{"role":"assistant","content":"Sure, what would you like to know?"},"finish_reason":"stop","index":0}]}
注意:如果遇到400错误,请查看你的参数是否正确;如果read timeout 就是内容太长,需要将超时时间设置大些
前提是:本地已经打开梯子(FQ工具)了,毕竟是外接口
踩过这个坑,还有下一个坑等着你,这一路就是给自己填坑,坑填多了,也就习惯了,直到这一路平坦了,也就无怨无悔了。