返回

Spring AI Alibaba 功能全景与 Demo 指南

Spring AI Alibaba 功能全景与 Demo 指南

基于 spring-ai-alibaba 开源项目 (https://github.com/alibaba/spring-ai-alibaba)
版本: 1.0.0.2+ | JDK 17+ | Spring Boot 3.x


一、项目概览

Spring AI Alibaba 是阿里巴巴开源的 AI Agent 应用开发框架,基于 Spring AI 构建,深度集成阿里云通义系列模型及百炼平台服务。核心目标是让 Java 开发者能像开发普通 Spring Boot 应用一样开发 AI 应用。

1.1 生态架构 (三层设计)

┌─────────────────────────────────────────────────────────┐
│  Agent Framework (智能体框架层)                          │
│  ReactAgent / SequentialAgent / ParallelAgent /          │
│  RoutingAgent / LoopAgent                               │
├─────────────────────────────────────────────────────────┤
│  Graph Runtime (图运行时层)                              │
│  StateGraph / Node / Edge / OverAllState               │
├─────────────────────────────────────────────────────────┤
│  Augmented LLM (增强大模型层)                             │
│  ChatModel / Tool / MCP / VectorStore / Message         │
└─────────────────────────────────────────────────────────┘

1.2 核心模块

| 模块 | 坐标 | 说明 |
|---|---|---|
| spring-ai-alibaba-starter-dashscope | com.alibaba.cloud.ai | 阿里云百炼模型适配 (ChatClient / ChatModel) |
| spring-ai-alibaba-graph-core | com.alibaba.cloud.ai | 状态图工作流引擎 (StateGraph) |
| spring-ai-alibaba-agent-framework | com.alibaba.cloud.ai | 多智能体框架 (ReactAgent 等) |
| spring-ai-alibaba-starter-memory | com.alibaba.cloud.ai | 会话记忆组件 |
| spring-ai-alibaba-starter-nl2sql | com.alibaba.cloud.ai | 自然语言转 SQL |
| spring-ai-alibaba-starter-nacos-mcp-client | com.alibaba.cloud.ai | Nacos MCP 客户端 (A2A 通信) |
| spring-ai-alibaba-starter-nacos-mcp-server | com.alibaba.cloud.ai | Nacos MCP 服务端 |
| spring-ai-alibaba-starter-nacos-prompt | com.alibaba.cloud.ai | Nacos Prompt 管理 |
| spring-ai-alibaba-starter-arms-observation | com.alibaba.cloud.ai | ARMS 可观测性 |


二、依赖管理最佳实践

所有组件版本通过 BOM 统一管理。

<properties>
    <spring-ai.version>1.0.0</spring-ai.version>
    <spring-ai-alibaba.version>1.1.2.1</spring-ai-alibaba.version>
    <spring-boot.version>3.4.5</spring-boot.version>
</properties>

<repositories>
    <repository>
        <id>spring-milestones</id>
        <url>https://repo.spring.io/milestone</url>
    </repository>
</repositories>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.alibaba.cloud.ai</groupId>
            <artifactId>spring-ai-alibaba-bom</artifactId>
            <version>${spring-ai-alibaba.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>${spring-boot.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-bom</artifactId>
            <version>${spring-ai.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <!-- 基础: ChatClient + DashScope -->
    <dependency>
        <groupId>com.alibaba.cloud.ai</groupId>
        <artifactId>spring-ai-alibaba-starter-dashscope</artifactId>
    </dependency>
</dependencies>

三、核心功能与 Demo

3.1 ChatClient — 基础对话

功能: 最简单的 LLM 对话能力,注入 ChatClient 即可与通义模型对话。

依赖:

<dependency>
    <groupId>com.alibaba.cloud.ai</groupId>
    <artifactId>spring-ai-alibaba-starter-dashscope</artifactId>
</dependency>

配置 (application.yml):

spring:
  ai:
    dashscope:
      api-key: ${AI_DASHSCOPE_API_KEY}

Demo — 简单对话:

@RestController
@RequestMapping("/helloworld")
public class HelloworldController {

    private final ChatClient chatClient;

    public HelloworldController(ChatClient.Builder chatClientBuilder) {
        this.chatClient = chatClientBuilder
                .defaultSystem("你是一个博学的智能聊天助手,请根据用户提问回答!")
                .defaultAdvisors(new SimpleLoggerAdvisor())
                .build();
    }

    @GetMapping("/simple/chat")
    public String simpleChat(@RequestParam(value = "query", defaultValue = "你好") String query) {
        return chatClient.prompt()
                .user(query)
                .call()
                .content();
    }
}

Demo — 流式响应:

@GetMapping(value = "/stream/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> streamChat(@RequestParam String query) {
    return chatClient.prompt()
            .user(query)
            .stream()
            .content();
}

3.2 ChatMemory — 多轮会话记忆

功能: 支持多轮连续对话,通过对话 ID 维护上下文。

依赖: 同 3.1 (ChatClient 内置支持)

Demo — 带记忆的对话:

@RestController
@RequestMapping("/memory")
public class ChatMemoryController {

    private final ChatClient chatClient;

    public ChatMemoryController(ChatClient.Builder chatClientBuilder) {
        this.chatClient = chatClientBuilder
                .defaultSystem("你是一个专业的技术顾问。")
                .defaultAdvisors(
                        // 基于内存的对话记忆
                        new MessageWindowChatMemoryAdvisor("memory"),
                        new SimpleLoggerAdvisor()
                )
                .build();
    }

    @GetMapping("/chat")
    public String chat(
            @RequestParam String query,
            @RequestParam(defaultValue = "default-user") String chatId) {
        return chatClient.prompt()
                .user(query)
                .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, chatId))
                .call()
                .content();
    }
}

Demo — MySQL 持久化记忆 (spring-ai-alibaba-starter-memory):

@Configuration
public class ChatMemoryConfig {

    @Bean
    public ChatMemory chatMemory(JdbcTemplate jdbcTemplate) {
        return new JdbcChatMemoryAdvisor(jdbcTemplate);
    }
}

@RestController
@RequestMapping("/persistent")
public class PersistentMemoryController {

    private final ChatClient chatClient;

    public PersistentMemoryController(ChatClient.Builder chatClientBuilder, ChatMemory chatMemory) {
        this.chatClient = chatClientBuilder
                .defaultSystem("你是用户的私人助理。")
                .defaultAdvisors(
                        new MessageWindowChatMemoryAdvisor(chatMemory),
                        new SimpleLoggerAdvisor()
                )
                .build();
    }

    @GetMapping("/chat")
    public String chat(@RequestParam String query,
                       @RequestParam(defaultValue = "user-001") String chatId) {
        return chatClient.prompt()
                .user(query)
                .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, chatId))
                .call()
                .content();
    }
}

