Posted on 2025/08/09, 11:10 AM By admin22
LangChainからMCPサーバを使うテストです。LMStudioでもできますが、いろいろ試して理解を深めます。
https://decode.red/net/archives/2208
参考)https://note.com/genaird/n/n89954c59c7e6
モデルは LMStudioのGemmaを使用します。
インストール
pip install langchain-mcp-adapters
pip install langgraph
pip install langchain_openai
client.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
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(base_url="http://192.168.0.xxx:1234/v1", api_key="not-needed", temperature=0.7) server_params = StdioServerParameters( command="python", args=["server.py"], ) async def run_agent(): async with stdio_client(server_params) as (read, write): async with ClientSession(read, write) as session: await session.initialize() tools = await load_mcp_tools(session) agent = create_react_agent(model, tools) #agent_response = await agent.ainvoke({"messages": "what's (3 + 5) x 12 ?"}) agent_response = await agent.ainvoke({"messages": "11 + 22 ?"}) return agent_response if __name__ == "__main__": result = asyncio.run(run_agent()) print(result) |
server.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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") |
参考サイトにある、かっこ付きの計算はできなかったので、簡単なものにしました。ToolExecutorなるものを使用するらしいのですが、ライブラリのバージョンが違いうまくいかず。。
もう少しLangGraphを勉強してからまた試したいと思います。
Categories: 未分類 タグ: LLM