自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

AI無邊界:通過MCP實(shí)現(xiàn)不同智能體框架的協(xié)作(含代碼)

人工智能 服務(wù)器產(chǎn)品
MCP實(shí)現(xiàn)的不同智能體框架協(xié)作具有重要的現(xiàn)實(shí)意義。它打破了框架的獨(dú)立性限制,用戶可以根據(jù)不同任務(wù)的需求,自由選擇和組合來自不同供應(yīng)商的智能體,充分發(fā)揮每個(gè)智能體的優(yōu)勢。

在人工智能飛速發(fā)展的當(dāng)下,智能體框架如雨后春筍般不斷涌現(xiàn)。從LangChain利用高度抽象的方式構(gòu)建智能體,到CAMEL - AI為用戶提供細(xì)致配置選項(xiàng)來創(chuàng)建智能體,不同框架各顯神通。但這些框架之間就像說著不同“方言”的個(gè)體,彼此溝通困難重重。直到模型上下文協(xié)議(Model Context Protocol,MCP)的出現(xiàn),才為打破這一僵局帶來了希望,開啟了不同智能體框架協(xié)作的新篇章。

一、智能體框架的“語言不通”困境

LangChain和CAMEL - AI是眾多智能體框架中的典型代表,它們在構(gòu)建智能體的方式上差異顯著。以創(chuàng)建智能體為例,LangChain可以借助強(qiáng)大的抽象能力,簡潔地完成智能體的構(gòu)建。在使用ChatOpenAI模型時(shí),只需指定模型名稱和溫度參數(shù)等關(guān)鍵信息,就能快速搭建一個(gè)智能體:

agent = ChatOpenAI(
    model="gpt-4o",
    temperature=0.2
)

而CAMEL - AI則更注重用戶對每個(gè)配置細(xì)節(jié)的把控,通過ModelFactory來創(chuàng)建模型,再基于模型構(gòu)建聊天智能體:

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
)

這些差異使得不同框架下的智能體難以直接交流。就好比生活在不同地區(qū)的人,各自說著獨(dú)特的方言,無法順暢溝通。這種“語言不通”的狀況極大地限制了智能體之間的協(xié)作,阻礙了人工智能發(fā)揮更大的效能。

二、MCP:跨越智能體框架鴻溝的橋梁

MCP作為一項(xiàng)關(guān)鍵技術(shù),為解決智能體框架間的通信難題提供了有效的方案。它是一種開放標(biāo)準(zhǔn),致力于在AI模型、外部工具以及不同智能體之間建立安全、雙向的連接。形象地說,MCP就如同AI領(lǐng)域的“USB - C接口”,能夠輕松實(shí)現(xiàn)數(shù)據(jù)的傳輸,讓整個(gè)系統(tǒng)高效運(yùn)行,同時(shí)保障數(shù)據(jù)的安全性。

MCP的核心優(yōu)勢在于它能夠突破簡單的客戶端 - 服務(wù)器模式的局限,實(shí)現(xiàn)不同AI框架智能體之間的直接對話。它將每個(gè)智能體都轉(zhuǎn)變?yōu)榧仁强蛻舳擞质欠?wù)器的角色,構(gòu)建起一個(gè)通用的翻譯層,讓智能體在內(nèi)部使用各自的“語言”,而在外部通過MCP進(jìn)行統(tǒng)一的通信。

MCP的架構(gòu)包含四個(gè)關(guān)鍵組件,共同支撐起智能體之間的通信。協(xié)議翻譯器負(fù)責(zé)將智能體的本地消息格式(如JSON、字典、提示等)轉(zhuǎn)化為統(tǒng)一的Markdown風(fēng)格模式,使所有智能體都能理解;通信層承擔(dān)消息的傳輸任務(wù),支持HTTP、WebSocket、STDIO等多種傳輸方式,同時(shí)確保消息可靠排隊(duì)、接收確認(rèn)以及處理實(shí)時(shí)流的服務(wù)器發(fā)送事件(SSE);上下文管理器同步每個(gè)智能體的內(nèi)存和狀態(tài),保證對話過程中信息不會(huì)丟失;工具集成器則負(fù)責(zé)映射和執(zhí)行外部工具調(diào)用(如API、數(shù)據(jù)庫、自定義函數(shù)),并確保在不同智能體間保持一致的調(diào)用格式。

三、搭建智能體通信的橋梁:以Camel/Langchain為例

為了實(shí)現(xiàn)不同智能體框架的通信,需要?jiǎng)?chuàng)建專門的適配器。以連接CAMEL - AI和Langchain框架為例,構(gòu)建的CamelMCPAdapter適配器就像是一位精通兩種語言的外交官。

CamelMCPAdapter類繼承自MCPAgent,在初始化時(shí),它會(huì)接收一系列參數(shù),包括名稱、傳輸方式、客戶端模式、CAMEL智能體實(shí)例以及系統(tǒng)消息等。如果沒有提供CAMEL智能體實(shí)例,會(huì)拋出錯(cuò)誤,以確保適配器能夠正常工作。

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.")

當(dāng)消息從其他智能體傳來時(shí),適配器會(huì)先接收MCP格式的消息,然后將其翻譯成CAMEL AI能理解的格式,傳遞給CAMEL智能體進(jìn)行處理。接著,它會(huì)把CAMEL智能體的響應(yīng)轉(zhuǎn)換回MCP格式,并發(fā)送給目標(biāo)接收者。

