Spring集成Coze智能体

Spring集成Coze智能体实践

在Coze中创建了两个智能体,在Spring项目中进行调用助手的功能

一个是问答机器人,一个是代码助手

问答机器人

在问答机器人智能体中设计人物和回答逻辑

调用了联网问答插件,可以查询实时信息

并且设计一个开场白

测试一下

代码助手

设计人物对话和逻辑

设计开场白

测试一下

进行Spring集成coze中的智能体

配置yml文件,配置自己的token和智能体的rob_id

spring:
  application:
    name: cozeBySpring
coze:
  token: "pat_TBEmOswLwuyOpwpiibua5wXryJllgm63onW0RrniOaB6vXXkMDGQd0vwMOhGRPHr"
  bots:
    answerRabbit: "7570519591101759539"
    codeHelper: "7570521894261293075"

设置controller中接口的调用逻辑

@RestController
@RequestMapping("/ai")
public class CozeController {

    private final CozeService cozeClient;

    public CozeController(CozeService cozeClient) {
        this.cozeClient = cozeClient;
    }

    //  问答机器人
    @GetMapping("/qa")
    public String askQuestion(@RequestParam("q") String q) {
        return cozeClient.askQuestion(q);
    }

    //  代码助手
    @GetMapping("/code")
    public String askCode(@RequestParam("q") String q) {
        return cozeClient.askCodeHelper(q);
    }
}

设计业务逻辑

@Service
public class CozeService {

    private static final Logger logger = LoggerFactory.getLogger(CozeService.class);


    private static final String baseUrl="https://api.coze.cn";

    @Value("${coze.token}")
    private String token;

    @Value("${coze.bots.answerRabbit}")
    private String answerRabbitId;

    @Value("${coze.bots.codeHelper}")
    private String codeHelperId;

    @Autowired
    private RestTemplate restTemplate;


    /**
     * 问答机器人
     * @param question
     * @return
     */
    public String answerRabbit(String question) {
        String url = baseUrl + "/v3/chat";

        Map<String, Object> body = new HashMap<>();
        body.put("bot_id", answerRabbitId);
        body.put("user_id", "spring_user");
        body.put("stream", false);
        body.put("auto_save_history", true);

        // v3版本的消息体为 additional_messages 数组
        List<Map<String, Object>> additionalMessages = new ArrayList<>();
        Map<String, Object> message = new HashMap<>();
        message.put("role", "user");
        message.put("content", question);
        message.put("content_type", "text");
        additionalMessages.add(message);
        body.put("additional_messages", additionalMessages);

        return doRequest(url, body);
    }

    /**
     * 代码助手
     * @param question
     * @return
     */
    public String askCodeHelper(String question) {
        String url = baseUrl + "/v3/chat";

        Map<String, Object> body = new HashMap<>();
        body.put("bot_id", codeHelperId);
        body.put("user_id", "spring_user");
        body.put("stream", false);
        body.put("auto_save_history", true);

        List<Map<String, Object>> additionalMessages = new ArrayList<>();
        Map<String, Object> message = new HashMap<>();
        message.put("role", "user");
        message.put("content", question);
        message.put("content_type", "text");
        additionalMessages.add(message);
        body.put("additional_messages", additionalMessages);

        return doRequest(url, body);
    }

//    通用调用
    private String doRequest(String url, Map<String, Object> body) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "Bearer " + token);
            headers.setContentType(MediaType.APPLICATION_JSON);

            logger.info("请求 URL: {}", url);
            logger.info("请求体: {}", body);

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers);
            ResponseEntity<Map> response = restTemplate.postForEntity(url, entity, Map.class);

            Map<String, Object> respBody = response.getBody();
            logger.info("API 响应: {}", respBody);

            if (respBody == null) {
                logger.error("API 返回为空");
                return "请求失败,API 返回为空";
            }

            // Coze v3 成功返回包含 choices 或 messages 字段
            if (respBody.containsKey("data")) {
                Map<String, Object> data = (Map<String, Object>) respBody.get("data");
                if (data != null && data.containsKey("messages")) {
                    List<Map<String, Object>> messages = (List<Map<String, Object>>) data.get("messages");
                    for (Map<String, Object> msg : messages) {
                        if ("assistant".equals(msg.get("role"))) {
                            return (String) msg.get("content");
                        }
                    }
                }
            }

            // 如果没有找到明确的 assistant 回复
            return "未获取到结果:" + respBody;

        } catch (Exception e) {
            logger.error("调用 Coze API 时发生异常: {}", e.getMessage(), e);
            return "请求失败: " + e.getMessage();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值