-
Notifications
You must be signed in to change notification settings - Fork 183
Expand file tree
/
Copy pathlangchainv1_mcp_http.py
More file actions
79 lines (65 loc) · 2.29 KB
/
langchainv1_mcp_http.py
File metadata and controls
79 lines (65 loc) · 2.29 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
79
"""LangChain v1 agent + MCP HTTP itinerary server example.
Prerequisite:
Start the local MCP server defined in `mcp_server_basic.py` on port 8000:
python examples/mcp_server_basic.py
"""
import asyncio
import logging
import os
import azure.identity
from dotenv import load_dotenv
from langchain.agents import create_agent
from langchain_core.messages import HumanMessage
from langchain_mcp_adapters.client import MultiServerMCPClient
from langchain_openai import ChatOpenAI
from rich.logging import RichHandler
logging.basicConfig(level=logging.WARNING, format="%(message)s", datefmt="[%X]", handlers=[RichHandler()])
logger = logging.getLogger("lang_itinerary")
load_dotenv(override=True)
API_HOST = os.getenv("API_HOST", "azure")
if API_HOST == "azure":
token_provider = azure.identity.get_bearer_token_provider(
azure.identity.DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
)
model = ChatOpenAI(
model=os.environ.get("AZURE_OPENAI_CHAT_DEPLOYMENT"),
base_url=os.environ["AZURE_OPENAI_ENDPOINT"] + "/openai/v1",
api_key=token_provider,
use_responses_api=True,
)
elif API_HOST == "ollama":
model = ChatOpenAI(
model=os.environ.get("OLLAMA_MODEL", "gemma4:e4b"),
base_url=os.environ.get("OLLAMA_ENDPOINT", "http://localhost:11434/v1"),
api_key="none",
use_responses_api=True,
)
else:
model = ChatOpenAI(
model=os.getenv("OPENAI_MODEL", "gpt-4o-mini"),
use_responses_api=True,
)
async def run_agent():
client = MultiServerMCPClient(
{
"itinerary": {
# Make sure you start your itinerary server on port 8000
"url": "http://localhost:8000/mcp/",
"transport": "streamable_http",
}
}
)
tools = await client.get_tools()
agent = create_agent(model, tools)
user_query = (
"Find me a hotel in San Francisco for 2 nights starting from 2026-01-01. "
"I need a hotel with free WiFi and a pool."
)
response = await agent.ainvoke({"messages": [HumanMessage(content=user_query)]})
final = response["messages"][-1].content
print(final)
def main():
asyncio.run(run_agent())
if __name__ == "__main__":
logger.setLevel(logging.INFO)
main()