forked from mcp-use/mcp-use
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlangchain_integration_example.py
More file actions
78 lines (60 loc) · 2.13 KB
/
langchain_integration_example.py
File metadata and controls
78 lines (60 loc) · 2.13 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import asyncio
from dataclasses import dataclass
from dotenv import load_dotenv
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from mcp_use import MCPClient
from mcp_use.agents.adapters import LangChainAdapter
# This example demonstrates how to use our integration
# adapters to use MCP tools and convert to the right format.
# In particularly, this example uses the LangChainAdapter.
load_dotenv()
# We use a dataclass here, but Pydantic models are also supported.
@dataclass
class ResponseFormat:
"""Response schema for the agent."""
# AirBnb response (available dates, prices, and relevant information)
relevant_response: str
async def main():
config = {
"mcpServers": {
"airbnb": {
"command": "npx",
"args": ["-y", "@openbnb/mcp-server-airbnb", "--ignore-robots-txt"],
},
}
}
try:
client = MCPClient(config=config)
# Creates the adapter for LangChain's format
adapter = LangChainAdapter()
# Convert tools from active connectors to the LangChain's format
await adapter.create_all(client)
# List concatenation (if you loaded all tools)
langchain_tools = adapter.tools + adapter.resources + adapter.prompts
# Create chat model
model = init_chat_model("gpt-4o-mini", temperature=0.5, timeout=10, max_tokens=1000)
# Create the LangChain agent
agent = create_agent(
model=model,
tools=langchain_tools,
system_prompt="You are a helpful assistant",
response_format=ResponseFormat,
)
# Run the agent
result = await agent.ainvoke(
{
"messages": [
{
"role": "user",
"content": "Please tell me the cheapest hotel for two people in Trapani.",
}
]
}
)
print(result["structured_response"])
except Exception as e:
print(f"Error: {e}")
raise e
if __name__ == "__main__":
asyncio.run(main())