Semantic Kernel实战:微软AI编排框架的Java落地指南

📅 2026/7/2 5:42:41
Semantic Kernel实战:微软AI编排框架的Java落地指南
、核心概念KernelAI 编排的核心管理所有技能和插件Skill一组相关能力的集合如文本处理、搜索Plugin外部工具的封装供大模型调用Planner自动规划任务分解和执行顺序回到顶部二、环境准备dependency groupIdcom.microsoft.semantic-kernel/groupId artifactIdkernel-core/artifactId version1.0.0-beta1/version /dependency dependency groupIdcom.microsoft.semantic-kernel/groupId artifactIdconnectors-ai-openai/artifactId version1.0.0-beta1/version /dependency回到顶部三、初始化 Kernelimport com.microsoft.semantic kernel.Kernel; import com.microsoft.semantic kernel.services AIServiceRequestHandlerConfig; public class SemanticKernelDemo { public static void main(String[] args) { // 配置 OpenAI OpenAIChatCompletion model OpenAIChatCompletion.builder() .withModelId(gpt-4o-mini) .withAPIKey(System.getenv(OPENAI_API_KEY)) .build(); // 创建 Kernel Kernel kernel Kernel.builder() .withDefaultAIService(ChatCompletionService.class, model) .build(); System.out.println(Semantic Kernel initialized successfully); } }回到顶部四、创建原生函数Native Functionsimport com.microsoft.semantic kernel.skills.annotation.KernelFunction; public class WeatherPlugin { KernelFunction(name get_weather, description 获取指定城市的天气) public String getWeather(String location) { // 实际项目中调用天气 API return location 今天晴气温22-28度适合出行; } KernelFunction(name get_date, description 获取当前日期) public String getCurrentDate() { return LocalDate.now().toString(); } }回到顶部五、注册插件并调用import com.microsoft.semantic kernel.skills.core.SkillsFactory; public class PluginDemo { public static void main(String[] args) { Kernel kernel createKernel(); // 注册插件 kernel.importSkill(new WeatherPlugin(), weather); // 执行自然语言任务 String prompt 帮我查一下北京今天的天气并告诉我今天是几号; String result kernel.run(prompt); System.out.println(result); // 输出北京今天晴气温22-28度适合出行。今天是2026-04-02。 } }回到顶部六、使用 Memory 实现记忆import com.microsoft.semantic kernel.memory.MemorySkill; import com.microsoft.semantic kernel.memory.builder.InMemoryTextMemory; public class MemoryDemo { public static void main(String[] args) { InMemoryTextMemory memory new InMemoryTextMemory(); // 保存对话记忆 memory.save(user_name, 张三); memory.save(user_preference, 喜欢Java技术); // 检索记忆 String name memory.get(user_name).join(); System.out.println(User name: name); // 输出User name: 张三 } }回到顶部七、Planner 自动任务规划public class PlannerDemo { public static void main(String[] args) { Kernel kernel createKernel(); kernel.importSkill(new WeatherPlugin(), weather); kernel.importSkill(new SearchPlugin(), search); // 复杂任务自动分解为多个步骤 String userGoal 先查北京天气然后搜索相关的旅游攻略; // SK 会自动规划执行步骤 // Step 1: 调用 weather.get_weather(location北京) // Step 2: 调用 search.search(query北京旅游攻略) // Step 3: 整合结果返回给用户 } }回到顶部总结Semantic Kernel 为 Java 开发者提供了接入大模型的统一编排方案。核心优势统一抽象一套代码支持 OpenAI、Azure OpenAI、HuggingFace 等