AI在线 AI在线

AI无边界:通过MCP实现不同智能体框架的协作(含代码)

作者:大模型之路
2025-04-28 08:29
在人工智能飞速发展的当下,智能体框架如雨后春笋般不断涌现。 从LangChain利用高度抽象的方式构建智能体,到CAMEL - AI为用户提供细致配置选项来创建智能体,不同框架各显神通。 但这些框架之间就像说着不同“方言”的个体,彼此沟通困难重重。

在人工智能飞速发展的当下,智能体框架如雨后春笋般不断涌现。从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,将两者的优势结合起来,可以为更多领域带来创新的解决方案。

相关标签:

相关资讯

Manus平替方案:用DeepSeek+MCP Server构建AI自主工作流

前言在AI技术日新月异的今天,我们正见证着LLM(大语言模型)从"能说会道"向"能工巧匠"的进化。 当Anthropic推出Model Context Protocol(MCP)时,它像一道闪电划破夜空——这个被称作AI界的USB-C的协议,正在重新定义人机协作的边界。 作为一个沉迷于技术探索的开发者,我始终在寻找让AI真正"落地"的方法。
4/16/2025 3:22:51 PM
后端小肥肠

mcp-agent发布:轻量级框架助力智能体应用高效构建

mcp-agent正式发布,作为一款基于模型上下文协议(MCP)的轻量级框架,旨在为开发者提供一个简化的智能体应用构建解决方案。 该框架不仅能够与其他MCP服务无缝集成,还具备高度的可组合性和可定制性,使得开发者能够更专注于核心业务逻辑的实现,而无需过多关注复杂的系统架构。 mcp-agent的设计理念是简洁而高效,它去除了传统框架中多余的模块,提供了一个轻量级的代理模式库。
4/21/2025 12:00:58 PM
AI在线

深度解析 MCP 与 AI 工具的未来

自 2023 年 OpenAI 发布函数调用功能以来,我一直在思考如何构建一个智能体与工具协同的生态系统。 随着基础模型的智能化程度提升,智能体与外部工具、数据和 API 的交互能力变得日益碎片化:开发者需要为每个集成系统单独实现包含特定业务逻辑的智能体。 显然,我们需要一个执行、数据获取和工具调用的标准接口。
4/2/2025 3:55:00 AM
MCP
  • 1