forked from lingyuzeng/agent
add mcp use method
This commit is contained in:
33
examples/mcp_modes/react_agent.py
Normal file
33
examples/mcp_modes/react_agent.py
Normal file
@@ -0,0 +1,33 @@
|
||||
# examples/mcp_modes/react_agent.py
|
||||
import os, asyncio
|
||||
from langchain_core.messages import HumanMessage
|
||||
from langgraph_qwen.mcp import create_qwen_agent_with_mcp_async
|
||||
|
||||
# 方式 A:直接在代码里声明服务器(HTTP + 本地 stdio 混用)
|
||||
SERVERS = {
|
||||
"weather": {
|
||||
"url": "http://127.0.0.1:8000/mcp/",
|
||||
"transport": "streamable_http",
|
||||
},
|
||||
# "airbnb": {"command":"npx","args":["-y","@openbnb/mcp-server-airbnb"],"transport":"stdio"},
|
||||
}
|
||||
|
||||
# 方式 B:集中配置文件(JSON/YAML),二选一:
|
||||
CONFIG_PATH = os.getenv("MCP_CONFIG_PATH") # 例如 ./mcp_servers.json 或 ./mcp_servers.yaml
|
||||
|
||||
async def main():
|
||||
# 任选其一:传 servers,或传 config_path,或两者都传(servers 会覆盖同名)
|
||||
agent = await create_qwen_agent_with_mcp_async(
|
||||
servers=SERVERS,
|
||||
config_path=CONFIG_PATH,
|
||||
tool_choice="auto",
|
||||
)
|
||||
res = await agent.ainvoke(
|
||||
{"messages": [HumanMessage(content="列出可用工具,然后任选一个演示调用,并用简洁中文总结。")]},
|
||||
config={"recursion_limit": 6}, # ★ 显式控制 ReAct 工具交互最大步数
|
||||
)
|
||||
print("=== Final ===")
|
||||
print(res["messages"][-1].content)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
Reference in New Issue
Block a user