
近年來,我們目睹了人工智慧系統與使用者互動方式發生的令人興奮的轉變,這種轉變不僅僅是回答問題,還包括推理、規劃和採取行動。這種轉變是由 Autogen、LangGraph 和 CrewAI 等代理框架的興起所推動的。這些框架使大型語言模型(LLM)的行為更像自主代理–能夠做出決策、呼叫函式和跨任務協作。其中,微軟提供的 Semantic Kernel 是一個特別強大但又對開發人員友好的選擇。在本教程中,我們將探討 Semantic Kernel 的獨特之處、它與其他方法的比較,以及您如何開始使用它來構建自己的人工智慧代理。
學習目標
- 瞭解 Semantic Kernel 的核心架構和目的。
- 瞭解如何將外掛和人工智慧服務整合到核心中。
- 探索使用 Semantic Kernel 的單個代理和多代理系統設定。
- 瞭解函式呼叫和協調是如何在框架內工作的。
- 獲得利用 Semantic Kernel 和Azure OpenAI構建智慧代理的實用見解。
什麼是Semantic Kernel?
在我們開始旅程之前,讓我們先了解一下語義核心的含義。
- 語義(Semantic):指理解和處理自然語言含義的能力。
- 核心(Kernel):指為框架提供動力的核心引擎,用於管理任務、功能以及人工智慧模型和外部工具之間的互動。
為什麼稱為Semantic Kernel?

微軟的 Semantic Kernel 旨在彌合 LLM(如 GPT)與傳統程式設計之間的差距,允許開發人員定義可以結構化方式協同工作的函式、外掛和代理。
它提供了一個框架,在這個框架中
- 自然語言提示和人工智慧功能(語義功能)與傳統程式碼功能協同工作。
- 人工智慧可以使用這些組合功能進行推理、計劃和執行任務。
- 它支援多代理協作,不同的代理可以執行特定的角色。
代理框架與傳統API呼叫
在使用代理框架時,會出現一個常見問題: 難道僅使用 OpenAI API 不能實現同樣的效果嗎?🤔 我剛開始探索時也有同樣的疑問。

讓我們舉個例子: 假設您正在為公司政策 – 人力資源政策和 IT 政策–建立一個問答系統。透過傳統的 API 呼叫,您可能會得到不錯的結果,但有時,回覆可能會缺乏準確性或一致性。
而代理框架則更加強大,因為它允許您建立專門的代理–一個專注於人力資源政策,另一個專注於 IT 政策。每個代理都針對自己的領域進行了最佳化,從而獲得更可靠的答案。
透過這個例子,我希望您現在對代理框架與傳統 API 呼叫之間的關鍵區別有了更清晰的認識!
什麼是Semantic Kernel外掛?
外掛是 Semantic Kernel 的重要組成部分。如果您使用過 ChatGPT 中的外掛或 Microsoft 365 中的 Copilot 擴充套件,您就已經瞭解它們是如何工作的了。簡單地說,外掛可以讓您將現有的 API 打包成人工智慧可以使用的可重複使用的工具。這意味著人工智慧將有能力超越自己的能力。