消息在不同智能體之間傳遞遵循特定的流程。首先是消息創(chuàng)建,智能體A以其本地格式創(chuàng)建消息;然后進(jìn)行翻譯,智能體A的適配器將消息翻譯成標(biāo)準(zhǔn)的MCP格式;之后通過通信層傳輸消息,到達(dá)智能體B;智能體B的適配器接收消息并翻譯成智能體B的本地格式,智能體B進(jìn)行處理并生成響應(yīng);最后響應(yīng)沿著相同的路徑返回給智能體A。在這個(gè)過程中,消息處理程序起著關(guān)鍵作用,它根據(jù)消息類型進(jìn)行正確的路由,確保任務(wù)請求得到處理,其他智能體的結(jié)果能創(chuàng)建新的對話任務(wù)。

要構(gòu)建Langchain - Camel通信網(wǎng)絡(luò),首先需要初始化兩個(gè)框架的智能體。對于Langchain智能體,通過以下步驟創(chuàng)建:先使用ChatOpenAI創(chuàng)建語言模型,設(shè)置模型為“gpt - 4o - mini”,溫度為0.7;接著定義提示模板,包含系統(tǒng)消息、用戶輸入占位符和一個(gè)虛擬工具(因?yàn)镺penAI的函數(shù)智能體至少需要一個(gè)工具);最后使用這些組件創(chuàng)建智能體,并將其包裝在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創(chuàng)建模型實(shí)例,設(shè)置模型平臺(tái)為OPENAI,模型類型為GPT_4O_MINI,溫度為0.7,再定義系統(tǒng)提示并創(chuàng)建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)

初始化完智能體后,需要?jiǎng)?chuàng)建一個(gè)共享的傳輸層用于通信,并為每個(gè)智能體創(chuàng)建MCP適配器。然后將智能體連接到傳輸層,并在后臺(tái)任務(wù)中啟動(dòng)它們。最后,生成初始消息并發(fā)送給目標(biāo)智能體,開始智能體之間的對話。

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)

四、智能體協(xié)作的實(shí)際應(yīng)用與深遠(yuǎn)意義

當(dāng)運(yùn)行上述示例時(shí),會(huì)看到詳細(xì)的日志信息展示智能體之間的對話流程。從LangchainAgent發(fā)送初始消息,到CamelAgent接收并處理,再到雙方不斷交換任務(wù)結(jié)果,整個(gè)過程清晰可見,這充分證明了不同智能體框架之間能夠?qū)崿F(xiàn)無縫通信。

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實(shí)現(xiàn)的不同智能體框架協(xié)作具有重要的現(xiàn)實(shí)意義。它打破了框架的獨(dú)立性限制,用戶可以根據(jù)不同任務(wù)的需求,自由選擇和組合來自不同供應(yīng)商的智能體,充分發(fā)揮每個(gè)智能體的優(yōu)勢。在一個(gè)項(xiàng)目中,可以將擅長研究的智能體、擅長總結(jié)的智能體和擅長創(chuàng)意寫作的智能體組合在一起,形成一個(gè)專業(yè)的團(tuán)隊(duì),共同完成復(fù)雜的任務(wù)。

這種協(xié)作模式還促進(jìn)了AI生態(tài)系統(tǒng)的增長。開發(fā)者能夠創(chuàng)建專門的智能體,并使其與現(xiàn)有的解決方案無縫集成,而無需從頭開始編寫所有代碼,大大提高了開發(fā)效率。對于企業(yè)來說,減少了對單一AI框架供應(yīng)商的依賴,降低了供應(yīng)商鎖定的風(fēng)險(xiǎn),不同供應(yīng)商的智能體可以協(xié)同工作,為企業(yè)提供更靈活、更強(qiáng)大的AI解決方案。

從實(shí)際應(yīng)用場景來看,CAMEL AI智能體在模擬場景和協(xié)調(diào)復(fù)雜多智能體交互方面表現(xiàn)出色,例如在虛擬世界的構(gòu)建、角色扮演游戲的劇情生成等方面具有獨(dú)特優(yōu)勢;而LangChain智能體在處理結(jié)構(gòu)化線性工作流程和工具集成方面更為擅長,如自動(dòng)化辦公流程、數(shù)據(jù)分析任務(wù)等。通過MCP,將兩者的優(yōu)勢結(jié)合起來,可以為更多領(lǐng)域帶來創(chuàng)新的解決方案。

責(zé)任編輯:武曉燕 來源: 大模型之路
相關(guān)推薦

2018-03-12 19:45:13

華為云軟件開發(fā)開發(fā)云

2025-04-03 07:06:35

2025-04-07 09:00:00

AI趨勢智能體Agent

2025-04-01 08:05:00

智能體人工智能MCP

2025-04-14 09:00:00

數(shù)據(jù)泄露AI AgentMCP協(xié)議安全

2025-04-10 09:42:51

2019-02-20 13:25:28

無邊界網(wǎng)絡(luò)網(wǎng)絡(luò)安全網(wǎng)絡(luò)攻擊

2023-11-30 16:34:18

2023-11-22 12:41:42

AI模型

2025-03-25 12:40:54

2014-07-25 13:45:15

2012-05-24 11:53:52

華為寬帶

2025-04-07 02:00:00

2021-01-22 10:41:40

人工智能開源深度學(xué)習(xí)

2017-05-18 19:42:27

無邊界安全志翔科技

2010-10-27 16:19:58

無邊界網(wǎng)絡(luò)架構(gòu)無線產(chǎn)品思科

2010-11-01 21:49:05

思科

2018-08-23 20:55:00

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號