专栏名称: 芋道源码
纯 Java 源码分享公众号,目前有「Dubbo」「SpringCloud」「Java 并发」「RocketMQ」「Sharding-JDBC」「MyCAT」「Elastic-Job」「SkyWalking」「Spring」等等
目录
相关文章推荐
专注业绩潜伏  ·  年报业绩预告超预期(2.4) ·  23 小时前  
专注业绩潜伏  ·  年报业绩预告超预期(2.4) ·  23 小时前  
审计芸  ·  云集 ... ·  昨天  
审计芸  ·  云集 ... ·  昨天  
天天财经116  ·  门店仓库“挤满”已售暂存商品, ... ·  2 天前  
天天财经116  ·  门店仓库“挤满”已售暂存商品, ... ·  2 天前  
新黄河  ·  刘国梁建言取消强制参赛政策 ·  3 天前  
新黄河  ·  刘国梁建言取消强制参赛政策 ·  3 天前  
51好读  ›  专栏  ›  芋道源码

SpringBoot封装AI模块,快速实现智能化!

芋道源码  · 公众号  ·  · 2025-02-05 09:53

正文

👉 这是一个或许对你有用的社群

🐱 一对一交流/面试小册/简历优化/求职解惑,欢迎加入芋道快速开发平台知识星球。下面是星球提供的部分资料: 

👉这是一个或许对你有用的开源项目

国产 Star 破 10w+ 的开源项目,前端包括管理后台 + 微信小程序,后端支持单体和微服务架构。

功能涵盖 RBAC 权限、SaaS 多租户、数据权限、商城、支付、工作流、大屏报表、微信公众号、ERPCRMAI 大模型等等功能:

  • Boot 多模块架构:https://gitee.com/zhijiantianya/ruoyi-vue-pro
  • Cloud 微服务架构:https://gitee.com/zhijiantianya/yudao-cloud
  • 视频教程:https://doc.iocoder.cn
【国内首批】支持 JDK 17/21 + SpringBoot 3.3、JDK 8/11 + Spring Boot 2.7 双版本 

来源:blog.csdn.net/hrh1234h
/article/details/144217621


国内支持SDK调用的优秀开源AI平台

  • 智谱AI(ZhipuAI): 智谱AI是一家专注于大模型技术的公司,由清华大学计算机系知识工程实验室技术成果转化而来。智谱AI提供了包括对话模型、视觉模型、代码生成模型等多种AI模型,并提供了开放平台供开发者使用和集成。智谱AI的SDK可以用于快速集成其AI能力,如对话、图像识别等功能。
  • 百度飞桨(PaddlePaddle): 百度飞桨是中国首个开源深度学习平台,提供丰富的API和SDK,支持多种深度学习模型的开发和部署。
  • 腾讯AI Lab: 腾讯AI Lab提供了多种AI技术和服务,包括计算机视觉、语音识别、自然语言处理等领域的SDK和API。
  • 阿里云机器学习平台PAI: 阿里云提供的机器学习平台PAI支持多种机器学习算法和模型,提供了SDK供开发者调用。
  • 华为ModelArts: 华为云ModelArts是一个全流程模型生产服务,提供丰富的API和SDK,支持模型的训练、部署和管理。

注释:本文以智谱AI为例,其他开源AI平台同理

导入依赖

<dependency>
    <groupId>cn.bigmodel.openapigroupId>
    <artifactId>oapi-java-sdkartifactId>
    <version>release-V4-2.3.0version>
dependency>

基于 Spring Boot + MyBatis Plus + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

  • 项目地址:https://github.com/YunaiV/ruoyi-vue-pro
  • 视频教程:https://doc.iocoder.cn/video/

获取API key(注意保密)

官网的个人中心,找到项目管理下的API keys。

基于 Spring Cloud Alibaba + Gateway + Nacos + RocketMQ + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

  • 项目地址:https://github.com/YunaiV/yudao-cloud
  • 视频教程:https://doc.iocoder.cn/video/

