AI無邊界:通過MCP實現不同智能體框架的協作(含代碼)
在人工智能飛速發展的當下,智能體框架如雨后春筍般不斷涌現。從LangChain利用高度抽象的方式構建智能體,到CAMEL - AI為用戶提供細致配置選項來創建智能體,不同框架各顯神通。但這些框架之間就像說著不同“方言”的個體,彼此溝通困難重重。直到模型上下文協議(Model Context Protocol,MCP)的出現,才為打破這一僵局帶來了希望,開啟了不同智能體框架協作的新篇章。
一、智能體框架的“語言不通”困境
LangChain和CAMEL - AI是眾多智能體框架中的典型代表,它們在構建智能體的方式上差異顯著。以創建智能體為例,LangChain可以借助強大的抽象能力,簡潔地完成智能體的構建。在使用ChatOpenAI模型時,只需指定模型名稱和溫度參數等關鍵信息,就能快速搭建一個智能體:
agent = ChatOpenAI(
model="gpt-4o",
temperature=0.2
)
而CAMEL - AI則更注重用戶對每個配置細節的把控,通過ModelFactory來創建模型,再基于模型構建聊天智能體:
model = ModelFactory.create(
model_platform=ModelPlatformType.ANTHROPIC,
model_type="claude-3-7-sonnet",
api_key=anthropic_api_key,
model_config_dict={"temperature": 0.4}
)
agent = ChatAgent(
system_message=sys_msg,
model=model
)
這些差異使得不同框架下的智能體難以直接交流。就好比生活在不同地區的人,各自說著獨特的方言,無法順暢溝通。這種“語言不通”的狀況極大地限制了智能體之間的協作,阻礙了人工智能發揮更大的效能。
二、MCP:跨越智能體框架鴻溝的橋梁
MCP作為一項關鍵技術,為解決智能體框架間的通信難題提供了有效的方案。它是一種開放標準,致力于在AI模型、外部工具以及不同智能體之間建立安全、雙向的連接。形象地說,MCP就如同AI領域的“USB - C接口”,能夠輕松實現數據的傳輸,讓整個系統高效運行,同時保障數據的安全性。
MCP的核心優勢在于它能夠突破簡單的客戶端 - 服務器模式的局限,實現不同AI框架智能體之間的直接對話。它將每個智能體都轉變為既是客戶端又是服務器的角色,構建起一個通用的翻譯層,讓智能體在內部使用各自的“語言”,而在外部通過MCP進行統一的通信。
MCP的架構包含四個關鍵組件,共同支撐起智能體之間的通信。協議翻譯器負責將智能體的本地消息格式(如JSON、字典、提示等)轉化為統一的Markdown風格模式,使所有智能體都能理解;通信層承擔消息的傳輸任務,支持HTTP、WebSocket、STDIO等多種傳輸方式,同時確保消息可靠排隊、接收確認以及處理實時流的服務器發送事件(SSE);上下文管理器同步每個智能體的內存和狀態,保證對話過程中信息不會丟失;工具集成器則負責映射和執行外部工具調用(如API、數據庫、自定義函數),并確保在不同智能體間保持一致的調用格式。
三、搭建智能體通信的橋梁:以Camel/Langchain為例
為了實現不同智能體框架的通信,需要創建專門的適配器。以連接CAMEL - AI和Langchain框架為例,構建的CamelMCPAdapter適配器就像是一位精通兩種語言的外交官。
CamelMCPAdapter類繼承自MCPAgent,在初始化時,它會接收一系列參數,包括名稱、傳輸方式、客戶端模式、CAMEL智能體實例以及系統消息等。如果沒有提供CAMEL智能體實例,會拋出錯誤,以確保適配器能夠正常工作。
class CamelMCPAdapter(MCPAgent):
"""Adapter for Camel AI ChatAgent to work with MCP"""
def __init__(self,
name: str,
transport: Optional[MCPTransport] = None,
client_mode: bool = False,
camel_agent: ChatAgent = None,
system_message: str = "",
**kwargs):
# Initialize with system message
effective_system_message = system_message or (camel_agent.system_message.content
if camel_agent and camel_agent.system_message
else "Camel AI Assistant")
super().__init__(name=name, system_message=effective_system_message, **kwargs)
# Store important components
self.transport = transport
self.client_mode = client_mode
self.camel_agent = camel_agent
self.task_queue = asyncio.Queue()
if not self.camel_agent:
raise ValueError("A camel.agents.ChatAgent instance must be provided.")
當消息從其他智能體傳來時,適配器會先接收MCP格式的消息,然后將其翻譯成CAMEL AI能理解的格式,傳遞給CAMEL智能體進行處理。接著,它會把CAMEL智能體的響應轉換回MCP格式,并發送給目標接收者。
消息在不同智能體之間傳遞遵循特定的流程。首先是消息創建,智能體A以其本地格式創建消息;然后進行翻譯,智能體A的適配器將消息翻譯成標準的MCP格式;之后通過通信層傳輸消息,到達智能體B;智能體B的適配器接收消息并翻譯成智能體B的本地格式,智能體B進行處理并生成響應;最后響應沿著相同的路徑返回給智能體A。在這個過程中,消息處理程序起著關鍵作用,它根據消息類型進行正確的路由,確保任務請求得到處理,其他智能體的結果能創建新的對話任務。
要構建Langchain - Camel通信網絡,首先需要初始化兩個框架的智能體。對于Langchain智能體,通過以下步驟創建:先使用ChatOpenAI創建語言模型,設置模型為“gpt - 4o - mini”,溫度為0.7;接著定義提示模板,包含系統消息、用戶輸入占位符和一個虛擬工具(因為OpenAI的函數智能體至少需要一個工具);最后使用這些組件創建智能體,并將其包裝在AgentExecutor中。
def setup_langchain_agent():
# Create the language model with OpenAI
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.7)
# Define the prompt template with placeholders
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant called {agent_name}."),
("user", "{input}"),
("placeholder", "{agent_scratchpad}"),
])
# Create a simple tool (OpenAI functions agents require at least one tool)
@tool
def dummy_tool() -> str:
"""A placeholder tool that does nothing."""
return "This tool does nothing."
tools = [dummy_tool]
# Create the agent with the LLM, tools, and prompt
agent = create_openai_functions_agent(llm, tools, prompt)
# Wrap the agent in an executor and return it
return AgentExecutor(agent=agent, tools=tools, verbose=True)
對于CAMEL - AI智能體,使用ModelFactory創建模型實例,設置模型平臺為OPENAI,模型類型為GPT_4O_MINI,溫度為0.7,再定義系統提示并創建ChatAgent。
def setup_camel_agent():
# Create a model instance using CAMEL's ModelFactory
model_instance = ModelFactory.create(
model_platform=ModelPlatformType.OPENAI,
model_type=ModelType.GPT_4O_MINI,
model_config_dict={"temperature": 0.7}
)
# Define the system prompt for the agent
system_prompt = "You are a creative AI assistant called {agent_name}, skilled in writing poetry."
# Create and return the CAMEL ChatAgent
return ChatAgent(system_message=system_prompt, model=model_instance)
初始化完智能體后,需要創建一個共享的傳輸層用于通信,并為每個智能體創建MCP適配器。然后將智能體連接到傳輸層,并在后臺任務中啟動它們。最后,生成初始消息并發送給目標智能體,開始智能體之間的對話。
async def main():
# Load API keys from environment variables
load_dotenv()
# Initialize our agents from both frameworks
langchain_executor = setup_langchain_agent()
camel_chat_agent = setup_camel_agent()
# Create a shared transport layer for communication
transport = InMemoryTransport()
# Create MCP adapters for each agent
langchain_adapter = LangchainMCPAdapter(
name="LangchainAgent",
agent_executor=langchain_executor,
transport=transport
)
camel_adapter = CamelMCPAdapter(
name="CamelAgent",
camel_agent=camel_chat_agent,
transport=transport
)
# Connect each agent to the transport layer
await transport.connect("LangchainAgent")
await transport.connect("CamelAgent")
# Start both agents running in background tasks
task1 = asyncio.create_task(langchain_adapter.run())
task2 = asyncio.create_task(camel_adapter.run())
# Give the agents a moment to start up properly
await asyncio.sleep(2)
# Generate initial message
initial_message = {
"type": "task",
"task_id": initial_task_id,
"description": "Hello CamelAgent, let's discuss AI ethics.",
"sender": "LangchainAgent",
"reply_to": "LangchainAgent"
}
# Send initial message
await transport.send_message(target="CamelAgent", message=initial_message)
四、智能體協作的實際應用與深遠意義
當運行上述示例時,會看到詳細的日志信息展示智能體之間的對話流程。從LangchainAgent發送初始消息,到CamelAgent接收并處理,再到雙方不斷交換任務結果,整個過程清晰可見,這充分證明了不同智能體框架之間能夠實現無縫通信。
INFO - [LangchainAgent] Sending initial message to CamelAgent...
INFO - [InMemoryTransport] Message queued for 'CamelAgent' from 'LangchainAgent'.
INFO - [CamelAgent] Processing message: {'type': 'task', 'task_id': 'conv_start_44b4eea6-75bd-4cec-a074-f42aa4be9455', 'description': 'Hello CamelAgent, lets discuss AI ethics.', 'sender': 'LangchainAgent', 'reply_to': 'LangchainAgent'}
INFO - [CamelAgent] Starting execution of task...
INFO - [LangchainAgent] Received task_result from CamelAgent: "Hello LangchainAgent! While I'm primarily focused on poetry, I can certainly appreciate the intricacies of building multi-agent systems. Would you like me to express those ideas in poetic form?"
INFO - [CamelAgent] Received task_result from LangchainAgent: "Absolutely! I would love to see your thoughts on multi-agent systems expressed in poetry. Please share your verse!"
INFO - [LangchainAgent] Received task_result from CamelAgent: "In a realm where wisdom seeks to bind,
A gathering of minds, uniquely designed.
Each agent distinct, with purpose to claim,
Yet harmony beckons through collaborative aim..."
MCP實現的不同智能體框架協作具有重要的現實意義。它打破了框架的獨立性限制,用戶可以根據不同任務的需求,自由選擇和組合來自不同供應商的智能體,充分發揮每個智能體的優勢。在一個項目中,可以將擅長研究的智能體、擅長總結的智能體和擅長創意寫作的智能體組合在一起,形成一個專業的團隊,共同完成復雜的任務。
這種協作模式還促進了AI生態系統的增長。開發者能夠創建專門的智能體,并使其與現有的解決方案無縫集成,而無需從頭開始編寫所有代碼,大大提高了開發效率。對于企業來說,減少了對單一AI框架供應商的依賴,降低了供應商鎖定的風險,不同供應商的智能體可以協同工作,為企業提供更靈活、更強大的AI解決方案。
從實際應用場景來看,CAMEL AI智能體在模擬場景和協調復雜多智能體交互方面表現出色,例如在虛擬世界的構建、角色扮演游戲的劇情生成等方面具有獨特優勢;而LangChain智能體在處理結構化線性工作流程和工具集成方面更為擅長,如自動化辦公流程、數據分析任務等。通過MCP,將兩者的優勢結合起來,可以為更多領域帶來創新的解決方案。