Spring AI Alibaba集成阿里云百炼大模型应用

阿里云百炼推出的智能体应用工作流应用智能体编排应用,有效解决了大模型在处理私有领域问题、获取最新信息、遵循固定流程以及自动规划复杂项目等方面的局限,显著拓展了其应用范围。

Spring AI Alibaba框架

1.准备工作

  1. 登录阿里百炼平台,新建一个appkey,然后创建一个智能体应用,获取一个appId
  2. 开发环境:JDK17+、SpringBoot3.x+

2.引入maven依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.8</version>
    </parent>

    <groupId>com.linging</groupId>
    <artifactId>spring-ai-alibaba</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud.ai</groupId>
            <artifactId>spring-ai-alibaba-starter</artifactId>
            <version>1.0.0-M5.1</version>
        </dependency>

    </dependencies>

</project>

3.application.yml

spring:
  ai:
    dashscope:
      agent:
        app-id: xxxx # 大模型应用ID,需要在平台发布(创建时会指定使用的模型)
      api-key: xxxx # 百炼API Key
      workspace-id: xxxx # 业务空间ID,可选,未配置时使用主账号空间

4.调用

4.1.非流式调用

/**
 * 非流式调用
 */
@RestController
@RequestMapping("/ai")
public class BailianAgentRagController {
    private static final Logger logger = LoggerFactory.getLogger(BailianAgentRagController.class);
    private DashScopeAgent agent;

    @Value("${spring.ai.dashscope.agent.app-id:xxx}")
    private String appId;

    public BailianAgentRagController(DashScopeAgentApi dashscopeAgentApi) {
        this.agent = new DashScopeAgent(dashscopeAgentApi);
    }

    @GetMapping("/bailian/agent/call")
    public String call(@RequestParam(value = "message",
            defaultValue = "如何使用SDK快速调用阿里云百炼的应用?") String message) {
        ChatResponse response = agent.call(new Prompt(message, DashScopeAgentOptions.builder().withAppId(appId).build()));
        if (response == null || response.getResult() == null) {
            logger.error("chat response is null");
            return "chat response is null";
        }

        AssistantMessage app_output = response.getResult().getOutput();
        return app_output.getContent();
    }
}

4.2.流式调用

/**
 * 流式调用
 */
@RestController
@RequestMapping("/ai")
public class BailianAgentRagStreamController {
    private static final Logger logger = LoggerFactory.getLogger(BailianAgentRagStreamController.class);
    private DashScopeAgent agent;

    @Value("${spring.ai.dashscope.agent.app-id:xxx}")
    private String appId;

    public BailianAgentRagStreamController(DashScopeAgentApi dashscopeAgentApi) {
        this.agent = new DashScopeAgent(dashscopeAgentApi,
				DashScopeAgentOptions.builder()
						.withSessionId("current_session_id")
						.withIncrementalOutput(true)
						.withHasThoughts(true)
						.build());
    }

    @GetMapping(value="/bailian/agent/stream", produces="text/event-stream;charset=utf-8")
    public Flux<String> stream(@RequestParam(value = "message",
              defaultValue = "你好,请问你的知识库文档主要是关于什么内容的?") String message, HttpServletResponse re) {
        re.setContentType("text/event-stream;charset=utf-8");
        return agent.stream(new Prompt(message, DashScopeAgentOptions.builder().withAppId(appId).build())).map(response -> {
    	    if (response == null || response.getResult() == null) {
                  logger.error("chat response is null");
    		return "chat response is null";
    	    }
    
    	    AssistantMessage app_output = response.getResult().getOutput();
    	    String content = app_output.getContent();
    
    	    return content;
          });
    }

    @GetMapping(value="/bailian/agent/stream/html", produces="text/html;charset=utf-8")
    public Flux<String> streamHtml(@RequestParam(value = "message",
            defaultValue = "你好,请问你的知识库文档主要是关于什么内容的?") String message) {
        return agent.stream(new Prompt(message, DashScopeAgentOptions.builder().withAppId(appId).build())).map(response -> {
            if (response == null || response.getResult() == null) {
                logger.error("chat response is null");
                return "chat response is null";
            }

            AssistantMessage app_output = response.getResult().getOutput();
            String content = app_output.getContent();

            return content;
        });
    }
}
### SpringAI 中配置百炼 RAG 的教程 在 SpringAI 平台中集成百炼 Retrieval-Augmented Generation (RAG),可以通过 DashScope 提供的相关接口实现。以下是详细的配置方法以及示例代码。 #### 配置环境 为了成功运行基于 SpringAI百炼 RAG 的应用,需确保已安装必要的依赖库并完成 API 密钥的设置。具体操作如下: 1. 安装 `dashscope` Python SDK 库以便调用相关服务[^1]。 ```bash pip install dashscope ``` 2. 设置 API Key,在程序启动前通过环境变量或者直接编码的方式加载密钥。 ```python import os os.environ['DASHSCOPE_API_KEY'] = 'your_api_key_here' ``` #### 创建 ChatOptions 实例 根据官方文档中的描述,DashScope 提供了一个名为 `ChatOptions` 的类用于自定义对话行为参数。这些选项可以用来指定检索增强功能的行为模式,例如启用或禁用 RAG 功能、调整上下文长度等。 下面是一个简单的例子展示如何创建带有 RAG 支持的 `ChatOptions` 对象: ```python from dashscope.api_entities.dashscope_response import Response from dashscope.chat_options import ChatOptions, KnowledgeBaseConfig chat_options = ChatOptions( knowledge_base=KnowledgeBaseConfig(enable=True), max_tokens=500, temperature=0.7 ) ``` 在此段代码里设置了知识库查询开关为开启状态 (`enable=True`) 同时还设定了最大返回 token 数量与随机度调节因子两个重要属性值分别为 500 及 0.7。 #### 调用模型进行交互 当完成了上述准备工作之后就可以利用所构建好的 chat options 来发起请求并与大语言模型展开交流互动了。这里给出一段完整的样例演示整个流程: ```python import dashscope response = dashscope.Generation.call( model='qwen-max', messages=[{'role': 'user', 'content': '你好'}, {'role': 'assistant'}], options=chat_options ) if response.status_code == 200: print(response.output.text) else: print('Error:', response.code, response.message) ``` 以上就是有关于如何在 spring ai 当中去配置来自阿里云百练 rag 技术的一个基本指南及其对应的实际运用案例分享。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值