对接前需要获取token

不会的看下对接工作流中的内容
智能体创建自己找资料把 这里略过
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
这里需要记住botId

调用

相比工作流 这里稍微复杂一颠

  1. 调用v3/chat API创建对话
  2. 轮询v3/chat/retrieve API,直到状态变为completed
  3. 调用v3/chat/message/list API获取最终结果
    额外的 调用时建议采用异步方式
 /**
     * 第一步:调用v3/chat API创建对话
     * 第二步:轮询v3/chat/retrieve API,直到状态变为completed
     * 第三步:调用v3/chat/message/list API获取最终结果
     */
    public static String checkFS(List<String> fileUrl){
        // 记录开始时间
        long startTime = System.currentTimeMillis();
        String conversationId = null;
        String chatId = null;

        // 创建HttpRequestConfig对象并设置超时时间
        int time = 1000 * 60 * 3;//3分钟
        HttpConfig config = new HttpConfig();
        config.setConnectionTimeout(time); // 设置连接超时时间
        config.setReadTimeout(time); // 设置读取超时时间

        try {
            log.info("COZE AI 调用智能体API v3");

            // 第一步:调用v3/chat API创建对话
            log.info("COZE AI 第一步:调用v3/chat API创建对话");

            // 构建文件URL列表,为每个URL添加时间戳
            String fileUrlsText = fileUrl.stream().map((i) -> "\"" + i + "?_t=" + System.currentTimeMillis() + "\"").collect(Collectors.joining(","));

            log.info("COZE AI 上传文件地址>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n{}", fileUrlsText);

            // 构建请求体,使用v3版本的格式
            JSONObject requestBody = new JSONObject();
            requestBody.put("bot_id", botId); // 智能体ID
            requestBody.put("user_id", "123"); // 用户ID
            requestBody.put("stream", false); // 非流式返回

            // 构建additional_messages数组,根据参考资料格式
            JSONArray additionalMessages = new JSONArray();
            JSONObject userMessage = new JSONObject();
            //userMessage.put("content", "请分析以下文件:" + fileUrlsText);
            userMessage.put("content", fileUrlsText);
            userMessage.put("content_type", "text");
            userMessage.put("role", "user");
            userMessage.put("type", "question");
            additionalMessages.add(userMessage);

            requestBody.put("additional_messages", additionalMessages);
            requestBody.put("parameters", new JSONObject());

            String bodyStr = requestBody.toJSONString();
            log.info("COZE AI 智能体请求体>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n{}", bodyStr);

            // 调用v3/chat API
            String chatResult = HttpRequest.post("https://api.coze.cn/v3/chat")
                    .header("Authorization", authToken)
                    .header("Content-Type", "application/json")
                    .body(bodyStr)
                    .setConfig(config)
                    .execute().body();

            log.info("COZE AI 智能体响应>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n{}", chatResult);

            // 解析响应
            JSONObject chatResponse = JSONObject.parseObject(chatResult);
            if(!chatResponse.getInteger("code").equals(0)) {
                log.error("COZE AI 智能体调用失败: {}", chatResponse.getString("msg"));
                throw new RuntimeException("COZE AI 智能体调用失败: " + chatResponse.getString("msg"));
            }

            // 获取conversation_id和chat_id
            JSONObject chatData = chatResponse.getJSONObject("data");
            if (chatData == null) {
                throw new IllegalArgumentException("智能体响应中data字段不存在");
            }

            conversationId = chatData.getString("conversation_id");
            chatId = chatData.getString("id");

            log.info("COZE AI 获取到conversation_id: {}, chat_id: {}", conversationId, chatId);

            // 第二步:轮询v3/chat/retrieve API,直到状态变为completed
            log.info("COZE AI 第二步:轮询v3/chat/retrieve API");
            String status = "";
            int maxRetries = 60; // 最大重试次数
            int retryCount = 0;
            int waitTime = 1000*10; // 每次等待

            while (retryCount < maxRetries) {
                // 构建轮询请求
                String retrieveUrl = "https://api.coze.cn/v3/chat/retrieve?conversation_id=" + conversationId + "&chat_id=" + chatId;
                String retrieveResult = HttpRequest.get(retrieveUrl)
                        .header("Authorization", authToken)
                        .header("Content-Type", "application/json")
                        .setConfig(config)
                        .execute().body();

                log.info("COZE AI 轮询响应 ({}): {}", retryCount + 1, retrieveResult);

                JSONObject retrieveResponse = JSONObject.parseObject(retrieveResult);
                if(!retrieveResponse.getInteger("code").equals(0)) {
                    log.error("COZE AI 轮询失败: {}", retrieveResponse.getString("msg"));
                    throw new RuntimeException("COZE AI 轮询失败: " + retrieveResponse.getString("msg"));
                }

                JSONObject retrieveData = retrieveResponse.getJSONObject("data");
                status = retrieveData.getString("status");
                log.info("COZE AI 当前状态: {}", status);

                if ("completed".equals(status)) {
                    break; // 状态完成,退出轮询
                } else if ("failed".equals(status)) {
                    throw new RuntimeException("智能体处理失败");
                }

                // 等待一段时间后重试
                Thread.sleep(waitTime);
                retryCount++;
            }

            if (!"completed".equals(status)) {
                throw new RuntimeException("智能体处理超时");
            }

            // 第三步:调用v3/chat/message/list API获取最终结果
            log.info("COZE AI 第三步:调用v3/chat/message/list API获取最终结果");

            String messageListUrl = "https://api.coze.cn/v3/chat/message/list?conversation_id=" + conversationId + "&chat_id=" + chatId;
            String messageListResult = HttpRequest.get(messageListUrl)
                    .header("Authorization", authToken)
                    .header("Content-Type", "application/json")
                    .setConfig(config)
                    .execute().body();

            log.info("COZE AI 消息列表响应: {}", messageListResult);

            JSONObject messageListResponse = JSONObject.parseObject(messageListResult);
            if(!messageListResponse.getInteger("code").equals(0)) {
                log.error("COZE AI 获取消息列表失败: {}", messageListResponse.getString("msg"));
                throw new RuntimeException("COZE AI 获取消息列表失败: " + messageListResponse.getString("msg"));
            }

            // 解析消息列表,查找智能体回复
            JSONArray messages = messageListResponse.getJSONArray("data");
            if (messages == null || messages.isEmpty()) {
                throw new IllegalArgumentException("消息列表为空");
            }

            // 查找智能体回复(type为answer的消息)
            JSONObject answerMessage = null;
            for (int i = messages.size() - 1; i >= 0; i--) {
                JSONObject message = messages.getJSONObject(i);
                if (message != null && "answer".equals(message.getString("type"))) {
                    answerMessage = message;
                    break;
                }
            }

            if (answerMessage == null) {
                throw new IllegalArgumentException("未找到智能体回复消息");

            }
            // 获取智能体回复内容
            String text = answerMessage.getString("content");
            if (text == null) {
                throw new IllegalArgumentException("智能体回复内容为空");
            }
            log.info("COZE AI 消息最终响应: {}", text);
            // 记录运行时间
            long duration = System.currentTimeMillis() - startTime;
            log.info("COZE AI 智能体调用总时间: " + duration/1000 + " 秒");

            return text;

        } catch (Exception e) {
            log.error("COZE AI 智能体调用错误>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n{}", e);
            log.error("COZE AI 智能体调用错误>>>>>>>>>>>>>>>>>conversationId>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n{}", conversationId);
            log.error("COZE AI 智能体调用错误>>>>>>>>>>>>>>>>>chatId>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n{}", chatId);
            throw new RuntimeException("COZE AI 智能体调用错误: " + e.getMessage());
        }
    }