3.3 Tool Calling — 函数调用

功能: 让 LLM 调用外部工具(如搜索、数据库查询、API 调用),实现 ReAct 推理-行动模式。

依赖:

<!-- 基础工具调用 (不需要额外依赖) -->
<!-- 使用 Spring AI 内置 @Tool 注解 -->

<!-- 社区扩展工具 (可选) -->
<dependency>
    <groupId>com.alibaba.cloud.ai</groupId>
    <artifactId>spring-ai-alibaba-starter-tool-calling-baidu-search</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba.cloud.ai</groupId>
    <artifactId>spring-ai-alibaba-starter-tool-calling-github</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba.cloud.ai</groupId>
    <artifactId>spring-ai-alibaba-starter-tool-calling-dingtalk</artifactId>
</dependency>

Demo — 自定义 Tool:

// Step 1: 定义工具
public class WeatherService {

    @Tool(description = "查询指定城市的当前天气")
    public String getWeather(@ToolParam(description = "城市名称") String city) {
        // 实际项目中调用天气 API
        return city + "今天天气晴朗,气温 22-28°C,适宜出行。";
    }
}

// Step 2: 注册工具并使用
@Configuration
public class ToolConfig {

    @Bean
    public FunctionCallbackWrapper weatherFunction() {
        return FunctionCallbackWrapper.builder(new WeatherService())
                .withName("getWeather")
                .withDescription("查询城市天气")
                .build();
    }
}

// Step 3: Controller 中调用
@RestController
@RequestMapping("/tool")
public class ToolController {

    private final ChatClient chatClient;

