Spring AI 框架下接入 agent skill 手把手教程

Spring AI 框架下接入 agent skill 手把手教程
参考文档:Spring AI Agentic Patterns (Part 1): Agent Skills - Modular, Reusable Capabilities

引言

点进来的读者应该都了解了 agent skills 是什么,为什么会出现这种工程手段等等,此处不在多说,本篇博客聚焦于在 Spring-AI 下如何快速接入 Skills,并且探究背后实现的原理。
项目示例代码可以在 https://github.com/MimicHunterZ/PocketMind/tree/master/backend/src/main/java/com/doublez/pocketmindserver/demo 下查看,如果觉得项目不错,欢迎给我star~

环境准备

maven依赖

根据官方手册,skill 需要 Spring-AI 2.0.0-M2 版本以上,所以根据这个配置,项目demo的依赖如下:

<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>4.0.2</version><relativePath/></parent><properties><java.version>21</java.version><spring-ai.version>2.0.0-M2</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-starter-model-openai</artifactId></dependency><!--引入社区实现的 skills 工具--><dependency><groupId>org.springaicommunity</groupId><artifactId>spring-ai-agent-utils</artifactId><version>0.4.2</version></dependency></dependencies><dependencyManagement><dependencyManagement><dependencies><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><repositories><repository><id>spring-milestones</id><name>Spring Milestones</name><url>https://repo.spring.io/milestone</url></repository></repositories>
实测,Spring boot 3.5.10、jdk17、Spring AI 1.1.2 也可以跑通demo,不过不知道有没有更多的坑

yml配置

server:port:8080spring:application:name: pocketmind-server ai:chat:client:observations:log-prompt:truelog-completion:trueopenai:api-key: xxxx # 替换为你的 API Key base-url: xxxx # 替换为你的 Base URL 不需要 /v1 chat: options:model: deepseek-chat # 替换为你使用的模型名称 
示例demo采用 openai兼容的 api,如需兼容anthropic,那么根据对应文档进行切换即可

示例代码

skill.md

在根目录下添加对应的skill,skill的格式应该如下:

my-skill/ ├── SKILL.md # Required: instructions + metadata ├── scripts/ # Optional: executable code ├── references/ # Optional: documentation └── assets/ # Optional: templates, resources 

在 skill.md 中 格式应该如下,至少应该包含元信息和详细的说明文档

--- name: code-reviewer description: Reviews Java code for best practices, security issues, and Spring Framework conventions. Use when user asks to review, analyze, or audit code --- # Code Reviewer ## Instructions When reviewing code: 1. Check **for** security vulnerabilities (SQL injection, XSS, etc.) 2. Verify Spring Boot best practices (proper use of @Service, @Repository, etc.) 3. Look **for** potential null pointer exceptions 4. Suggest improvements **for** readability and maintainability 5. Provide specific line-by-line feedback with code examples 

示例如下:

在这里插入图片描述

controller