测试Demo

测试是否调用AI成功,注意API key要换成自己的。

@SpringBootTest
public class ZhiPuAiTest {
 
    @Test
    public void test() {
        String apiKey = "自己的apikey";
        // 创建客户端
        ClientV4 client = new ClientV4.Builder(apiKey).build();
        // 构造请求
        List messages = new ArrayList<>();
        ChatMessage chatMessage = new ChatMessage(ChatMessageRole.USER.value(), "作为一名营销专家,请为智谱开放平台创作一个吸引人的slogan");
        messages.add(chatMessage);
        String requestId = String.valueOf(System.currentTimeMillis());
        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                .model(Constants.ModelChatGLM4)
                .stream(Boolean.FALSE)
                .invokeMethod(Constants.invokeMethod)
                .messages(messages)
                .requestId(requestId)
                .build();
        // 调用
        ModelApiResponse invokeModelApiResp = client.invokeModelApi(chatCompletionRequest);
        System.out.println("model output:" + invokeModelApiResp.getMsg());
    }
}

封装通用AI模块

application.yml配置API key

#  ai 配置
ai:
  api-key: 自己的key

定义AI配置类

@Configuration
@ConfigurationProperties(prefix = "ai")
@Data
public class AiConfig {
 
    /**
     * apiKey
     */

 
    private String apiKey;
 
    @Bean
    public ClientV4 getClientV4() {
        return new ClientV4.Builder(apiKey).build();
    }
}

封装通用的AI请求模块

AiManager类提供了多种方法来执行同步和流式请求,包括稳定和不稳定答案的同步请求,以及可以根据随机数温度参数自定义的同步请求。这些方法允许以简化的方式传递系统和用户消息,或者直接传递一个消息列表。

/**
 * 通用 AI 调用能力
 */

@Component
public class AiManager {
 
    @Resource
    private ClientV4 clientV4;
 
    // 稳定的随机数
    private static final float STABLE_TEMPERATURE = 0.05f;
 
    // 不稳定的随机数
    private static final float UNSTABLE_TEMPERATURE = 0.99f;
 
    /**
     * 同步请求(答案不稳定)
     *
     * @param systemMessage
     * @param userMessage
     * @return
     */

    public String doSyncUnstableRequest(String systemMessage, String userMessage) {
        return doRequest(systemMessage, userMessage, Boolean.FALSE, UNSTABLE_TEMPERATURE);
    }
 
    /**
     * 同步请求(答案较稳定)
     *
     * @param systemMessage
     * @param userMessage
     * @return
     */

    public String doSyncStableRequest(String systemMessage, String userMessage) {
        return doRequest(systemMessage, userMessage, Boolean.FALSE, STABLE_TEMPERATURE);
    }
 
    /**
     * 同步请求
     *
     * @param systemMessage
     * @param userMessage
     * @param temperature
     * @return
     */

    public String doSyncRequest(String systemMessage, String userMessage, Float temperature) {
        return doRequest(systemMessage, userMessage, Boolean.FALSE, temperature);
    }
 
    /**
     * 通用请求(简化消息传递)
     *
     * @param systemMessage
     * @param userMessage
     * @param stream
     * @param temperature
     * @return
     */