    public ToolController(ChatClient.Builder chatClientBuilder) {
        this.chatClient = chatClientBuilder
                .defaultSystem("你是一个天气助手,当用户询问天气时,调用工具获取真实数据。")
                .defaultAdvisors(new SimpleLoggerAdvisor())
                .build();
    }

    @GetMapping("/chat")
    public String chat(@RequestParam String query) {
        return chatClient.prompt()
                .user(query)
                .functions("getWeather")
                .call()
                .content();
    }
}

配置选项:

spring:
  ai:
    dashscope:
      chat:
        options:
          model: qwen-max          # 通义模型
          temperature: 0.7          # 创造性 (0-1)
          top-p: 0.8               # 核采样
          max-tokens: 1000         # 最大 Token 数

3.4 MCP (Model Context Protocol) — 模型上下文协议

功能: 标准化的工具/上下文协议,支持 MCP Server 发布和 MCP Client 调用。可将本地文件、数据库等作为 AI 的工具。

依赖:

<!-- MCP Server -->
<dependency>
    <groupId>com.alibaba.cloud.ai</groupId>
    <artifactId>spring-ai-alibaba-starter-nacos-mcp-server</artifactId>
</dependency>
<!-- MCP Client -->
<dependency>
    <groupId>com.alibaba.cloud.ai</groupId>
    <artifactId>spring-ai-alibaba-starter-nacos-mcp-client</artifactId>
</dependency>

Demo — MCP Server (发布工具):

// 定义 MCP 工具 (类似 FunctionCallback)
@Component
public class FileSystemMcpTool {

    @Tool(description = "读取本地文件内容")
    public String readFile(@ToolParam(description = "文件路径") String path) {
        try {
            return Files.readString(Path.of(path));
        } catch (IOException e) {
            return "读取文件失败: " + e.getMessage();
        }
    }

    @Tool(description = "搜索文件")
    public List<String> searchFiles(
            @ToolParam(description = "目录路径") String dir,
            @ToolParam(description = "文件名模式") String pattern) {
        try {
            return Files.walk(Path.of(dir))
                    .filter(p -> p.getFileName().toString().contains(pattern))
                    .map(Path::toString)
                    .toList();
        } catch (IOException e) {
            return List.of("搜索失败: " + e.getMessage());
        }
    }
}

// 注册为 MCP Server
@Configuration
@EnableMcpServer
public class McpServerConfig {

    @Bean
    public SimpleMcpToolProvider fileSystemToolProvider(FileSystemMcpTool tool) {
        return new SimpleMcpToolProvider(List.of(tool));
    }
}

Demo — MCP Client (消费工具):

spring:
  ai:
    alibaba:
      agent:
        proxy:
          nacos:
            server-addr: 127.0.0.1:8848
            username: nacos
            password: nacos
@RestController
@RequestMapping("/mcp")
public class McpClientController {

    private final ChatClient chatClient;

    public McpClientController(ChatClient.Builder chatClientBuilder) {
        this.chatClient = chatClientBuilder
                .defaultSystem("你可以使用 MCP 工具访问外部系统和数据。")
                .defaultAdvisors(new SimpleLoggerAdvisor())
                .build();
    }

    @GetMapping("/chat")
    public String chat(@RequestParam String query) {
        return chatClient.prompt()
                .user(query)
                .tools("weather", "file-read", "github-repo") // 引用 MCP 工具名
                .call()
                .content();
    }
}

3.5 RAG (Retrieval-Augmented Generation) — 检索增强生成

功能: 将知识库内容向量化存储,查询时检索相关片段注入 LLM 上下文,提升回答准确性。

依赖:

<!-- 文档解析 -->
<dependency>
    <groupId>com.alibaba.cloud.ai</groupId>
    <artifactId>spring-ai-alibaba-starter-document-reader-basic</artifactId>
</dependency>
<!-- 向量存储 (百炼 / OpenSearch / Milvus / PGVector) -->
<dependency>
    <groupId>com.alibaba.cloud.ai</groupId>
    <artifactId>spring-ai-alibaba-starter-vector-store-bailian</artifactId>
</dependency>

Demo — 基础 RAG:

// Step 1: 文档加载与分块
@Service
public class DocumentService {

    @Autowired private DocumentReader pdfReader;
    @Autowired private EmbeddingModel embeddingModel;
    @Autowired private VectorStore vectorStore;

