Java调用文心一言案例

wen java案例 2

本文目录导读:

Java调用文心一言案例

  1. 准备工作
  2. 完整代码实现
  3. 错误处理
  4. 配置文件示例 (application.properties)
  5. 注意事项

我来为您提供一个完整的Java调用文心一言(ERNIE Bot)API的案例。

准备工作

1 获取API密钥

  1. 访问百度智能云控制台
  2. 创建应用获取API Key和Secret Key
  3. 注意:文心一言API需要先申请开通

2 Maven依赖

<dependencies>
    <!-- HTTP客户端 -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.13</version>
    </dependency>
    <!-- JSON处理 -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>2.0.32</version>
    </dependency>
    <!-- JSON处理(备选) -->
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.10.1</version>
    </dependency>
</dependencies>

完整代码实现

1 文心一言调用客户端

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
/**
 * 文心一言 API 调用客户端
 */
public class WenxinYiyanClient {
    // 配置信息
    private static final String API_KEY = "你的API_KEY";
    private static final String SECRET_KEY = "你的SECRET_KEY";
    // API地址
    private static final String ACCESS_TOKEN_URL = "https://aip.baidubce.com/oauth/2.0/token";
    private static final String CHAT_URL = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro";
    private String accessToken;
    private long expireTime;
    /**
     * 获取访问令牌
     */
    private String getAccessToken() throws IOException {
        // 检查token是否过期
        if (accessToken != null && System.currentTimeMillis() < expireTime) {
            return accessToken;
        }
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String url = ACCESS_TOKEN_URL + "?grant_type=client_credentials" +
                    "&client_id=" + API_KEY +
                    "&client_secret=" + SECRET_KEY;
        HttpPost httpPost = new HttpPost(url);
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            JSONObject jsonObject = JSON.parseObject(responseBody);
            // 设置token和过期时间(提前5分钟过期以确保安全)
            this.accessToken = jsonObject.getString("access_token");
            int expiresIn = jsonObject.getInteger("expires_in");
            this.expireTime = System.currentTimeMillis() + (expiresIn - 300) * 1000;
            return this.accessToken;
        }
    }
    /**
     * 调用文心一言API
     * @param message 用户输入的消息
     * @return 文心一言的回复
     */
    public String chat(String message) throws IOException {
        String token = getAccessToken();
        String url = CHAT_URL + "?access_token=" + token;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        // 设置请求头
        httpPost.setHeader("Content-Type", "application/json");
        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("messages", new Object[]{
            Map.of("role", "user", "content", message)
        });
        // 可选参数
        requestBody.put("temperature", 0.8);
        requestBody.put("top_p", 0.8);
        requestBody.put("penalty_score", 1.0);
        requestBody.put("stream", false);
        String jsonBody = JSON.toJSONString(requestBody);
        httpPost.setEntity(new StringEntity(jsonBody, StandardCharsets.UTF_8));
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            HttpEntity entity = response.getEntity();
            String responseBody = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            JSONObject jsonResponse = JSON.parseObject(responseBody);
            // 检查是否有错误
            if (jsonResponse.containsKey("error_code")) {
                String errorMsg = jsonResponse.getString("error_msg");
                throw new IOException("API调用失败: " + errorMsg);
            }
            // 获取回复内容
            return jsonResponse.getJSONObject("result")
                              .getJSONArray("content")
                              .getJSONObject(0)
                              .getString("content");
        }
    }
    /**
     * 流式调用文心一言API(适用于长对话)
     */
    public void streamChat(String message, MessageCallback callback) throws IOException {
        String token = getAccessToken();
        String url = CHAT_URL + "?access_token=" + token;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json");
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("messages", new Object[]{
            Map.of("role", "user", "content", message)
        });
        requestBody.put("stream", true);
        String jsonBody = JSON.toJSONString(requestBody);
        httpPost.setEntity(new StringEntity(jsonBody, StandardCharsets.UTF_8));
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            // 处理流式响应
            // 实际实现需要读取InputStream并解析SSE格式
            // 这里简化处理,实际使用请参考完整实现
        }
    }
    /**
     * 消息回调接口
     */
    public interface MessageCallback {
        void onMessage(String content);
        void onError(Exception e);
        void onComplete();
    }
}

2 使用示例

import java.io.IOException;
import java.util.Scanner;
/**
 * 文心一言调用示例
 */
public class WenxinYiyanDemo {
    public static void main(String[] args) {
        WenxinYiyanClient client = new WenxinYiyanClient();
        Scanner scanner = new Scanner(System.in);
        System.out.println("=== 文心一言对话测试 ===");
        System.out.println("输入 'exit' 退出程序");
        System.out.println("=" .repeat(40));
        while (true) {
            System.out.print("\n用户: ");
            String input = scanner.nextLine();
            if ("exit".equalsIgnoreCase(input)) {
                System.out.println("再见!");
                break;
            }
            try {
                System.out.println("文心一言: ");
                String response = client.chat(input);
                System.out.println(response);
            } catch (IOException e) {
                System.err.println("调用失败: " + e.getMessage());
            }
        }
        scanner.close();
    }
}

3 高级用法 - 多轮对话

/**
 * 多轮对话示例
 */
public class MultiTurnChat {
    public static void main(String[] args) throws IOException {
        WenxinYiyanClient client = new WenxinYiyanClient();
        // 多轮对话示例
        String[] conversations = {
            "你是谁?",
            "你能做什么?",
            "刚才我问了你什么问题?"
        };
        for (String question : conversations) {
            System.out.println("用户: " + question);
            String response = client.chat(question);
            System.out.println("文心一言: " + response);
            System.out.println("-".repeat(40));
        }
    }
}

错误处理

/**
 * 增强的错误处理示例
 */
public class ErrorHandlingDemo {
    public static void main(String[] args) {
        WenxinYiyanClient client = new WenxinYiyanClient();
        try {
            String response = client.chat("你好");
            System.out.println("回复: " + response);
        } catch (IOException e) {
            System.err.println("网络错误: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("系统错误: " + e.getMessage());
        } finally {
            // 清理资源
        }
    }
}

配置文件示例 (application.properties)

# 文心一言配置
wenxin.api.key=你的API_KEY
wenxin.secret.key=你的SECRET_KEY
wenxin.api.url=https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro
wenxin.access.token.url=https://aip.baidubce.com/oauth/2.0/token
# 模型参数
wenxin.temperature=0.8
wenxin.top_p=0.8
wenxin.penalty_score=1.0
wenxin.max_tokens=2048

注意事项

  1. API配额限制:注意免费额度和调用频率限制
  2. 错误码处理:建议实现完整的错误码处理逻辑
  3. 安全性:API密钥不要硬编码在代码中,建议使用环境变量或配置文件
  4. 超时设置:建议设置合理的连接超时和读取超时时间
  5. 会话管理:多轮对话时注意维护会话上下文

这个示例提供了一个完整的基础实现,您可以根据实际需求进行调整和优化。

抱歉,评论功能暂时关闭!