    public String doRequest(String systemMessage, String userMessage, Boolean stream, Float temperature) {
        List chatMessageList = new ArrayList<>();
        ChatMessage systemChatMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), systemMessage);
        chatMessageList.add(systemChatMessage);
        ChatMessage userChatMessage = new ChatMessage(ChatMessageRole.USER.value(), userMessage);
        chatMessageList.add(userChatMessage);
        return doRequest(chatMessageList, stream, temperature);
    }
 
    /**
     * 通用请求
     *
     * @param messages
     * @param stream
     * @param temperature
     * @return
     */

    public String doRequest(List messages, Boolean stream, Float temperature) {
        // 构建请求
        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                .model(Constants.ModelChatGLM4)
                .stream(stream)
                .temperature(temperature)
                .invokeMethod(Constants.invokeMethod)
                .messages(messages)
                .build();
        try {
            ModelApiResponse invokeModelApiResp = clientV4.invokeModelApi(chatCompletionRequest);
            return invokeModelApiResp.getData().getChoices().get(0).toString();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, e.getMessage());
        }
    }
 
    /**
     * 通用流式请求(简化消息传递)
     *
     * @param systemMessage
     * @param userMessage
     * @param temperature
     * @return
     */

    public Flowable doStreamRequest(String systemMessage, String userMessage, Float temperature) {
        List chatMessageList = new ArrayList<>();
        ChatMessage systemChatMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), systemMessage);
        chatMessageList.add(systemChatMessage);
        ChatMessage userChatMessage = new ChatMessage(ChatMessageRole.USER.value(), userMessage);
        chatMessageList.add(userChatMessage);
        return doStreamRequest(chatMessageList, temperature);
    }
 
 
    /**
     * 通用流式请求
     *
     * @param messages
     * @param temperature
     * @return
     */

    public Flowable doStreamRequest(List messages, Float temperature) {
        // 构建请求
        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                .model(Constants.ModelChatGLM4)
                .stream(Boolean.TRUE)
                .temperature(temperature)
                .invokeMethod(Constants.invokeMethod)
                .messages(messages)
                .build();
        try {
            ModelApiResponse invokeModelApiResp = clientV4.invokeModelApi(chatCompletionRequest);
            return invokeModelApiResp.getFlowable();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, e.getMessage());
        }
    }
}

使用AI赋能项目

设计Prompt的常用技巧

Prompt是一种向语言模型提供输入的方法,它通过特定的提示或指令引导模型生成预期的输出。在自然语言处理中,简而言之,Prompt是一种高效利用语言模型能力的技术手段。

  • 技巧一  定义 System Prompt

用于设定AI助手行为模式的工具,包括角色设定、语言风格、任务模式和针对特定问题的具体行为指导。

示例:

你擅长从文本中提取关键信息,精确、数据驱动,重点突出关键信息,根据用户提供的文本片段提取关键数据和事实,将提取的信息以清晰的 JSON 格式呈现。

  • 技巧二  让 AI 进行角色扮演

让 AI 扮演角色、可以更准确地模仿该角色的行为和对话方式。

示例:

作为一个量子物理学家,解释量子物理学的基本原理,并简要介绍其在现代科技中的应用。

  • 技巧三  提供具体的细节要求

在 Prompt 中添加要求模型输出内容的细节和背景信息。

示例:

我对太阳系的行星非常感兴趣,特别是土星。请提供关于土星的基本信息,包括其大小、组成、环系统和任何独特的天文现象。

  • 技巧四  使用分隔符标示不同的输入部分

示例:

请基于以下内容:

""" 要总结的文章内容"""

提炼核心观点和纲要

  • 技巧五  思维链提示

要求模型分步骤解答问题,还要求其展示其推理过程的每个步骤。通过这种方式,可以减少不准确结果的可能性,并使用户更容易评估模型的响应。

示例:

作为一个 AI 助手,你的任务是帮助用户解决复杂的数学问题。对于每个问题,你需要首先独立解决它,然后比较和评估用户的答案,并最终提供反馈。在这个过程中,请展示你的每一步推理过程。我有一个数学问题需要帮助:"""问题是:一个农场有鸡和牛共 35 头,脚总共有 94 只。鸡和牛各有多少头?我的答案是鸡有 23 头,牛有 12 头"""。

  • 技巧六  少样本学习

可以作为进行少样本学习的示例。这些样本可以用来引导模型模仿特定的行为和语言风格。

模仿这种风格

1、三杯鸡在锅中欢跃,是岁月的篝火,是浪漫的乐章。

2、炖排骨的滋味,是冬日的棉被,是乡土的回响。