    public void loadDocument(Path filePath) {
        // 读取文档
        Document document = pdfReader.read(filePath);

        // 分块 (每 500 字符为一块,重叠 50 字符)
        List<Document> chunks = new TextDocumentSplitter(500, 50)
                .split(document);

        // 存入向量数据库
        vectorStore.add(chunks);
    }
}

// Step 2: RAG 查询
@RestController
@RequestMapping("/rag")
public class RagController {

    private final ChatClient chatClient;
    private final VectorStore vectorStore;

    public RagController(ChatClient.Builder chatClientBuilder, VectorStore vectorStore) {
        this.chatClient = chatClientBuilder
                .defaultSystem("你是一个知识库问答助手,基于提供的上下文回答问题。")
                .defaultAdvisors(new SimpleLoggerAdvisor())
                .build();
        this.vectorStore = vectorStore;
    }

    @GetMapping("/chat")
    public String chat(@RequestParam String query) {
        // 1. 检索相关文档
        List<Document> docs = vectorStore.similaritySearch(query);

        // 2. 构建上下文
        String context = docs.stream()
                .map(Document::getContent)
                .collect(Collectors.joining("\n---\n"));

        // 3. 带上下文的查询
        return chatClient.prompt()
                .user("根据以下上下文回答问题。\n上下文:\n" + context
                        + "\n\n问题: " + query)
                .call()
                .content();
    }
}

配置 (百炼知识库):

spring:
  ai:
    dashscope:
      embedding:
        options:
          model: text-embedding-v3

3.6 ImageModel — 图片生成

功能: 通过 DashScope 模型生成图片 (文生图)。

依赖: 同 3.1

Demo — 图片生成:

@RestController
@RequestMapping("/image")
public class ImageController {

    private final ImageModel imageModel;

    public ImageController(DashScopeImageModel imageModel) {
        this.imageModel = imageModel;
    }

    @GetMapping("/generate")
    public String generateImage(@RequestParam String prompt) {
        ImageResponse response = imageModel.call(
                new ImagePrompt(prompt,
                        DashScopeImageOptions.builder()
                                .model(DashScopeImageModel.DEFAULT_MODEL)
                                .withSize(1024, 1024)
                                .withN(1)
                                .build())
        );

        // 返回图片 URL
        return response.getResult().getOutput().getUrl();
    }
}

Demo — 图片理解 (多模态):

@RestController
@RequestMapping("/multimodal")
public class MultimodalController {

    private final ChatClient chatClient;

    public MultimodalController(ChatClient.Builder chatClientBuilder) {
        this.chatClient = chatClientBuilder
                .defaultSystem("你是一个多模态助手,可以分析图片内容。")
                .defaultAdvisors(new SimpleLoggerAdvisor())
                .build();
    }

    @GetMapping("/analyze")
    public String analyzeImage(@RequestParam String imageUrl, @RequestParam String question) {
        return chatClient.prompt()
                .user(u -> u.text(question)
                        .media(MediaType.IMAGE_PNG, new UrlResource(imageUrl)))
                .call()
                .content();
    }
}

3.7 Graph Workflow — 状态图工作流

功能: 通过 StateGraph 构建复杂的多步骤 AI 工作流,支持条件路由、并行节点、嵌套图。

依赖:

<dependency>
    <groupId>com.alibaba.cloud.ai</groupId>
    <artifactId>spring-ai-alibaba-graph-core</artifactId>
    <version>${spring-ai-alibaba.version}</version>
</dependency>
<dependency>
    <groupId>com.alibaba.cloud.ai</groupId>
    <artifactId>spring-ai-alibaba-starter-dashscope</artifactId>
</dependency>

Demo — 客户反馈分类工作流:

// Step 1: 定义全局状态
OverAllStateFactory stateFactory = () -> {
    OverAllState state = new OverAllState();
    state.registerKeyAndStrategy("input", new ReplaceStrategy());
    state.registerKeyAndStrategy("classifier_output", new ReplaceStrategy());
    state.registerKeyAndStrategy("solution", new ReplaceStrategy());
    return state;
};

// Step 2: 定义节点
// 反馈正负分类节点
QuestionClassifierNode feedbackClassifier = QuestionClassifierNode.builder()
        .chatClient(chatClient)
        .inputTextKey("input")
        .categories(List.of("positive feedback", "negative feedback"))
        .classificationInstructions(List.of(
                "理解用户反馈时的情绪,判断是正面还是负面。"))
        .build();

