请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

不知道为撒没有按照想法去输出日志

import asyncio

from langchain_core.messages import HumanMessage, AIMessage, ToolMessage
from mcp import StdioServerParameters, stdio_client, ClientSession
from langchain_mcp_adapters.tools import load_mcp_tools
from langgraph.prebuilt import create_react_agent
from bailian.common import llm  # 你自己的大模型封装(保持不动)


# ========================================
# 获取 MCP Tools 并运行 agent
# ========================================
async def mcp_playwright_tools():
    # 1. 定义 MCP server 参数(这里用 Playwright MCP)
    server_params = StdioServerParameters(
        command="npx",
        args=["@playwright/mcp@latest"]  # 确保本地能运行 npx
    )

    # 2. 建立与 MCP server 的通信
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            # 初始化 MCP 会话
            await session.initialize()

            # 3. 加载 MCP 提供的工具
            tools = await load_mcp_tools(session)
            print("已加载工具:", [t.name for t in tools])

            # 4. 创建一个 ReAct agent,绑定大模型和 MCP 工具
            agent = create_react_agent(model=llm, tools=tools, debug=True)

            # 5. 发送用户输入给 agent
            response = await agent.ainvoke(
                input={
                    "messages": [
                        ("user", "在百度中查询北京今天的天气,然后告诉我天气情况后结束")
                    ]
                }
            )

            # 6. 从响应中取出所有消息
            messages = response["messages"]

            # 7. 遍历消息并分类打印
            for message in messages:
                # 用户消息
                if isinstance(message, HumanMessage):
                    print("用户:", message.content)

                # 助理消息(可能是调用工具,也可能是普通回答)
                elif isinstance(message, AIMessage):
                    if message.tool_calls:
                        # AI 调用了工具
                        for tool_call in message.tool_calls:
                            print("调用[调用工具]:", tool_call["name"], tool_call["args"])
                    elif message.content:
                        # AI 普通回答
                        print("助理:", message.content)

                # 工具执行结果
                elif isinstance(message, ToolMessage):
                    # 注意:content 有些是 dict,有些是 str,这里统一处理
                    result = message.content
                    if isinstance(result, dict) and "message" in result:
                        result = result["message"]
                    print("调用[工具返回结果]:", message.name, result)


# ========================================
# 程序入口
# ========================================
if __name__ == "__main__":
    asyncio.run(mcp_playwright_tools())

日志截图如下:
图片描述
我尝试用ai改了还是不行,最开始MCP用老师你课上那个打开浏览器后就一直卡住了,我换成第一个浏览器正常了他会自己去查询天气,但是日志我按照课上讲的代码,输出后还是这么大坨的日志
图片描述

正在回答 回答被采纳积分+3

1回答

Sam 2025-08-20 10:28:29

看你的截图,确实没有按照和课程一样的格式输出日志。需要确认下你的langgraph版本号是多少,我看下是否存在更新的情况

0 回复 有任何疑惑可以回复我~
  • 提问者 从未定义 #1
    dependencies = [
        "langchain>=0.3.27",
        "langchain-community>=0.3.27",
        "langchain-experimental>=0.3.4",
        "langchain-mcp-adapters>=0.1.9",
        "langchain-ollama>=0.3.6",
        "langchain-openai>=0.3.28",
        "langgraph>=0.6.5",
        "moviepy>=1.0.3",
        "numpy>=1.21.0",
        "openai>=1.99.1",
        "opencv-python>=4.8.0",
        "pydantic>=2.11.7",
    ]
    回复 有任何疑惑可以回复我~ 2025-08-20 10:35:44
  • 提问者 从未定义 #2
    安装【langgraph】时候的日志:
    (base) (ai-agent-test) PS E:\agentlist\ai-agent-test> uv add langgraph
    Resolved 85 packages in 2.06s
    Prepared 6 packages in 249ms
    ░░░░░░░░░░░░░░░░░░░░ [0/6] Installing wheels...
    warning: Failed to hardlink files; falling back to full copy. This may lead to degraded performance.
             If the cache and target directories are on different filesystems, hardlinking may not be supported.
             If this is intentional, set `export UV_LINK_MODE=copy` or use `--link-mode=copy` to suppress this warning.
    Installed 6 packages in 89ms
     + langgraph==0.6.5
     + langgraph-checkpoint==2.1.1
     + langgraph-prebuilt==0.6.4
     + langgraph-sdk==0.2.2
     + ormsgpack==1.10.0
     + xxhash==3.5.0
    回复 有任何疑惑可以回复我~ 2025-08-20 10:37:29
问题已解决,确定采纳
还有疑问,暂不采纳
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号