3、红烧勤鱼的鲜香,是海洋的密语,是大海的情书。

生成新的句子。

项目中调用AI(实战)

  • 定义Prompt常量

参考上文设计Prompt的常用技巧,根据自己的业务需求设计Prompt,示例代码是需要AI生成问卷题目,仅供参考。

// AI Prompt
private static final String GENERATE_QUESTION_SYSTEM_MESSAGE = "你是一位严谨的出题专家,我会给你如下信息:\n" +
        "```\n" +
        "应用名称,\n" +
        "【【【应用描述】】】,\n" +
        "应用类别,\n" +
        "要生成的题目数,\n" +
        "每个题目的选项数\n" +
        "```\n" +
        "\n" +
        "请你根据上述信息,按照以下步骤来出题:\n" +
        "1. 要求:题目和选项尽可能地短,题目不要包含序号,每题的选项数以我提供的为主,题目不能重复\n" +
        "2. 严格按照下面的 json 格式输出题目和选项\n" +
        "```\n" +
        "[{\"options\":[{\"value\":\"选项内容\",\"key\":\"A\"},{\"value\":\"\",\"key\":\"B\"}],\"title\":\"题目标题\"}]\n" +
        "```\n" +
        "title 是题目,options 是选项,每个选项的 key 按照英文字母序(比如 A、B、C、D)以此类推,value 是选项内容\n" +
        "3. 检查题目是否包含序号,若包含序号则去除序号\n" +
        "4. 返回的题目列表格式必须为 JSON 数组";
  • 业务逻辑中调用AI

调用AI,使用定义好的Prompt生成题目

// AI 生成
String result = aiManager.doSyncRequest(GENERATE_QUESTION_SYSTEM_MESSAGE, userMessage, null);

完整代码

/**
 * 生成题目的用户消息
 *
 * @param app
 * @param questionNumber
 * @param optionNumber
 * @return
 */

private String getGenerateQuestionUserMessage(App app, int questionNumber, int optionNumber) {
    StringBuilder userMessage = new StringBuilder();
    userMessage.append(app.getAppName()).append("\n");
    userMessage.append(app.getAppDesc()).append("\n");
    userMessage.append(AppTypeEnum.getEnumByValue(app.getAppType()).getText() + "类").append("\n");
    userMessage.append(questionNumber).append("\n");
    userMessage.append(optionNumber);
    return userMessage.toString();
}

@PostMapping("/ai_generate")
public BaseResponse> aiGenerateQuestion(
        @RequestBody AiGenerateQuestionRequest aiGenerateQuestionRequest) {
    ThrowUtils.throwIf(aiGenerateQuestionRequest == null, ErrorCode.PARAMS_ERROR);
    // 获取参数
    Long appId = aiGenerateQuestionRequest.getAppId();
    int questionNumber = aiGenerateQuestionRequest.getQuestionNumber();
    int optionNumber = aiGenerateQuestionRequest.getOptionNumber();
    // 获取应用信息
    App app = appService.getById(appId);
    ThrowUtils.throwIf(app == null, ErrorCode.NOT_FOUND_ERROR);
    // 封装 Prompt
    String userMessage = getGenerateQuestionUserMessage(app, questionNumber, optionNumber);
    // AI 生成
    String result = aiManager.doSyncRequest(GENERATE_QUESTION_SYSTEM_MESSAGE, userMessage, null);
    // 截取需要的 JSON 信息
    int start = result.indexOf("[");
    int end = result.lastIndexOf("]");
    String json = result.substring(start, end + 1);
    List questionContentDTOList = JSONUtil.toList(json, QuestionContentDTO.class);
    return ResultUtils.success(questionContentDTOList);
}

欢迎加入我的知识星球,全面提升技术能力。

👉 加入方式,长按”或“扫描”下方二维码噢

星球的内容包括:项目实战、面试招聘、源码解析、学习路线。

文章有帮助的话,在看,转发吧。

谢谢支持哟 (*^__^*)