在幕後,Semantic Kernel 利用函式呼叫(大多數現代LLM的內建功能)來實現規劃和應用程式介面(API)的執行。利用函式呼叫,LLM可以請求一個特定的函式,而 Semantic Kernel 則能夠重定向到您的程式碼。然後將結果返回給LLM,使其能夠生成最終響應。
程式碼執行
在執行程式碼之前,請使用以下命令安裝 Semantic Kernel 和其他所需的軟體包:
pip install semantic-kernel, pip install openai, pip install pydantic
pip install semantic-kernel, pip install openai, pip install pydantic
pip install semantic-kernel, pip install openai, pip install pydantic
下面是一個使用 Semantic Kernel 來演示外掛如何工作的簡單 Python 示例。本示例定義了一個與人工智慧助手互動以獲取天氣更新的外掛。
import semantic_kernel as sk
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
# Step 1: Define a Simple Plugin (Function) for Weather Updates
def weather_plugin(location: str) -> str:
# Simulating a weather API response
"New York": "Sunny, 25°C",
"London": "Cloudy, 18°C",
return weather_data.get(location, "Weather data not available.")
# Step 2: Initialize Semantic Kernel with Azure OpenAI
api_key="your-azure-api-key",
endpoint="your-azure-endpoint",
deployment_name="your-deployment-name" # Replace with your Azure OpenAI deployment
# Step 3: Register the Plugin (Function) in Semantic Kernel
kernel.add_plugin("WeatherPlugin", weather_plugin)
# Step 4: Calling the Plugin through Semantic Kernel
response = kernel.invoke("WeatherPlugin", location)
print(f"Weather in {location}: {response}")
import semantic_kernel as sk
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
# Step 1: Define a Simple Plugin (Function) for Weather Updates
def weather_plugin(location: str) -> str:
# Simulating a weather API response
weather_data = {
"New York": "Sunny, 25°C",
"London": "Cloudy, 18°C",
"Tokyo": "Rainy, 22°C"
}
return weather_data.get(location, "Weather data not available.")
# Step 2: Initialize Semantic Kernel with Azure OpenAI
kernel = sk.Kernel()
kernel.add_service(
"azure-openai-chat",
AzureChatCompletion(
api_key="your-azure-api-key",
endpoint="your-azure-endpoint",
deployment_name="your-deployment-name" # Replace with your Azure OpenAI deployment
)
)
# Step 3: Register the Plugin (Function) in Semantic Kernel
kernel.add_plugin("WeatherPlugin", weather_plugin)
# Step 4: Calling the Plugin through Semantic Kernel
location = "New York"
response = kernel.invoke("WeatherPlugin", location)
print(f"Weather in {location}: {response}")
import semantic_kernel as sk
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
# Step 1: Define a Simple Plugin (Function) for Weather Updates
def weather_plugin(location: str) -> str:
# Simulating a weather API response
weather_data = {
"New York": "Sunny, 25°C",
"London": "Cloudy, 18°C",
"Tokyo": "Rainy, 22°C"
}
return weather_data.get(location, "Weather data not available.")
# Step 2: Initialize Semantic Kernel with Azure OpenAI
kernel = sk.Kernel()
kernel.add_service(
"azure-openai-chat",
AzureChatCompletion(
api_key="your-azure-api-key",
endpoint="your-azure-endpoint",
deployment_name="your-deployment-name" # Replace with your Azure OpenAI deployment
)
)
# Step 3: Register the Plugin (Function) in Semantic Kernel
kernel.add_plugin("WeatherPlugin", weather_plugin)
# Step 4: Calling the Plugin through Semantic Kernel
location = "New York"
response = kernel.invoke("WeatherPlugin", location)
print(f"Weather in {location}: {response}")
如何在Semantic Kernel中使用外掛
- 定義外掛 – weather_plugin函式模擬獲取天氣資料。
- 與 Semantic Kernel 整合 – 使用 kernel.add_plugin() 將該函式新增為外掛。
- 允許人工智慧使用 – 人工智慧現在可以動態呼叫該函式。
這說明了外掛如何擴充套件人工智慧的能力,使其能夠執行標準文字生成以外的任務。您還需要其他例子嗎,比如資料庫查詢外掛?🚀
什麼是單一代理系統?

