2025最新版Semantic Kernel Python全攻略:从零基础到企业级部署的AI集成指南
为什么选择Semantic Kernel?
还在为LLM集成复杂、多Agent协作困难而烦恼?Semantic Kernel(语义内核)作为微软开源的AI集成框架,让你轻松将前沿大语言模型技术融入应用。本文将带你从安装到部署,掌握Python版Semantic Kernel的全部核心技能,读完你将能够:
- 快速搭建AI应用的开发环境
- 创建智能Agent并实现多Agent协作
- 集成各类工具和插件扩展AI能力
- 部署企业级AI解决方案
环境准备与安装
系统要求
Semantic Kernel Python版需要以下环境:
- Python 3.10+
- 支持Windows、macOS和Linux系统
快速安装
使用pip命令即可完成基础安装:
pip install --upgrade semantic-kernel
如需添加特定集成,可使用以下命令:
# 安装Hugging Face集成
pip install --upgrade semantic-kernel[hugging_face]
# 安装所有可用集成
pip install --upgrade semantic-kernel[all]
配置AI服务
API密钥设置
创建.env文件存储API密钥:
OPENAI_API_KEY=sk-...
OPENAI_CHAT_MODEL_ID=gpt-4
AZURE_OPENAI_API_KEY=...
AZURE_OPENAI_ENDPOINT=...
AZURE_OPENAI_CHAT_DEPLOYMENT_NAME=...
也可以在代码中直接配置服务:
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
chat_service = AzureChatCompletion(
api_key="YOUR_API_KEY",
endpoint="YOUR_ENDPOINT",
deployment_name="YOUR_DEPLOYMENT_NAME",
api_version="2024-02-15-preview",
)
更多配置示例可参考service_settings.py文件。
核心功能使用
基础Kernel使用
Kernel是Semantic Kernel的核心,以下是一个简单示例:
import asyncio
from semantic_kernel import Kernel
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.functions import KernelArguments
kernel = Kernel()
kernel.add_service(OpenAIChatCompletion())
prompt = """
1) A robot may not injure a human being...
2) A robot must obey orders given it by human beings...
3) A robot must protect its own existence...
Give me the TLDR in exactly {{$num_words}} words."""
async def main():
result = await kernel.invoke_prompt(prompt, arguments=KernelArguments(num_words=5))
print(result)
asyncio.run(main())
# 输出: Protect humans, obey, self-preserve, prioritized.
直接使用AI服务
不使用Kernel也可以直接调用AI服务:
import asyncio
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.contents import ChatHistory
async def main():
service = OpenAIChatCompletion()
chat_history = ChatHistory(system_message="You are a helpful assistant.")
chat_history.add_user_message("Write a haiku about Semantic Kernel.")
response = await service.get_chat_message_content(chat_history=chat_history)
print(response.content)
asyncio.run(main())
构建智能Agent
创建基础Agent
以下示例展示如何创建一个带插件的聊天Agent:
import asyncio
from typing import Annotated
from pydantic import BaseModel
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
from semantic_kernel.functions import kernel_function
class MenuPlugin:
@kernel_function(description="Provides a list of specials from the menu.")
def get_specials(self) -> Annotated[str, "Returns the specials from the menu."]:
return """
Special Soup: Clam Chowder
Special Salad: Cobb Salad
Special Drink: Chai Tea
"""
@kernel_function(description="Provides the price of the requested menu item.")
def get_item_price(
self, menu_item: Annotated[str, "The name of the menu item."]
) -> Annotated[str, "Returns the price of the menu item."]:
return "$9.99"
class MenuItem(BaseModel):
price: float
name: str
async def main():
agent = ChatCompletionAgent(
service=AzureChatCompletion(),
name="SK-Assistant",
instructions="You are a helpful assistant.",
plugins=[MenuPlugin()]
)
response = await agent.get_response("What is the price of the soup special?")
print(response.content)
asyncio.run(main())
更多Agent示例可参考getting_started_with_agents目录。
多Agent协作
Semantic Kernel支持多Agent编排,实现复杂任务协作:
import asyncio
from semantic_kernel.agents import ChatCompletionAgent, GroupChatOrchestration, RoundRobinGroupChatManager
from semantic_kernel.agents.runtime import InProcessRuntime
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
def get_agents():
return [
ChatCompletionAgent(
name="Writer",
instructions="You are a creative content writer. Generate and refine slogans based on feedback.",
service=AzureChatCompletion(),
),
ChatCompletionAgent(
name="Reviewer",
instructions="You are a critical reviewer. Provide detailed feedback on proposed slogans.",
service=AzureChatCompletion(),
),
]
async def main():
agents = get_agents()
group_chat = GroupChatOrchestration(
members=agents,
manager=RoundRobinGroupChatManager(max_rounds=5),
)
runtime = InProcessRuntime()
runtime.start()
result = await group_chat.invoke(
task="Create a slogan for a new electric SUV that is affordable and fun to drive.",
runtime=runtime,
)
value = await result.get()
print(f"Final Slogan: {value}")
await runtime.stop_when_idle()
if __name__ == "__main__":
asyncio.run(main())
高级应用与部署
流程框架使用
Semantic Kernel提供流程框架,用于构建结构化业务流程:
# 示例:使用Process框架构建工作流
from semantic_kernel.processes import Process, Step
class OrderProcessingWorkflow(Process):
def __init__(self):
super().__init__(name="OrderProcessing")
self.add_step(Step(name="ValidateOrder", function=self.validate_order))
self.add_step(Step(name="ProcessPayment", function=self.process_payment))
self.add_step(Step(name="ShipOrder", function=self.ship_order))
async def validate_order(self, context):
# 订单验证逻辑
pass
async def process_payment(self, context):
# 支付处理逻辑
pass
async def ship_order(self, context):
# 订单发货逻辑
pass
更多流程框架示例可参考getting_started_with_processes目录。
部署最佳实践
- 环境隔离:使用虚拟环境或容器确保环境一致性
- 配置管理:使用环境变量或配置服务管理敏感信息
- 日志监控:集成日志系统监控AI交互和性能
- 模型缓存:对频繁使用的模型响应进行缓存
- 异步处理:利用异步编程提高并发处理能力
学习资源与社区
官方文档与示例
- Python版Semantic Kernel文档
- 概念示例:高级场景和集成示例
- 交互式Notebook:快速实验和学习
参与社区
- 提交Issue和PR:帮助改进项目
- 加入讨论:分享使用经验和解决方案
- 贡献插件:扩展Semantic Kernel生态系统
总结与展望
通过本文,你已经掌握了Semantic Kernel Python版的核心功能和使用方法。从简单的LLM调用到复杂的多Agent系统,Semantic Kernel提供了灵活而强大的框架,帮助开发者轻松构建AI应用。
随着AI技术的不断发展,Semantic Kernel也在持续进化,未来将支持更多的模型和集成,为开发者提供更强大的工具。现在就开始你的AI应用开发之旅吧!
点赞收藏本文,关注后续更多Semantic Kernel高级技巧分享!
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考




