Spring AI实战应用(1.基础使用)

Spring AI 项目旨在简化开发包含人工智能功能的应用程序,而无需不必要的复杂性。

该项目从著名的 Python 项目中汲取灵感,如 LangChain 和 LlamaIndex,但 Spring AI 并不是这些项目的直接移植。

Spring AI 提供以下功能:

支持所有主要的模型提供商,如 OpenAI、Microsoft、Amazon、Google 和 Huggingface。

支持的模型类型包括聊天和文本到图像,未来将支持更多类型。

跨 AI 提供商的便携式 API,支持同步和流式 API 选项。

将 AI 模型输出映射到 POJO。

支持所有主要向量数据库提供商,如 Azure Vector Search、Chroma、Milvus、Neo4j、PostgreSQL/PGVector、PineCone、Qdrant、Redis 和 Weaviate。

官方文档:https://docs.spring.io/spring-ai/reference/

本文代码示例是基于OpenAI的,有些小伙伴没有网络环境,可以使用我的中转站:https://one.mengxiaofan.top/

更多信息可点击查看

示例中我将使用中转站

文中示例jdk版本为jdk17,springboot版本为3.2.5

废话不多说直接贴maven信息

<properties>
    <java.version>17</java.version>
    <spring-ai.version>0.8.1</spring-ai.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-json</artifactId>
        <version>5.8.27</version>
    </dependency>

</dependencies>

1.1 修改配置文件 修改此项目的application.yml配置文件,核心配置如下

spring:
  ai:
    openai:
      api-key: xxxx
      base-url: https://one.mengxiaofan.top/  #这个是我中转站的地址 如果你有接口或者有网络环境这个要换掉

1.2 写一个最简单的调用

    @GetMapping("/ai/completion")
    public ChatResponse completion(@RequestParam(value = "message", defaultValue = "The vibrant city skyline shimmered with a myriad of lights as the sun set, casting a warm glow on the bustling streets below.") String message) {
        PromptTemplate promptTemplate = new PromptTemplate("把给定的英语句子译成中文 {query}");
        Prompt prompt = promptTemplate.create(Map.of("query", message));
        return chatClient.call(prompt);
    }

效果如图所示:

1722132944621.png

1.3 流式调用

@GetMapping("/ai/stream")
public SseEmitter stream(HttpServletResponse response) {
    response.setContentType("text/event-stream");
    response.setCharacterEncoding("UTF-8");
    SseEmitter emitter = new SseEmitter();
    String systemPrompt = "{prompt}";
    SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemPrompt);
    String userPrompt = "淄博有什么特产?";
    Message userMessage = new UserMessage(userPrompt);
    Message systemMessage = systemPromptTemplate.createMessage(Map.of("prompt", "you are a helpful AI assistant"));
    Prompt prompt = new Prompt(List.of(userMessage, systemMessage));
    chatClient.stream(prompt).subscribe(x -> {
        try {
            List<Generation> generations = x.getResults();
            if (!CollectionUtils.isEmpty(generations)) {
                for (Generation generation : generations) {
                    AssistantMessage assistantMessage = generation.getOutput();
                    String content = assistantMessage.getContent();
                    if (StringUtils.isNotEmpty(content)) {
                        emitter.send(content);
                    } else {
                        if (StringUtils.equals(content, "null"))
                            emitter.complete();
                    }
                }
            }
        } catch (Exception e) {
            emitter.complete();
            e.printStackTrace();
        }
    });
    return emitter;
}

效果是这样的

1722133023230.png

简单使用先到这里,后面会持续更新,连续对话,文档对话以及知识库等等

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值