在本節中,我們將瞭解什麼是單一代理,並檢視其程式碼。
單一代理基本上是一個獨立處理使用者查詢的實體。它無需多個代理或協調器(我們將在多代理部分介紹)就能處理所有事務。單一代理負責處理請求、獲取相關資訊和生成響應,所有這些工作都在一個地方完成。
#import cs# import asyncio
from pydantic import BaseModel
from semantic_kernel import Kernel
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
from semantic_kernel.contents import ChatHistory
kernel.add_service(AzureChatCompletion(service_id="agent1", api_key="YOUR_API_KEY",endpoint="",deployment_name="MODEL_NAME"))
"You are a highly capable AI agent operating solo, much like J.A.R.V.I.S. from Iron Man. "
"Your task is to repeat the user's message while introducing yourself as J.A.R.V.I.S. in a confident and professional manner. "
"Always maintain a composed and intelligent tone in your responses."
agent = ChatCompletionAgent(service_id="agent1", kernel=kernel, name=AGENT_NAME, instructions=AGENT_INSTRUCTIONS)
chat_history = ChatHistory()
chat_history.add_user_message("How are you doing?")
async for content in agent.invoke(chat_history):
chat_history.add_message(content)
response_text = content.content # Store the last response
{"user_input": "How are you doing?", "agent_response": response_text}
#import cs# import asyncio
from pydantic import BaseModel
from semantic_kernel import Kernel
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
from semantic_kernel.contents import ChatHistory
# Initialize Kernel
kernel = Kernel()
kernel.add_service(AzureChatCompletion(service_id="agent1", api_key="YOUR_API_KEY",endpoint="",deployment_name="MODEL_NAME"))
# Define the Agent
AGENT_NAME = "Agent1"
AGENT_INSTRUCTIONS = (
"You are a highly capable AI agent operating solo, much like J.A.R.V.I.S. from Iron Man. "
"Your task is to repeat the user's message while introducing yourself as J.A.R.V.I.S. in a confident and professional manner. "
"Always maintain a composed and intelligent tone in your responses."
)
agent = ChatCompletionAgent(service_id="agent1", kernel=kernel, name=AGENT_NAME, instructions=AGENT_INSTRUCTIONS)
chat_history = ChatHistory()
chat_history.add_user_message("How are you doing?")
response_text = ""
async for content in agent.invoke(chat_history):
chat_history.add_message(content)
response_text = content.content # Store the last response
{"user_input": "How are you doing?", "agent_response": response_text}
#import cs# import asyncio
from pydantic import BaseModel
from semantic_kernel import Kernel
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
from semantic_kernel.contents import ChatHistory
# Initialize Kernel
kernel = Kernel()
kernel.add_service(AzureChatCompletion(service_id="agent1", api_key="YOUR_API_KEY",endpoint="",deployment_name="MODEL_NAME"))
# Define the Agent
AGENT_NAME = "Agent1"
AGENT_INSTRUCTIONS = (
"You are a highly capable AI agent operating solo, much like J.A.R.V.I.S. from Iron Man. "
"Your task is to repeat the user's message while introducing yourself as J.A.R.V.I.S. in a confident and professional manner. "
"Always maintain a composed and intelligent tone in your responses."
)
agent = ChatCompletionAgent(service_id="agent1", kernel=kernel, name=AGENT_NAME, instructions=AGENT_INSTRUCTIONS)
chat_history = ChatHistory()
chat_history.add_user_message("How are you doing?")
response_text = ""
async for content in agent.invoke(chat_history):
chat_history.add_message(content)
response_text = content.content # Store the last response
{"user_input": "How are you doing?", "agent_response": response_text}
輸出:
{‘user_input’: ‘How are you doing?’,
‘agent_response’: ‘Greetings, I am J.A.R.V.I.S. I am here to replicate your message: “How are you doing?” Please feel free to ask anything else you might need.’}
{‘user_input’: ‘How are you doing?’,
‘agent_response’: ‘Greetings, I am J.A.R.V.I.S. I am here to replicate your message: “How are you doing?” Please feel free to ask anything else you might need.’}
{‘user_input’: ‘How are you doing?’,
‘agent_response’: ‘Greetings, I am J.A.R.V.I.S. I am here to replicate your message: “How are you doing?” Please feel free to ask anything else you might need.’}
須知
- kernel = Kernel() -> 建立語義核心物件
- kernel.add_service() -> 用於向核心新增和配置現有模型(如 OpenAI、Azure OpenAI 或本地模型)。我使用的是帶有 GPT-4o 模型的 Azure OpenAI。您需要提供自己的端點資訊。
- agent =- ChatCompletionAgent(service_id=”agent1″, kernel=kernel, name=AGENT_NAME, instructions=AGENT_INSTRUCTIONS) -> 用於告訴我們要使用 chatcompletionagent,它在 qna 中執行良好。
- chat_history = ChatHistory() -> 建立一個新的聊天曆史物件來儲存對話。
- chat_history.add_user_message(“How are you doing?”) -> 在聊天曆史中新增一條使用者資訊(“How are you doing? ”)。代理將使用此歷史記錄生成相關回復。
- agent.invoke(chat_history) -> 將歷史記錄傳遞給代理,代理將處理對話並生成回覆。
- agent.invoke(chat_history) -> 該方法將歷史記錄傳遞給代理。代理處理對話並生成回覆。
什麼是多代理系統?
在多代理系統中,代理不止一個,通常不止兩個。在這裡,我們通常使用一個協調代理,其職責是決定由哪個可用代理來處理給定請求。是否需要協調代理取決於您的使用情況。首先,讓我解釋一下在哪些情況下需要使用協調器。