// 负面反馈细分节点
QuestionClassifierNode specificClassifier = QuestionClassifierNode.builder()
        .chatClient(chatClient)
        .inputTextKey("input")
        .categories(List.of("after-sale service", "transportation",
                            "product quality", "others"))
        .classificationInstructions(List.of(
                "理解用户具体需要什么帮助,进行细分分类。"))
        .build();

// Step 3: 定义条件路由
// 反馈分类 -> 下一节点路由
public class FeedbackDispatcher implements EdgeAction {
    @Override
    public String apply(OverAllState state) {
        String result = state.getString("classifier_output");
        if (result.contains("positive")) return "positive";
        return "negative";
    }
}

// Step 4: 构建 StateGraph
StateGraph graph = new StateGraph("Customer Service Workflow", stateFactory)
    .addNode("feedback_classifier", node_async(feedbackClassifier))
    .addNode("specific_classifier", node_async(specificClassifier))
    .addNode("recorder", node_async(recorderNode))

    // 起点
    .addEdge(START, "feedback_classifier")

    // 条件路由
    .addConditionalEdges("feedback_classifier",
            edge_async(new FeedbackDispatcher()),
            Map.of("positive", "recorder", "negative", "specific_classifier"))

    // 细分分类后全部汇入 recorder
    .addConditionalEdges("specific_classifier",
            edge_async(new SpecificDispatcher()),
            Map.of("after-sale", "recorder", "transportation", "recorder",
                   "quality", "recorder", "others", "recorder"))

    // 终点
    .addEdge("recorder", END)
    .compile();

// Step 5: 执行工作流
@RestController
@RequestMapping("/workflow")
public class WorkflowController {

    @Autowired private StateGraph graph;

    @GetMapping("/chat")
    public String chat(@RequestParam String query) {
        OverAllState result = graph.invoke(Map.of("input", query));
        return result.getString("solution");
    }
}

工作流示意图:

START → [feedback_classifier] → ┬─ positive → [recorder] → END
                                └─ negative → [specific_classifier]
                                                ├─ after-sale  → [recorder] → END
                                                ├─ transportation → [recorder] → END
                                                ├─ quality → [recorder] → END
                                                └─ others → [recorder] → END

3.8 Multi-Agent — 多智能体编排

功能: 使用预置的多智能体模式组合多个 Agent,实现复杂任务协同。

依赖:

<dependency>
    <groupId>com.alibaba.cloud.ai</groupId>
    <artifactId>spring-ai-alibaba-agent-framework</artifactId>
    <version>1.1.2.0</version>
</dependency>
<dependency>
    <groupId>com.alibaba.cloud.ai</groupId>
    <artifactId>spring-ai-alibaba-starter-dashscope</artifactId>
</dependency>

Demo — ReactAgent (单个智能体):

public class AgentExample {
    public static void main(String[] args) throws Exception {
        // 创建模型
        DashScopeApi api = DashScopeApi.builder()
                .apiKey(System.getenv("AI_DASHSCOPE_API_KEY"))
                .build();

        ChatModel chatModel = DashScopeChatModel.builder()
                .dashScopeApi(api)
                .defaultOptions(DashScopeChatOptions.builder()
                        .model("qwen-max")
                        .build())
                .build();

        // 注册工具
        FunctionCallbackWrapper weatherFunc = FunctionCallbackWrapper.builder(
                new WeatherService())
                .withName("getWeather")
                .withDescription("查询城市天气")
                .build();

        // 构建 ReactAgent
        ReactAgent agent = ReactAgent.builder()
                .name("weather_agent")
                .model(chatModel)
                .instruction("你是一个天气助手,使用工具获取真实天气数据。")
                .tools(weatherFunc)
                .build();

        // 执行
        String result = agent.call("北京今天天气怎么样?");
        System.out.println(result);
    }
}

Demo — SequentialAgent (顺序执行):

// 定义两个专业 Agent
ReactAgent translator = ReactAgent.builder()
        .name("translator")
        .model(chatModel)
        .instruction("将用户输入翻译成英文。")
        .build();

