LangChain 模型上下文協議
MCP 源於解決大型語言模型(LLM)應用的一個關鍵限制,即它們與外部數據源和工具隔離的問題。
MCP 源於解決大型語言模型(LLM)應用的一個關鍵限制,即它們與外部數據源和工具隔離的問題。
LLM 驅動的應用程序的一個主要關注點是數據交付。將數據傳遞給 LLM 進行推理,這是 RAG 實現、微調以及 MCP 的目標。
MCP 的主要目的是標準化 LLM 驅動的應用程序連接到各種系統的機制,如下圖所示:
1、消除自定義集成
將 AI 代理 / LLM 驅動的應用程序與外部數據源集成存在挑戰。
已經有許多嘗試通過利用 GUI、網頁瀏覽器和網絡搜索來實現某種無縫集成。所有這些途徑都有其優勢和劣勢。
MCP 有潛力作爲一個通用接口,可以將其視爲 AI 的虛擬 / 軟件版本 USB-C。
它能夠使 LLM/AI 代理與外部資源之間的數據交換變得無縫、安全和可擴展。
MCP 採用_客戶端 - 服務器_架構,其中 MCP 主機(AI 應用程序)與 MCP 服務器(數據 / 工具提供者)通信。
開發者可以使用 MCP 構建可重用的模塊化連接器,爲流行的平臺提供預構建的服務器,從而創建一個社區驅動的生態系統。
MCP 的開源性質鼓勵創新,允許開發者擴展其功能,同時通過細粒度權限等功能保持安全性。
最終,MCP 旨在將 AI 代理從孤立的聊天機器人轉變爲與數字環境深度集成的上下文感知、互操作系統。
2、使用說明
Anthropic 的模型上下文協議(MCP)是一個開源協議,用於連接 LLM 與上下文、工具和提示。它擁有越來越多的連接到各種工具或數據源的服務器。在這裏,我們將展示如何將任何 MCP 服務器連接到 LangGraph 代理並使用 MCP 工具……
如果你像我一樣,無論多麼簡單的原型工作都能帶來極大的清晰感和理解力;至少在我自己的腦海中是這樣的。
要開始,請打開終端應用程序…… 以下是在 MacBook 上找到它的位置
在終端窗口中,創建兩個標籤頁;其中一個用於運行服務器,另一個用於運行客戶端。
創建虛擬環境以安裝和運行代碼是一個好習慣;下面的命令創建名爲MCP_Demo
的虛擬環境。
python3 -m venv MCP_Demo
然後運行以下命令以激活(進入)虛擬環境:
source MCP_Demo/bin/activate
你會看到你的命令提示符更新爲(MCP_Demo)
。
按順序運行以下代碼行:
pip install langchain-mcp-adapters
pip install langchain-mcp-adapters
export OPENAI_API_KEY=<your_api_key>
將文本<your_api_key>
替換爲你的 OpenAI API 密鑰。
在其中一個終端標籤頁中,創建一個文本文件:vim server.py
並將以下 Python 代碼粘貼進去:
# math_server.py
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Math")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers"""
return a + b
@mcp.tool()
def multiply(a: int, b: int) -> int:
"""Multiply two numbers"""
return a * b
if __name__ == "__main__":
mcp.run(transport="stdio")
關閉文本文件,啓動並運行服務器,使用以下命令:
python3 math_server.py
你不會看到任何輸出,終端標籤頁看起來會是這樣的:
現在我們將創建並運行客戶端……
當一個標籤頁中的 MCP 服務器正在運行時,轉到第二個標籤頁……
創建一個文件以粘貼客戶端代碼:vim client.py.
將以下代碼粘貼到文件中
# Create server parameters for stdio connection
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from langchain_mcp_adapters.tools import load_mcp_tools
from langgraph.prebuilt import create_react_agent
from langchain_openai import ChatOpenAI
import asyncio
model = ChatOpenAI(model="gpt-4o")
server_params = StdioServerParameters(
command="python",
# Make sure to update to the full absolute path to your math_server.py file
args=["math_server.py"],
)
async def run_agent():
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
# Initialize the connection
await session.initialize()
# Get tools
tools = await load_mcp_tools(session)
# Create and run the agent
agent = create_react_agent(model, tools)
agent_response = await agent.ainvoke({"messages": "what's (3 + 5) x 12?"})
return agent_response
# Run the async function
if __name__ == "__main__":
result = asyncio.run(run_agent())
print(result)
使用命令python3 client.py
運行客戶端。
客戶端將運行一次並結束,輸出如下:
{'messages':
[HumanMessage(content="what's (3 + 5) x 12?",
additional_kwargs={}, response_metadata={},
id='87a8b6b6-9add-4da7-aea5-1b197c0fc0f5'),
AIMessage(content='',
additional_kwargs={'tool_calls': [{'id': 'call_1eyRzR7WpKzhMXG4ZFQAJtUD',
'function':
{'arguments': '{"a": 3, "b": 5}', 'name': 'add'},
'type': 'function'},
{'id': 'call_q82CX807NC3T6nHMrhoHT46E',
'function':
{'arguments': '{"a": 8, "b": 12}', 'name': 'multiply'},
'type': 'function'}],
'refusal': None},
response_metadata={'token_usage':
{'completion_tokens': 51,
'prompt_tokens': 77,
'total_tokens': 128,
'completion_tokens_details':
{'accepted_prediction_tokens': 0,
'audio_tokens': 0,
'reasoning_tokens': 0,
'rejected_prediction_tokens': 0},
'prompt_tokens_details':
{'audio_tokens': 0,
'cached_tokens': 0}},
'model_name': 'gpt-4o-2024-08-06',
'system_fingerprint': 'fp_eb9dce56a8',
'finish_reason': 'tool_calls',
'logprobs': None},
id='run-13c01640-f92b-48b7-9340-c2ad983eb1c8-0',
tool_calls=[{'name': 'add', 'args': {'a': 3, 'b': 5},
'id': 'call_1eyRzR7WpKzhMXG4ZFQAJtUD',
'type': 'tool_call'}, {'name': 'multiply',
'args': {'a': 8, 'b': 12},
'id': 'call_q82CX807NC3T6nHMrhoHT46E',
'type': 'tool_call'}],
usage_metadata={'input_tokens': 77,
'output_tokens': 51,
'total_tokens': 128,
'input_token_details': {'audio': 0,
'cache_read': 0},
'output_token_details': {'audio': 0,
'reasoning': 0}}),
ToolMessage(content='8',
name='add',
id='f8e0aba5-7a62-44c6-92a3-5fe3b07c9bd5',
tool_call_id='call_1eyRzR7WpKzhMXG4ZFQAJtUD'),
ToolMessage(content='96',
name='multiply',
id='66b9bbd9-b99a-402f-b26c-df83f5a69fa3',
tool_call_id='call_q82CX807NC3T6nHMrhoHT46E'),
AIMessage(content='The result of \\((3 + 5) \\times 12\\) is 96.',
additional_kwargs={'refusal': None},
response_metadata={'token_usage': {'completion_tokens': 22,
'prompt_tokens': 143,
'total_tokens': 165,
'completion_tokens_details': {'accepted_prediction_tokens': 0,
'audio_tokens': 0,
'reasoning_tokens': 0,
'rejected_prediction_tokens': 0},
'prompt_tokens_details': {'audio_tokens': 0,
'cached_tokens': 0}},
'model_name': 'gpt-4o-2024-08-06',
'system_fingerprint': 'fp_eb9dce56a8',
'finish_reason': 'stop',
'logprobs': None},
id='run-6c00a336-7d52-4917-9186-b282a5984b10-0',
usage_metadata={'input_tokens': 143,
'output_tokens': 22,
'total_tokens': 165,
'input_token_details': {'audio': 0, 'cache_read': 0},
'output_token_details': {'audio': 0,
'reasoning': 0}})]}
3、結束語
MCP 是一種方便的集成方式,可以將 AI 代理與提供上下文和記憶的信息和服務結合起來。
聯繫我
最後,推薦大家關注一下開源項目:LangChat,Java 生態下的 AIGC 大模型產品解決方案。
-
LangChat 產品官網:https://langchat.cn/
-
Github: https://github.com/TyCoding/langchat
-
Gitee: https://gitee.com/langchat/langchat
-
微信:LangchainChat
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/q06yh4AVUnQO8MFWY808VQ