引言:
随着人工智能技术的快速发展,认知大模型如星火在自然语言处理、语音识别等领域发挥着越来越重要的作用。本文将通过一个实际的Java代码示例,详细讲解如何使用Java连接星火认知大模型,并处理其响应。
1.导入依赖:
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.7.16</version></dependency>
2.加载配置
private static final String CONFIG_FILE = "/config.properties";
3.构建http请求
String body = HttpRequest.post(apiUrl).header("Authorization", authHeader).header("Content-Type", "application/json").body(String.valueOf(param)).execute().body();
4.处理API响应
String body = HttpRequest.post(apiUrl).header("Authorization", authHeader).header("Content-Type", "application/json").body(String.valueOf(param)).execute().body();
完整代码如下:
private static final String CONFIG_FILE = "/config.properties";public static void main(String[] args) {String content = "土豆炖马铃薯怎么做?"; // 假设这是从某处获取的输入内容String messageContent = callAPI(content);System.out.println(messageContent); // 输出消息内容}public static String callAPI(String content) {JSONObject message = null;Properties config = new Properties();try {config.load(APIHandler.class.getResourceAsStream(CONFIG_FILE));String apiUrl = config.getProperty("api.url");String authHeader = config.getProperty("authorization.bearer");JSONArray dataList = new JSONArray();JSONObject param = new JSONObject();param.set("model", "general");JSONObject data = new JSONObject();data.set("role", "user");data.set("content", content);dataList.add(data);param.set("messages", dataList);String body = HttpRequest.post(apiUrl).header("Authorization", authHeader).header("Content-Type", "application/json").body(String.valueOf(param)).execute().body();JSONObject result = JSONUtil.parseObj(body);JSONArray choices = result.getJSONArray("choices");if (choices.isEmpty()) {return "API没有返回任何选择";}JSONObject mes = choices.get(0, JSONObject.class, Boolean.TRUE);message = mes.getJSONObject("message");} catch (IOException e) {return "读取配置文件失败";} catch (Exception e) {e.printStackTrace();return "调用API接口失败";}if (message == null) {return "未能获取有效消息";}return message.getStr("content");}
5.测试
Spark List模型是免费的,可以用这个来测试玩一玩;
希望这篇博客能帮助你更好地理解和应用Java中的认知大模型连接。