当前位置:首页>文章>使用指南>OpenAI-Java示例代码

OpenAI-Java示例代码

文本是《工具配置(共24篇)》专题的第 24 篇。阅读本文前,建议先阅读前面的文章:

1. 资源准备

2. pom依赖

<dependency>
   <groupId>com.google.code.gson</groupId>
   <artifactId>gson</artifactId>
   <version>2.8.6</version>
</dependency>

3. 实现代码

import com.google.gson.*;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
/**
 * @description:
 * @Author: my.yang
 * @Date: 2025/4/10 15:10
 */

public class Java8OpenAIExample {

    /**
     * 这里填写在https://yibuapi.com网站上创建的API Key
     */
    private static final String API_KEY = "sk-xxxxxx";
    /**
     * 这里填写https://yibuapi.com/v1
     */
    private static final String BASE_URL = "https://yibuapi.com/v1";
    private static final String QUESTIONS = "生成三个虚构的中文书名及其作者和类型的清单。\n" +
            "使用以下键以 JSON 格式提供它们:book_id, title, author, genre.";

    public static void main(String[] args) {
        try {
            String response = getOpenAiResponse(QUESTIONS, API_KEY, BASE_URL);
            System.out.println("回答: " + response);
        } catch (Exception e) {
            System.out.println("请求失败: " + e.getMessage());
        }
    }

    private static String getOpenAiResponse(String question, String apiKey, String baseUrl) throws Exception {
        HttpURLConnection connection = null;
        try {
            // 创建连接
            URL url = new URL(baseUrl + "/chat/completions");
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Authorization", "Bearer " + apiKey);
            connection.setDoOutput(true);

            // 构建请求体
            String requestBody = buildRequestBody(question);

            // 发送请求
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = requestBody.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 处理响应
            int statusCode = connection.getResponseCode();
            if (statusCode != 200) {
                return "请求失败: HTTP " + statusCode;
            }

            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                return parseResponse(response.toString());
            }
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    private static String buildRequestBody(String question) {
        JsonObject message = new JsonObject();
        message.addProperty("role", "user");
        message.addProperty("content", question);

        JsonArray messages = new JsonArray();
        messages.add(message);

        JsonObject requestBody = new JsonObject();
        requestBody.addProperty("model", "gpt-4o-mini");
        requestBody.add("messages", messages);

        return requestBody.toString();
    }

    private static String parseResponse(String jsonResponse) throws Exception {
        try {
            JsonObject obj = new JsonParser().parse(jsonResponse).getAsJsonObject();
            JsonArray choices = obj.getAsJsonArray("choices");
            JsonObject firstChoice = choices.get(0).getAsJsonObject();
            return firstChoice.getAsJsonObject("message").get("content").getAsString();
        } catch (JsonSyntaxException e) {
            throw new Exception("JSON解析失败: " + e.getMessage());
        }
    }
}

4. 运行效果

OpenAI-Java示例代码

使用指南工具配置

Gemini-Python示例代码

2025-8-25 11:44:27

工具配置

Dify:开源低代码 AI 应用平台 | 一站式构建与部署

2025-7-25 16:46:45

搜索