Files
agent/examples/mcp_modes/react_agent.py
2025-09-01 11:59:17 +08:00

34 lines
1.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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())