异步调用:

                // 异步调用智能体,避免阻塞主流程
                CompletableFuture.runAsync(() -> {
                    try {
                        // 调用智能体,捕获所有异常,确保后续逻辑能继续执行
                        String aiResult = CozeUtils.checkFS(reviewProposalVo.getFileUrls());

                        // 创建ReviewProposal对象用于更新,避免持有原对象引用导致内存泄漏
                        ReviewProposal updateProposal = new ReviewProposal();
                        updateProposal.setProposalId(proposalId);
                        updateProposal.setAiContent(aiResult);
                        // 更新数据库
                        proposalService.updateById(updateProposal);
                    } catch (Exception e) {
                        log.error("调用智能体失败,proposalId: {}", proposalId, e);
                    }
                }, new ThreadPoolExecutor(
                        1, // 核心线程数
                        5, // 最大线程数
                        60L, TimeUnit.SECONDS, // 空闲线程存活时间
                        new ArrayBlockingQueue<>(10), // 工作队列
                        new ThreadFactory() {
                            private final AtomicInteger threadNumber = new AtomicInteger(1);
                            @Override
                            public Thread newThread(Runnable r) {
                                Thread t = new Thread(r, "review-proposal-ai-" + threadNumber.getAndIncrement());
                                t.setDaemon(true); // 设置为守护线程,避免内存泄漏
                                return t;
                            }
                        },
                        new ThreadPoolExecutor.AbortPolicy() // 拒绝策略
                ));
Logo

中国智能体开发者社区,聚焦智能体与大模型开发,提供前沿资讯、实用工具链、开源项目及行业案例。通过技术沙龙、开发者大赛等活动,促进经验交流与协作,助力开发者快速构建创新智能应用。

更多推荐