1.先到阿里云平台开头阿里云白炼账号,创建apiKey

2. 引入maven依赖

<dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>dashscope-sdk-java</artifactId>
                <version>2.8.3</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/io.projectreactor/reactor-core -->
            <dependency>
                <groupId>io.projectreactor</groupId>
                <artifactId>reactor-core</artifactId>
                <version>3.6.0</version>
            </dependency>

3.调用通义api

  String content ;
        // 构建消息对象
        try{
            Message message = Message.builder().role(Role.USER.getValue()).content(question.toString()).build();

            // 构建通义千问参数对象
            GenerationParam param = GenerationParam.builder()
                    .model(Generation.Models.QWEN_PLUS)
                    .messages(Collections.singletonList(message))
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    .topP(0.8)
                    .apiKey(apiKey)//正式
//                    .apiKey("sk-86fadc62eeaf4e3a9a24b55925b9a80d")//正式
//                .apiKey("sk-6f335e7853a64e3e9b8384e338d22e50")//测试
                    .build();


            GenerationResult result = new Generation().call(param);

            // 获取生成的内容
            content = result.getOutput().getChoices().get(0).getMessage().getContent();

            // 设置响应内容类型
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");

            // 构建成功响应
            Map<String, Object> successMap = new HashMap<>();
            successMap.put("data", content);
            response.getWriter().write(objectMapper.writeValueAsString(successMap));
        } catch (Exception e) {
            throw new ServiceException(GlobalErrorCodeConstants.NOT_FOUND.getCode(), "调用AI接口异常:"+e.getMessage());
        }
        return content;

pipost测试接口返回:

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