ReactAgent summarizer = ReactAgent.builder()
        .name("summarizer")
        .model(chatModel)
        .instruction("将英文文本总结为 3 个要点。")
        .build();

// 顺序执行: 先翻译 -> 再总结
SequentialAgent pipeline = SequentialAgent.builder()
        .name("translate_and_summarize")
        .agents(translator, summarizer)
        .build();

String result = pipeline.call("人工智能正在改变我们的生活方式和工作模式。");

Demo — ParallelAgent (并行执行):

// 并行执行多个独立 Agent,最后汇总
ParallelAgent parallel = ParallelAgent.builder()
        .name("research_assistant")
        .agents(
                ReactAgent.builder().name("web_search").model(chatModel)
                        .instruction("搜索最新的 AI 技术进展").build(),
                ReactAgent.builder().name("news_search").model(chatModel)
                        .instruction("搜索最新的 AI 行业新闻").build(),
                ReactAgent.builder().name("code_search").model(chatModel)
                        .instruction("搜索最新的 AI 开源项目").build()
        )
        .synthesisInstruction("汇总三个搜索结果,生成一份完整报告。")
        .build();

String report = parallel.call("AI 领域的最新动态");

Demo — RoutingAgent (路由分发):

// 根据意图路由到不同 Agent
RoutingAgent router = RoutingAgent.builder()
        .name("intent_router")
        .model(chatModel)
        .routingInstruction("判断用户意图,选择最合适的 Agent:"
                + "weather->天气Agent, news->新闻Agent, code->编程Agent")
        .routeTo("weather", weatherAgent)
        .routeTo("news", newsAgent)
        .routeTo("code", codeAgent)
        .build();

3.9 Spring AI Alibaba Admin — 可视化 Agent 平台

功能: 一站式 Agent 开发平台,支持 Prompt 管理、运行追踪、Agent 评估、MCP 管理。可视化调试 Agent,并与 Dify 等低代码平台集成。

部署 (Docker):

docker run -d -p 8080:8080 \
  -e AI_DASHSCOPE_API_KEY=your_api_key \
  --name spring-ai-alibaba-admin \
  sca-registry.cn-hangzhou.cr.aliyuncs.com/spring-ai-alibaba/admin:1.0.0.2-x

访问 http://localhost:8080 即可使用可视化平台。

接入自建 Agent 应用:

# Agent 应用中配置 Nacos 连接
spring:
  ai:
    alibaba:
      agent:
        proxy:
          nacos:
            server-addr: ${nacos-address:127.0.0.1:8848}
            username: nacos
            password: nacos
          prompt-key: my-agent-prompt
<dependencies>
    <!-- Agent Nacos 代理 -->
    <dependency>
        <groupId>com.alibaba.cloud.ai</groupId>
        <artifactId>spring-ai-alibaba-agent-nacos</artifactId>
    </dependency>
    <!-- OpenTelemetry 追踪上报 -->
    <dependency>
        <groupId>io.opentelemetry</groupId>
        <artifactId>opentelemetry-exporter-otlp</artifactId>
    </dependency>
</dependencies>

3.10 Playground — 全功能体验示例

功能: 包含完整前端 UI + 后端的综合示例,覆盖对话记忆、工具调用、图片生成、多模态、MCP、RAG 等所有核心能力。

Docker 快速体验:

docker run -d -p 8080:8080 \
  -e AI_DASHSCOPE_API_KEY=your_api_key \
  --name spring-ai-alibaba-playground \
  sca-registry.cn-hangzhou.cr.aliyuncs.com/spring-ai-alibaba/playground:1.0.0.2-x

浏览器访问 http://localhost:8080

源码地址: https://github.com/springaialibaba/spring-ai-alibaba-examples/tree/main/spring-ai-alibaba-playground


3.11 NL2SQL — 自然语言转 SQL

功能: 将自然语言转换为 SQL 查询,实现"对话即 BI"。

依赖:

<dependency>
    <groupId>com.alibaba.cloud.ai</groupId>
    <artifactId>spring-ai-alibaba-starter-nl2sql</artifactId>
</dependency>

Demo:

@Service
public class Nl2SqlService {

    private final ChatClient chatClient;
    private final JdbcTemplate jdbcTemplate;

