-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathmain.py
More file actions
60 lines (48 loc) · 2 KB
/
main.py
File metadata and controls
60 lines (48 loc) · 2 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
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_anthropic import ChatAnthropic
from dotenv import load_dotenv
import asyncio
import os
load_dotenv()
model = ChatAnthropic(model="claude-3-5-sonnet-20240620")
server_params = StdioServerParameters(
command="npx",
env={
"API_TOKEN": os.getenv("API_TOKEN"),
"BROWSER_AUTH": os.getenv("BROWSER_AUTH"),
"WEB_UNLOCKER_ZONE": os.getenv("WEB_UNLOCKER_ZONE"),
},
# Make sure to update to the full absolute path to your math_server.py file
args=["@brightdata/mcp"],
)
async def chat_with_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)
# Start conversation history
messages = [
{
"role": "system",
"content": "You can use multiple tools in sequence to answer complex questions. Think step by step.",
}
]
print("Type 'exit' or 'quit' to end the chat.")
while True:
user_input = input("\nYou: ")
if user_input.strip().lower() in {"exit", "quit"}:
print("Goodbye!")
break
# Add user message to history
messages.append({"role": "user", "content": user_input})
# Call the agent with the full message history
agent_response = await agent.ainvoke({"messages": messages})
# Extract agent's reply and add to history
ai_message = agent_response["messages"][-1].content
print(f"Agent: {ai_message}")
if __name__ == "__main__":
asyncio.run(chat_with_agent())