importorg.springaicommunity.agent.tools.FileSystemTools;importorg.springaicommunity.agent.tools.ShellTools;importorg.springaicommunity.agent.tools.SkillsTool;importorg.springframework.ai.chat.client.ChatClient;importorg.springframework.web.bind.annotation.*;importjava.util.Map;@RestController@RequestMapping("/demo")publicclassSkillController{privatefinalChatClient chatClient;publicSkillController(ChatClient.Builder chatClientBuilder){this.chatClient = chatClientBuilder .defaultToolCallbacks(SkillsTool.builder().addSkillsDirectory(".claude/skills")//也可以使用下面这个//.addSkillsResource(resourceLoader.getResource("classpath:.claude/skills")).build()).defaultTools(FileSystemTools.builder().build()).defaultTools(ShellTools.builder().build()).defaultToolContext(Map.of("foo","bar")).build();}/** * 测试 skill 流程 * @param message 用户的输入 * @return */@PostMapping("/skill")publicStringchat(@RequestBodyString message){return chatClient.prompt().user(message).call().content();}}

此时运行程序,访问对应的端口即可查看返回内容

代码解释

  1. 先声明一个 ChatClient ,并且通过 DI 进行注入
  2. 通过 chatClientBuilder 进行 builder 策略构建
    • .defaultToolCallbacks(...):给 ChatClient 一个“已经组装好”的工具包(包含代码逻辑 + JSON Schema 描述),此处即为注册 skill 功能
    • .defaultTools(): 注册对应的系统工具名称,用于动态发现skill来进行使用
    • .defaultToolContext(Map.of("foo", "bar")) 添加工具上下文,防止报错
    • .defaultToolContext(Map.of("foo", "bar")) 这个是为了框架报错,需要添加一个map传入作为ToolContext,否则无法正常build,为框架缺陷
  3. 通过链条进行构建llm的request
    • .user(message) 加载用户提示词
    • .call() 由框架内部发其请求
    • .content() 获取大模型返回的内容

源码分析

0. 设置目录:

publicclassSkillsTool{//...publicstaticclassBuilder{privateList<Skill> skills =newArrayList<>();privateString toolDescriptionTemplate = TOOL_DESCRIPTION_TEMPLATE;protectedBuilder(){}publicBuildertoolDescriptionTemplate(String template){this.toolDescriptionTemplate = template;returnthis;}publicBuilderaddSkillsResources(List<Resource> skillsRootPaths){for(Resource skillsRootPath : skillsRootPaths){this.addSkillsResource(skillsRootPath);}returnthis;}publicBuilderaddSkillsResource(Resource skillsRootPath){try{String path = skillsRootPath.getFile().toPath().toAbsolutePath().toString();this.addSkillsDirectory(path);}catch(IOException ex){thrownewRuntimeException("Failed to load skills from directory: "+ skillsRootPath, ex);}returnthis;}publicBuilderaddSkillsDirectory(String skillsRootDirectory){this.addSkillsDirectories(List.of(skillsRootDirectory));returnthis;}publicBuilderaddSkillsDirectories(List<String> skillsRootDirectories){for(String skillsRootDirectory : skillsRootDirectories){try{this.skills.addAll(skills(skillsRootDirectory));}catch(IOException ex){thrownewRuntimeException("Failed to load skills from directory: "+ skillsRootDirectory, ex);}}returnthis;}//...}//...}
  • addSkillsResourceaddSkillsDirectory 添加 skill 的路径,支持多个

toolDescriptionTemplate: 添加 skill 描述说明

在这里插入图片描述

1. 加载 skill 元数据

这是加载器的入口。它会去你指定的文件夹里找 SKILL.md 文件。
/** * Recursively finds all SKILL.md files in the given root directory and returns their * parsed contents. * @param rootDirectory the root directory to search for SKILL.md files * @return a list of SkillFile objects containing the path, front-matter, and content * of each SKILL.md file * @throws IOException if an I/O error occurs while reading the directory or files */privatestaticList<Skill>skills(String rootDirectory)throwsIOException{Path rootPath =Paths.get(rootDirectory);if(!Files.exists(rootPath)){thrownewIOException("Root directory does not exist: "+ rootDirectory);}if(!Files.isDirectory(rootPath)){thrownewIOException("Path is not a directory: "+ rootDirectory);}List<Skill> skillFiles =newArrayList<>();try(Stream<Path> paths =Files.walk(rootPath)){ paths.filter(Files::isRegularFile).filter(path -> path.getFileName().toString().equals("SKILL.md"))// 遍历目录.forEach(path ->{try{// 解析文件:分为 FrontMatter (元数据) 和 Content (正文)String markdown =Files.readString(path,StandardCharsets.UTF_8);MarkdownParser parser =newMarkdownParser(markdown); skillFiles.add(newSkill(path, parser.getFrontMatter(), parser.getContent()));}catch(IOException e){thrownewRuntimeException("Failed to read SKILL.md file: "+ path, e);}});}return skillFiles;}
  • FrontMatter (YAML头):包含技能的名字(如 name: pdf)和描述。这部分会被提取出来,告诉 AI “我有这个技能”。
  • Content (正文):这是具体的 Prompt 指令(比如“处理 PDF 的步骤是:1. 转换文本… 2. 提取摘要…”)。
  1. t添加 skill 技能
publicToolCallbackbuild(){Assert.notEmpty(this.skills,"At least one skill must be configured");String skillsXml =this.skills.stream().map(s -> s.toXml()).collect(Collectors.joining("\n"));returnFunctionToolCallback.builder("Skill",newSkillsFunction(toSkillsMap(this.skills))).description(this.toolDescriptionTemplate.formatted(skillsXml)).inputType(SkillsInput.class).build();}
  • 此步骤会把扫描到的技能列表编织进工具的描述里。
  • 当 AI 看到这个工具时,它的 Prompt 里会出现你定义过的 skill 列表,例如:
    • <skill><name>pdf</name><description>Extract text from PDF</description></skill>
    • <skill><name>git</name><description>Git version control</description></skill>

3. 调用skill

当 AI 决定调用 Skill("pdf") 时,实际上触发了这段逻辑:
publicstaticclassSkillsFunctionimplementsFunction<SkillsInput,String>{privateMap<String,Skill> skillsMap;publicSkillsFunction(Map<String,Skill> skillsMap){this.skillsMap = skillsMap;}@OverridepublicStringapply(SkillsInput input){Skill skill =this.skillsMap.get(input.command());if(skill !=null){var skillBaseDirectory = skill.path().getParent().toString();return"Base directory for this skill: %s\n\n%s".formatted(skillBaseDirectory, skill.content());}return"Skill not found: "+ input.command();}}
  • 此时返回的是“路径”和“正文内容”,于是 AI 读到返回的文字后,会发现这是一份“Code Review 的操作指南”。

至此 skill 的机制已经完整实现了,ai 只需要根据返回的 Skill.md 就可以调用对应的说明或者reference/scripts 下面的技能。

如果读者对于spring ai 框架下 ai 怎么进行多次工具调用循环好奇,可以查看Spring ai下的工具调用以及循环调用

Read more

在ESP32-S3部署mimiclaw,基于deepseek并用飞书机器人开展对话-feishu

在ESP32-S3部署mimiclaw,基于deepseek并用飞书机器人开展对话-feishu

最近mimiclaw火爆,其开发团队也在密集更新,我看3天前已经可以用“飞书机器人”对话交互了。 目前网络上能查到的部署资料相对滞后,现在将飞书机器人的部署整理如下: 1. 前提 已经安装好ESP-IDF,并支持vscode编译esp32固件。 2. api-key准备 * 注册deepseek, * 创建APIkey, * 并充值,新注册的用户余额为零,无法使用 3. 飞书机器人 我是在飞书个人版中,创建的机器人。 1. 访问飞书开放平台,单击创建企业自建应用,填写应用名称和描述,选择应用图标,单击创建。 2. 左侧导航栏单击凭证与基础信息 页面,复制App ID(格式如 cli_xxx)和App Secret。 3. 配置事件订阅。 1. 在飞书开放平台左侧导航栏单击事件与回调,在事件配置页签中单击订阅方式,选择使用 长连接 接收事件,单击保存。 2. 在事件配置页面,单击添加事件,

深入解析VR与AR:从技术原理到未来图景

引言 虚拟现实(VR)和增强现实(AR)正逐步从科幻概念演变为改变我们工作、娱乐和社交方式的核心技术。它们通过数字内容与现实世界的融合,重塑了人机交互的边界。本文将系统分析两者的定义、技术架构、应用场景、当前挑战及未来趋势,帮助您全面理解这一变革性领域。 一、核心定义与区别 维度虚拟现实 (VR)增强现实 (AR)混合现实 (MR)概念完全由计算机生成的虚拟环境,用户沉浸其中,与物理世界隔绝将数字信息叠加到真实世界之上,用户同时看到虚实内容数字对象与真实世界实时交互,并相互影响(AR的进阶)沉浸感完全沉浸(封闭式)部分沉浸(透视式)虚实融合,具有空间锚定和物理交互典型设备Oculus Quest, HTC Vive, PlayStation VRMicrosoft HoloLens, Google Glass, 手机AR(ARKit/ARCore)Microsoft HoloLens 2, Magic Leap核心技术头显显示、

OpenClaw对接飞书机器人高频踩坑实战指南:从插件安装到回调配对全解析

前言 当前企业办公场景中,将轻量级AI框架OpenClaw与飞书机器人结合,能够快速实现智能交互、流程自动化等功能。然而,在实际对接过程中,开发者常常因权限配置、环境依赖、回调设置等细节问题陷入反复试错。本文以“问题解决”为核心,梳理了10个典型踩坑点,每个问题均配套原因分析、排查步骤和实操案例。同时,补充高效调试技巧与功能扩展建议,帮助开发者系统性地定位并解决对接障碍,提升落地效率。所有案例基于Windows 11环境、OpenClaw最新稳定版及飞书开放平台最新界面验证,解决方案可直接复用。 一、前置准备(快速自查) 为避免基础环境问题浪费时间,建议在开始前确认以下三点: * OpenClaw已正确安装,终端执行 openclaw -v 可查看版本(建议使用最新版,旧版本可能存在插件兼容风险)。 * Node.js版本不低于v14,npm版本不低于v6,通过 node -v 和 npm -v 验证,防止因依赖版本过低导致插件安装失败。 * 飞书账号需具备企业开发者权限(企业账号需管理员授权,个人账号默认具备)

数字FPGA方向 + 双一流本科 + C9硕士在读,前路如何?

数字FPGA方向 + 双一流本科 + C9硕士在读,前路如何?

数字FPGA方向 + 双一流本科 + C9硕士在读 + 组内有完整工程项目经验 如果只有前面三项,其实确实会焦虑。 因为现在做FPGA的人里,成绩好、学历高的并不少。 但再加上扎实的工程项目经历——真正从需求、架构、RTL、时序收敛到板级联调都走过一遍——这套配置,在当下已经不算弱。 即便如此,这类同学依然迷茫,我信。 现在卷的不是学历,是“谁更像工程师”。 回到标题这个问题——“数字FPGA、双一流本、C9硕士在读,出路在哪?” 从背景来看,有几条路可以认真想一想。 硕士毕业直接就业,是一条很现实的路。 FPGA行业本质是工程驱动型行业。 企业比起论文,更看你有没有真正做过项目: 是否独立写过模块? 是否收过时序? 是否在板子上调过问题? 是否面对过真实接口协议? 哪怕第一份工作只是做验证支持,或者在中小公司做通用逻辑开发,只要你能在两三年里真正参与完整产品交付,含金量会迅速拉开差距。 很多人焦虑的是起点,其实真正决定差距的是前三年的积累密度。 继续读博。 这条路只适合两种人: 第一,真的喜欢做架构和方法研究; 第二,目标非常明确,