    public Nl2SqlService(ChatClient.Builder chatClientBuilder, JdbcTemplate jdbcTemplate) {
        this.chatClient = chatClientBuilder
                .defaultSystem("你是一个 SQL 专家,将自然语言转换为标准 SQL。")
                .defaultAdvisors(new SimpleLoggerAdvisor())
                .build();
        this.jdbcTemplate = jdbcTemplate;
    }

    public String query(String naturalLanguage, String tableSchema) {
        // 生成 SQL
        String sql = chatClient.prompt()
                .user("表结构:\n" + tableSchema + "\n\n请将以下问题转换为 SQL:\n"
                        + naturalLanguage)
                .call()
                .content();

        // 执行查询
        return jdbcTemplate.queryForObject(sql, String.class);
    }
}

3.12 Observability — 可观测性

功能: 集成 ARMS、OpenTelemetry,支持 Trace、Metrics、日志追踪。

依赖:

<dependency>
    <groupId>com.alibaba.cloud.ai</groupId>
    <artifactId>spring-ai-alibaba-starter-arms-observation</artifactId>
</dependency>

配置:

spring:
  ai:
    alibaba:
      observation:
        enabled: true
        endpoint: ${ARMS_ENDPOINT}
        app-name: spring-ai-alibaba-demo

四、生产级应用示例

4.1 DeepResearch — 深度研究助手

基于 Graph 实现的多步骤研究工具,支持任务规划、子 Agent、文件系统访问。

git clone --depth=1 https://github.com/alibaba/spring-ai-alibaba.git
cd spring-ai-alibaba/examples/deepresearch
export AI_DASHSCOPE_API_KEY=your_key
mvn spring-boot:run
# 访问 http://localhost:8080/chatui/index.html

核心能力: TodoListInterceptor 任务规划、FilesystemInterceptor 文件读写、SubAgentInterceptor 子 Agent 协作。

4.2 JManus — Java 版 Manus

通用 Agent 产品,参考 Manus 架构,集成优秀的前端 UI。

git clone https://github.com/alibaba/spring-ai-alibaba.git
cd spring-ai-alibaba/spring-ai-alibaba-jmanus
mvn spring-boot:run

五、功能速查表

| 功能 | 依赖 | 复杂度 | 适用场景 |
|---|---|---|---|
| ChatClient 对话 | starter-dashscope | ⭐ | 简单问答、单轮/多轮对话 |
| ChatMemory 记忆 | starter-dashscope | ⭐ | 需上下文的多轮对话 |
| Tool Calling | starter-dashscope | ⭐⭐ | 需要调用外部 API/工具 |
| MCP Server/Client | starter-nacos-mcp-* | ⭐⭐ | 标准化工具协议、分布式 Agent |
| RAG | starter-dashscope + vector-store | ⭐⭐⭐ | 知识库问答、私域知识检索 |
| ImageModel 图片生成 | starter-dashscope | ⭐ | 文生图、多模态理解 |
| Graph Workflow | graph-core | ⭐⭐⭐ | 复杂业务流程、条件分支 |
| ReactAgent | agent-framework | ⭐⭐ | 自主推理 + 工具调用的 Agent |
| SequentialAgent | agent-framework | ⭐⭐⭐ | 流程式多步骤任务 |
| ParallelAgent | agent-framework | ⭐⭐⭐ | 并行探索/多源信息汇总 |
| RoutingAgent | agent-framework | ⭐⭐⭐ | 意图识别 + 路由分发 |
| Admin 可视化平台 | Admin Docker | ⭐⭐ | Agent 开发调试、评估 |
| NL2SQL | starter-nl2sql | ⭐⭐ | 对话式数据分析 |
| Observability | starter-arms-observation | ⭐ | 生产环境监控 |


六、快速开始 Checklist

  1. JDK 17+ 安装就绪
  2. 获取 API Key: https://bailian.console.aliyun.com/
  3. 设置环境变量: export AI_DASHSCOPE_API_KEY=your_key
  4. 引入依赖: spring-ai-alibaba-starter-dashscope
  5. 编写 Controller: 注入 ChatClient 开始对话
  6. 按需扩展: 根据场景叠加 Tool → MCP → RAG → Graph → Multi-Agent

钉钉交流群: 94405033092
官网: https://java2ai.com
GitHub: https://github.com/alibaba/spring-ai-alibaba