Spring AI学习 程序接入大模型(框架接入)

终于来到了使用框架来接入大模型,这里我们使用两个流行的框架来接入大模型:

Spring AI:基于 Spring 生态系统的 AI 框架

LangChain4j:专注于构建 LLM 应用的 Java 框架,提供丰富的 AI 调用组件

Spring AI

首先就是我们常见的spring家族的新成员,Spring AI,旨在简化 AI 功能与 Spring 应用的集成。他集成了多种模型和各种AI常用的特性,比如RAG知识库、Tools 工具调用和 MCP 模型上下文协议,简化了AI的应用开发。

话不多说,直接快速开始:

引入依赖

复制代码
<dependency>
    <groupId>com.alibaba.cloud.ai</groupId>
    <artifactId>spring-ai-alibaba-starter</artifactId>
    <version>1.0.0-M6.1</version>
</dependency>

编写配置:

复制代码
spring:
  application:
    name: TT-ai-agent
  ai:
    dashscope:
      api-key: ${DASHSCOPE_API_KEY}
      chat:
        options:
          model: qwen-plus

编写示例代码:

复制代码
@Component
public class SpringAiAiInvoke implements CommandLineRunner {
    @Resource
    private ChatModel dashscopeChatModel;

    @Override
    public void run(String... args) throws Exception {
        AssistantMessage output = dashscopeChatModel.call(new Prompt("你好 我现在正在学习spring ai 你可以给我一些学习建议吗"))
                .getResult().getOutput();
        System.out.println(output.getText());
    }
}

这里简单说一下spring boot中的CommandLineRunner 接口,它是一个函数式接口,用于在Spring Boot应用程序启动后执行一些初始化操作。它提供了一个run方法,该方法在应用程序启动后被调用。

上述代码中我们是通⁠过 ChatModel 对象调用大模型,适合简单‌的对话场景。后续我们会学到ChatClient 调用方式,提供更‎多高级功能,比如会话记忆等,适合复杂的场景。

启动项目:

LangChain4j

同样引入依赖:

复制代码
<dependency>
    <groupId>dev.langchain4j</groupId>
    <artifactId>langchain4j-community-dashscope</artifactId>
    <version>1.0.0-beta2</version>
</dependency>

编写代码:

复制代码
public class Langchain4jAiInvoke {
    public static void main(String[] args) {
        QwenChatModel build = QwenChatModel
                .builder()
                .apiKey("sk-XXXXXXXXXXXXXX").modelName("qwen-max").build();
        String chat = build.chat("hello i am bbtat how are you");
        System.out.println(chat);
    }
}

执行结果:

从上面我们可以发现,使用框架实现程序接入大模型,代码更加整洁,清晰易懂。

相关推荐
触底反弹3 分钟前
🔥 2026 大模型选择指南:别再只看 Benchmark 了,这些维度才是关键!
人工智能·面试
神奇霸王龙21 分钟前
GB/T 46886 闭环屠夫:5 旗舰多模态 LLM 工业质检实测
人工智能·计算机视觉·ai·开源·ai编程·本地部署
南讯股份Nascent39 分钟前
洽洽全域会员项目启动会圆满召开
大数据·人工智能
大郭鹏宇42 分钟前
基于 LangGraph 构建智能分诊系统(一):项目概述与环境搭建
大数据·人工智能·microsoft·langchain
小林ixn1 小时前
大模型的“高考成绩单”:读懂Benchmark,选对真·生产力模型
人工智能·llm·测试
冬奇Lab1 小时前
AI 评测系列(04):RAG 评测——RAGAS 四指标实战与一个反直觉发现
人工智能·llm·agent
三声三视1 小时前
uni-app 鸿蒙端传参变成 [object Object]?顺着源码追到 ArkTS router 底层才搞明白
人工智能·ai·uni-app·aigc·ai编程·harmonyos
fthux2 小时前
“装闭”,让装修套路“装”不下去
人工智能·ai·开源·github·open source
andxe2 小时前
安科士 AndXe 技术博客:400G QSFP112 SR4 光模块|AI 算力与超算短距互联最优方案
网络·人工智能·光模块·光通信
a1117763 小时前
2FA 验证码生成器(github登录验证 app)
笔记·学习