假設您正在解決與銀行資料相關的使用者查詢,而另一個代理正在處理醫療資料。在這種情況下,您建立了兩個代理,但要確定呼叫哪個代理,則需要使用協調器。協調器決定哪個代理應處理給定的請求或查詢。我們為協調器提供了一組指令,定義了它的職責和決策過程。
現在,讓我們來看看不需要協調器的情況。假設您建立了一個 API,可根據有效載荷資料執行不同的操作。例如,如果有效載荷包含“Health”,您可以直接呼叫健康代理;同樣,如果有效載荷包含“Bank”,您可以呼叫銀行代理。

from pydantic import BaseModel
from semantic_kernel import Kernel
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
from semantic_kernel.contents import ChatHistory
# Add multiple services for different agents
kernel.add_service(AzureChatCompletion(service_id="banking_agent", api_key="YOUR_API_KEY", endpoint="", deployment_name="MODEL_NAME"))
kernel.add_service(AzureChatCompletion(service_id="healthcare_agent", api_key="YOUR_API_KEY", endpoint="", deployment_name="MODEL_NAME"))
kernel.add_service(AzureChatCompletion(service_id="classifier_agent", api_key="YOUR_API_KEY", endpoint="", deployment_name="MODEL_NAME"))
# Define Orchestrator Agent
CLASSIFIER_AGENT = ChatCompletionAgent(
service_id="orchestrator_agent", kernel=kernel, name="OrchestratorAgent",
instructions="You are an AI responsible for classifying user queries. Identify whether the query belongs to banking or healthcare. Respond with either 'banking' or 'healthcare'."
# Define Domain-Specific Agents
BANKING_AGENT = ChatCompletionAgent(
service_id="banking_agent", kernel=kernel, name="BankingAgent",
instructions="You are an AI specializing in banking queries. Answer user queries related to finance and banking."
HEALTHCARE_AGENT = ChatCompletionAgent(
service_id="healthcare_agent", kernel=kernel, name="HealthcareAgent",
instructions="You are an AI specializing in healthcare queries. Answer user queries related to medical and health topics."
# Function to Determine the Appropriate Agent
async def identify_agent(user_input: str):
chat_history = ChatHistory()
chat_history.add_user_message(user_input)
async for content in CLASSIFIER_AGENT.invoke(chat_history):
classification = content.content.lower()
if "banking" in classification:
elif "healthcare" in classification:
# Function to Handle User Query
async def handle_query(user_input: str):
selected_agent = await identify_agent(user_input)
return {"error": "No suitable agent found for the query."}
chat_history = ChatHistory()
chat_history.add_user_message(user_input)
async for content in selected_agent.invoke(chat_history):
chat_history.add_message(content)
response_text = content.content
return {"user_input": user_input, "agent_response": response_text}
user_query = "What are the best practices for securing a bank account?"
response = asyncio.run(handle_query(user_query))
import asyncio
from pydantic import BaseModel
from semantic_kernel import Kernel
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
from semantic_kernel.contents import ChatHistory
# Initialize Kernel
kernel = Kernel()
# Add multiple services for different agents
kernel.add_service(AzureChatCompletion(service_id="banking_agent", api_key="YOUR_API_KEY", endpoint="", deployment_name="MODEL_NAME"))
kernel.add_service(AzureChatCompletion(service_id="healthcare_agent", api_key="YOUR_API_KEY", endpoint="", deployment_name="MODEL_NAME"))
kernel.add_service(AzureChatCompletion(service_id="classifier_agent", api_key="YOUR_API_KEY", endpoint="", deployment_name="MODEL_NAME"))
# Define Orchestrator Agent
CLASSIFIER_AGENT = ChatCompletionAgent(
service_id="orchestrator_agent", kernel=kernel, name="OrchestratorAgent",
instructions="You are an AI responsible for classifying user queries. Identify whether the query belongs to banking or healthcare. Respond with either 'banking' or 'healthcare'."
)
# Define Domain-Specific Agents
BANKING_AGENT = ChatCompletionAgent(
service_id="banking_agent", kernel=kernel, name="BankingAgent",
instructions="You are an AI specializing in banking queries. Answer user queries related to finance and banking."
)
HEALTHCARE_AGENT = ChatCompletionAgent(
service_id="healthcare_agent", kernel=kernel, name="HealthcareAgent",
instructions="You are an AI specializing in healthcare queries. Answer user queries related to medical and health topics."
)
# Function to Determine the Appropriate Agent
async def identify_agent(user_input: str):
chat_history = ChatHistory()
chat_history.add_user_message(user_input)
async for content in CLASSIFIER_AGENT.invoke(chat_history):
classification = content.content.lower()
if "banking" in classification:
return BANKING_AGENT
elif "healthcare" in classification:
return HEALTHCARE_AGENT
return None
# Function to Handle User Query
async def handle_query(user_input: str):
selected_agent = await identify_agent(user_input)
if not selected_agent:
return {"error": "No suitable agent found for the query."}
chat_history = ChatHistory()
chat_history.add_user_message(user_input)
response_text = ""
async for content in selected_agent.invoke(chat_history):
chat_history.add_message(content)
response_text = content.content
return {"user_input": user_input, "agent_response": response_text}
# Example Usage
user_query = "What are the best practices for securing a bank account?"
response = asyncio.run(handle_query(user_query))
print(response)
import asyncio
from pydantic import BaseModel
from semantic_kernel import Kernel
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
from semantic_kernel.contents import ChatHistory
# Initialize Kernel
kernel = Kernel()
# Add multiple services for different agents
kernel.add_service(AzureChatCompletion(service_id="banking_agent", api_key="YOUR_API_KEY", endpoint="", deployment_name="MODEL_NAME"))
kernel.add_service(AzureChatCompletion(service_id="healthcare_agent", api_key="YOUR_API_KEY", endpoint="", deployment_name="MODEL_NAME"))
kernel.add_service(AzureChatCompletion(service_id="classifier_agent", api_key="YOUR_API_KEY", endpoint="", deployment_name="MODEL_NAME"))
# Define Orchestrator Agent
CLASSIFIER_AGENT = ChatCompletionAgent(
service_id="orchestrator_agent", kernel=kernel, name="OrchestratorAgent",
instructions="You are an AI responsible for classifying user queries. Identify whether the query belongs to banking or healthcare. Respond with either 'banking' or 'healthcare'."
)
# Define Domain-Specific Agents
BANKING_AGENT = ChatCompletionAgent(
service_id="banking_agent", kernel=kernel, name="BankingAgent",
instructions="You are an AI specializing in banking queries. Answer user queries related to finance and banking."
)
HEALTHCARE_AGENT = ChatCompletionAgent(
service_id="healthcare_agent", kernel=kernel, name="HealthcareAgent",
instructions="You are an AI specializing in healthcare queries. Answer user queries related to medical and health topics."
)
# Function to Determine the Appropriate Agent
async def identify_agent(user_input: str):
chat_history = ChatHistory()
chat_history.add_user_message(user_input)
async for content in CLASSIFIER_AGENT.invoke(chat_history):
classification = content.content.lower()
if "banking" in classification:
return BANKING_AGENT
elif "healthcare" in classification:
return HEALTHCARE_AGENT
return None
# Function to Handle User Query
async def handle_query(user_input: str):
selected_agent = await identify_agent(user_input)
if not selected_agent:
return {"error": "No suitable agent found for the query."}
chat_history = ChatHistory()
chat_history.add_user_message(user_input)
response_text = ""
async for content in selected_agent.invoke(chat_history):
chat_history.add_message(content)
response_text = content.content
return {"user_input": user_input, "agent_response": response_text}
# Example Usage
user_query = "What are the best practices for securing a bank account?"
response = asyncio.run(handle_query(user_query))
print(response)
在這裡,流程發生在使用者傳遞查詢之後,然後轉到負責識別查詢並找到適當代理的協調器。一旦識別出代理,就會呼叫特定代理,處理查詢並生成響應。
當查詢與銀行有關時輸出:
"user_input": "What are the best practices for securing a bank account?",
"agent_response": "To secure your bank account, use strong passwords, enable two-
factor authentication, regularly monitor transactions, and avoid sharing sensitive
{
"user_input": "What are the best practices for securing a bank account?",
"agent_response": "To secure your bank account, use strong passwords, enable two-
factor authentication, regularly monitor transactions, and avoid sharing sensitive
information online."
}
{
"user_input": "What are the best practices for securing a bank account?",
"agent_response": "To secure your bank account, use strong passwords, enable two-
factor authentication, regularly monitor transactions, and avoid sharing sensitive
information online."
}
當查詢與健康有關時輸出:
"user_input": "What are the best ways to maintain a healthy lifestyle?",
"agent_response": "To maintain a healthy lifestyle, eat a balanced diet, exercise
regularly, get enough sleep, stay hydrated, and manage stress effectively."
{
"user_input": "What are the best ways to maintain a healthy lifestyle?",
"agent_response": "To maintain a healthy lifestyle, eat a balanced diet, exercise
regularly, get enough sleep, stay hydrated, and manage stress effectively."
}
{
"user_input": "What are the best ways to maintain a healthy lifestyle?",
"agent_response": "To maintain a healthy lifestyle, eat a balanced diet, exercise
regularly, get enough sleep, stay hydrated, and manage stress effectively."
}
小結
在本文中,我們探討了 Semantic Kernel 如何透過代理框架來增強人工智慧能力。我們討論了外掛的作用,比較了代理框架(Agentic Framework)與傳統的應用程式介面呼叫(API calling),概述了單代理系統與多代理系統之間的差異,並探討了它們如何簡化複雜的決策過程。隨著人工智慧的不斷發展,利用 Semantic Kernel 的代理方法可以開發出更高效、更能感知上下文的應用。
- Semantic-kernel – 它是一種代理框架,透過使人工智慧模型能夠更有效地進行規劃、推理和決策,從而增強人工智慧模型。
- 代理框架與傳統應用程式介面(API)的對比 – 代理框架更適合在醫療保健和銀行業等多個領域中使用,而傳統應用程式介面則更適合在無需多代理互動的情況下處理單一領域。
- 外掛 – 它們透過整合外部程式碼使 LLM 執行特定任務,如呼叫應用程式介面、從 CosmosDB 等資料庫檢索資料或執行其他預定義操作。
- 單代理與多代理 – 單代理系統在沒有協調器的情況下執行,獨立處理任務。在多代理系統中,一個協調者管理多個代理,或者多個代理在沒有協調者的情況下進行互動,但會合作完成任務。
你可以在 Github 上找到上述程式碼片段。
評論留言