OpenManus 通用智能体实践与代码分析
过程中出现了 OpenAI API error: Error code: 429 错误,原因是 RATE_LIMIT_EXCEEDED 请求 PPIO OpenAI API Server 太快了被限速。非卡点问题,具体解决办法待定。browser_use 工具 go_to_url 打开网页,但是进入了人机测试页面,这里显然有问题。这些旅行计划的 md 文件中具有第二次补充的详细信息,包括:5 da
目录
OpenManus
OpenManus 是一个开源的通用 AI 代理框架,旨在提供一个无需邀请码的 Manus 替代方案。该项目由 MetaGPT 团队成员开发,支持多种 LLM 模型和工具集成,能够执行各种复杂任务。
功能特性:
- 支持多种模型:PPIO DeepSeek、OpenAI、Azure AI、Anthropic Claude、Google Gemini、Ollama 等
- 支持多种工具:浏览器自动化、桌面自动化、代码执行、文件操作、网络搜索等
- 支持 Workflow 架构: 支持复杂任务的规划和执行。
- 支持 Multi-Agent 架构: 支持多个专业化代理协同工作,内涵 Manus、DataAnalysis Agent。
- 支持 MCP 协议:包括 Server 和 Client。
- 支持 Docker 沙盒:提供安全的代码执行环境。
底层技术:
- 编程语言:Python 3.12+
- 异步框架:asyncio + aiohttp
- 数据验证:Pydantic v2
- 协议支持:MCP (Model Context Protocol)
- 容器化:Docker + Docker Compose
- 设计模式:工厂模式、策略模式、观察者模式、单例模式
环境信息
- MacOS
- IDE:Kiro
- LLM:PPIO deepseek-v3.2-exp
- github:https://github.com/FoundationAgents/OpenManus
- commit:https://github.com/FoundationAgents/OpenManus/commit/67d6c1c00d10d34f43a38894df871ccc796a4bd4
- 科学上网
安装和运行 OpenManus
安装
$ curl -LsSf https://astral.sh/uv/install.sh | sh
$ source $HOME/.local/bin/env
$ git clone https://github.com/FoundationAgents/OpenManus.git
$ cd OpenManus
$ uv venv --python 3.12
$ source .venv/bin/activate
$ uv pip install -r requirements.txt
# 浏览器自动化工具(可选)
$ npm install -g playwright
$ playwright install
- bug:https://github.com/FoundationAgents/OpenManus/issues/1231
$ uv pip list | grep crawl4ai
crawl4ai 0.7.4
配置
PPIO OpenAI API 配置手册:
- https://ppio.com/model-api/console
- https://ppio.com/docs/third-party/openmanus-use#openmanus-ppio-llm-api
$ cd OpenManus
$ cp config/config.example-model-ppio.toml config/config.toml
$ vim config/config.toml
# Global LLM configuration
[llm] #PPIO:
api_type = 'ppio'
model = "deepseek/deepseek-v3.2-exp" # The LLM model to use
base_url = "https://api.ppinfra.com/v3/openai" # API endpoint URL
api_key = "XXX" # Your API key
max_tokens = 16000 # Maximum number of tokens in the response
temperature = 0.0 # Controls randomness
[llm.vision] #PPIO VISION:
api_type = 'ppio'
model = "qwen/qwen2.5-vl-72b-instruct" # The vision model to use
base_url = "https://api.ppinfra.com/v3/openai" # API endpoint URL for vision model
api_key = "XXX" # Your API key for vision model
max_tokens = 96000 # Maximum number of tokens in the response
temperature = 0.0 # Controls randomness for vision model
[daytona]
daytona_api_key = "XXX"
daytona_server_url = "https://app.daytona.io/api"
daytona_target = "us"
- bug:https://github.com/FoundationAgents/OpenManus/issues/1233
- 解决:https://app.daytona.io/dashboard/keys
运行
- Single-Agent 模式
$ uv pip install structlog
$ uv pip install daytona
$ python main.py
/Users/fanguiju/workspace/OpenManus/.venv/lib/python3.12/site-packages/pydantic/_internal/_config.py:345: UserWarning: Valid config keys have changed in V2:
* 'underscore_attrs_are_private' has been removed
warnings.warn(message, UserWarning)
INFO [browser_use] BrowserUse logging setup complete with level info
INFO [root] Anonymized telemetry enabled. See https://docs.browser-use.com/development/telemetry for more information.
/Users/fanguiju/workspace/OpenManus/.venv/lib/python3.12/site-packages/pydantic/_internal/_config.py:345: UserWarning: Valid config keys have changed in V2:
* 'underscore_attrs_are_private' has been removed
warnings.warn(message, UserWarning)
2025-10-03T14:56:08.544913Z [info ] Initializing Daytona sandbox configuration filename=sandbox.py func_name=<module> lineno=19
2025-10-03T14:56:08.544992Z [info ] Daytona API key configured successfully filename=sandbox.py func_name=<module> lineno=27
2025-10-03T14:56:08.545029Z [info ] Daytona server URL set to: https://app.daytona.io/api filename=sandbox.py func_name=<module> lineno=32
2025-10-03T14:56:08.545050Z [info ] Daytona target set to: us filename=sandbox.py func_name=<module> lineno=37
2025-10-03T14:56:08.545581Z [info ] Daytona client initialized filename=sandbox.py func_name=<module> lineno=42
Enter your prompt:
- bug:https://github.com/FoundationAgents/OpenManus/issues/1232
- 解决:
$ uv pip install structlog
$ uv pip install daytona
测试
第一次请求
第一次请求我们关注用户体验,即:输入和输出的效果。
- 输入:在输出了制定旅行计划的 User Prompt 之后,Agent 开始运行,调用了一系列的工具。途中,调用了 ask_human 工具,用于提示 User 继续补充详细的旅行计划信息。
Enter your prompt: Help me make a new plan to travel to Beijing.
......
2025-10-03 23:16:13.985 | INFO | app.agent.toolcall:execute_tool:180 - 🔧 Activating tool: 'ask_human'...
Bot: To create your perfect Beijing travel plan, I need some information:
1. Trip Duration: How many days do you plan to stay?
2. Budget Range: What's your daily budget for accommodation + activities?
3. Main Interests: History, food, shopping, nature, or mix?
4. Travel Style: Fast-paced sightseeing or relaxed exploration?
5. Travel Companions: Solo, couple, family, or group?
6. Season of Travel: When are you planning to visit?
7. Special Requirements: Any accessibility, dietary, or other needs?
You: I plan to travel to Beijing for about five days. My budget is about $1000, and I'm interested in the history and traditions of Beijing.
- 输出:最终创建了 workspace 目录并生成了多个旅行计划的 md 文件。
这些旅行计划的 md 文件中具有第二次补充的详细信息,包括:5 days、$1000、History 等细节。
第二次请求
第二次请求关注具体的执行步骤,总结具有以下几类步骤和工具执行。
- Thinking & browser_use & web_search:Agent 开始思考和推理,并选择了第一个工具 browser_use 用于进行 web_search。但是在自动打开了浏览器之后,只有空白页,所以报了 Error,原因未知。
2025-10-03 23:36:27.296 | INFO | app.agent.base:run:140 - Executing step 1/20
2025-10-03 23:36:30.565 | INFO | app.llm:update_token_count:243 - Token usage: Input=1827, Completion=63, Cumulative Input=1827, Cumulative Completion=63, Total=1890, Cumulative Total=1890
2025-10-03 23:36:30.566 | INFO | app.agent.toolcall:think:81 - ✨ Manus's thoughts: I'll help you create a comprehensive travel plan for Beijing! Let me gather some current information about Beijing travel to make the most up-to-date plan for you.
2025-10-03 23:36:30.566 | INFO | app.agent.toolcall:think:82 - 🛠️ Manus selected 1 tools to use
2025-10-03 23:36:30.566 | INFO | app.agent.toolcall:think:86 - 🧰 Tools being prepared: ['browser_use']
2025-10-03 23:36:30.567 | INFO | app.agent.toolcall:think:89 - 🔧 Tool arguments: {"action": "web_search", "query": "Beijing travel guide 2024 best attractions itinerary"}
2025-10-03 23:36:30.568 | INFO | app.agent.toolcall:execute_tool:180 - 🔧 Activating tool: 'browser_use'...
2025-10-03 23:36:32.065 | INFO | app.tool.web_search:_try_all_engines:299 - 🔎 Attempting search with Google...
2025-10-03 23:37:06.233 | INFO | app.agent.toolcall:act:150 - 🎯 Tool 'browser_use' completed its mission! Result: Observed output of cmd `browser_use` executed:
Error: Browser action 'web_search' failed: RetryError[<Future at 0x149b91910 state=finished raised ReadTimeout>]
- Thinking & browser_use & web_search:由于 Step 1 失败了,所以再次重试使用 browser_use。但还是失败,原因未知。
2025-10-03 23:37:06.233 | INFO | app.agent.base:run:140 - Executing step 2/20
2025-10-03 23:37:09.668 | INFO | app.llm:update_token_count:243 - Token usage: Input=2141, Completion=63, Cumulative Input=3968, Cumulative Completion=126, Total=2204, Cumulative Total=4094
2025-10-03 23:37:09.669 | INFO | app.agent.toolcall:think:81 - ✨ Manus's thoughts: I'll help you create a comprehensive travel plan for Beijing. Let me start by searching for current information about Beijing travel to gather the most up-to-date details.
2025-10-03 23:37:09.669 | INFO | app.agent.toolcall:think:82 - 🛠️ Manus selected 1 tools to use
2025-10-03 23:37:09.669 | INFO | app.agent.toolcall:think:86 - 🧰 Tools being prepared: ['browser_use']
2025-10-03 23:37:09.669 | INFO | app.agent.toolcall:think:89 - 🔧 Tool arguments: {"action": "web_search", "query": "Beijing travel guide 2024 attractions itinerary planning"}
2025-10-03 23:37:09.669 | INFO | app.agent.toolcall:execute_tool:180 - 🔧 Activating tool: 'browser_use'...
2025-10-03 23:37:09.671 | INFO | app.tool.web_search:_try_all_engines:299 - 🔎 Attempting search with Google...
2025-10-03 23:37:43.804 | INFO | app.agent.toolcall:act:150 - 🎯 Tool 'browser_use' completed its mission! Result: Observed output of cmd `browser_use` executed:
Error: Browser action 'web_search' failed: RetryError[<Future at 0x1491833e0 state=finished raised ReadTimeout>]
- Thinking & browser_use & go_to_url:Agent 重试 2 次 browser_use 还是空白页,所以换了 go_to_url 直接访问网页的方式。
2025-10-03 23:37:43.805 | INFO | app.agent.base:run:140 - Executing step 3/20
2025-10-03 23:37:47.712 | INFO | app.llm:update_token_count:243 - Token usage: Input=2456, Completion=78, Cumulative Input=6424, Cumulative Completion=204, Total=2534, Cumulative Total=6628
2025-10-03 23:37:47.713 | INFO | app.agent.toolcall:think:81 - ✨ Manus's thoughts: I see the browser is currently on a blank page. Let me try a different approach to search for Beijing travel information. I'll navigate directly to a travel website to gather information.
2025-10-03 23:37:47.713 | INFO | app.agent.toolcall:think:82 - 🛠️ Manus selected 1 tools to use
2025-10-03 23:37:47.714 | INFO | app.agent.toolcall:think:86 - 🧰 Tools being prepared: ['browser_use']
2025-10-03 23:37:47.714 | INFO | app.agent.toolcall:think:89 - 🔧 Tool arguments: {"action": "go_to_url", "url": "https://www.tripadvisor.com/Tourism-g294212-Beijing-Vacations.html"}
2025-10-03 23:37:47.714 | INFO | app.agent.toolcall:execute_tool:180 - 🔧 Activating tool: 'browser_use'...
2025-10-03 23:38:02.447 | INFO | app.agent.toolcall:act:150 - 🎯 Tool 'browser_use' completed its mission! Result: Observed output of cmd `browser_use` executed:
Navigated to https://www.tripadvisor.com/Tourism-g294212-Beijing-Vacations.html
browser_use 工具 go_to_url 打开网页,但是进入了人机测试页面,这里显然有问题。后面内容提取会失败。
但是我手动输入链接是可以正常打开网页的,原因未知。
- Thinking & browser_use & extract_content:Agent 打开网页之后,开始从网页提取内容。
2025-10-03 23:38:02.447 | INFO | app.agent.base:run:140 - Executing step 4/20
2025-10-03 23:38:08.234 | INFO | app.llm:update_token_count:243 - Token usage: Input=2781, Completion=84, Cumulative Input=9205, Cumulative Completion=288, Total=2865, Cumulative Total=9493
2025-10-03 23:38:08.235 | INFO | app.agent.toolcall:think:81 - ✨ Manus's thoughts: Great! I'm now on the TripAdvisor Beijing page. Let me extract the content to gather information about Beijing travel attractions, accommodations, and activities to create a comprehensive travel plan.
2025-10-03 23:38:08.235 | INFO | app.agent.toolcall:think:82 - 🛠️ Manus selected 1 tools to use
2025-10-03 23:38:08.235 | INFO | app.agent.toolcall:think:86 - 🧰 Tools being prepared: ['browser_use']
2025-10-03 23:38:08.235 | INFO | app.agent.toolcall:think:89 - 🔧 Tool arguments: {"action": "extract_content", "goal": "Extract information about Beijing's top attractions, popular activities, best time to visit, accommodation options, and travel tips"}
2025-10-03 23:38:08.235 | INFO | app.agent.toolcall:execute_tool:180 - 🔧 Activating tool: 'browser_use'...
2025-10-03 23:38:10.346 | INFO | app.llm:update_token_count:243 - Token usage: Input=326, Completion=54, Cumulative Input=9531, Cumulative Completion=342, Total=380, Cumulative Total=9873
2025-10-03 23:38:10.346 | INFO | app.agent.toolcall:act:150 - 🎯 Tool 'browser_use' completed its mission! Result: Observed output of cmd `browser_use` executed:
Extracted from page:
{'metadata': {'source': 'tripadvisor.com01234567'}, 'text': "Beijing's top attractions, popular activities, best time to visit, accommodation options, and travel tips"}
- Thinking & browser_use & scroll_down:上图可知,工具 browser_use 具有自动操作网页的能力,包括 scroll_down 向下滚动。
2025-10-03 23:38:10.346 | INFO | app.agent.base:run:140 - Executing step 5/20
2025-10-03 23:38:13.062 | INFO | app.llm:update_token_count:243 - Token usage: Input=3131, Completion=47, Cumulative Input=12662, Cumulative Completion=389, Total=3178, Cumulative Total=13051
2025-10-03 23:38:13.063 | INFO | app.agent.toolcall:think:81 - ✨ Manus's thoughts: Let me scroll down to see more content and then extract detailed information about Beijing's attractions and travel planning details.
2025-10-03 23:38:13.063 | INFO | app.agent.toolcall:think:82 - 🛠️ Manus selected 1 tools to use
2025-10-03 23:38:13.063 | INFO | app.agent.toolcall:think:86 - 🧰 Tools being prepared: ['browser_use']
2025-10-03 23:38:13.063 | INFO | app.agent.toolcall:think:89 - 🔧 Tool arguments: {"action": "scroll_down", "scroll_amount": 500}
2025-10-03 23:38:13.063 | INFO | app.agent.toolcall:execute_tool:180 - 🔧 Activating tool: 'browser_use'...
2025-10-03 23:38:13.067 | INFO | app.agent.toolcall:act:150 - 🎯 Tool 'browser_use' completed its mission! Result: Observed output of cmd `browser_use` executed:
Scrolled down by 500 pixels
- Thinking & browser_use & extract_content:继续提取内容。但显然无法提取。
2025-10-03 23:38:13.068 | INFO | app.agent.base:run:140 - Executing step 6/20
2025-10-03 23:38:16.483 | INFO | app.llm:update_token_count:243 - Token usage: Input=3428, Completion=65, Cumulative Input=16090, Cumulative Completion=454, Total=3493, Cumulative Total=16544
2025-10-03 23:38:16.484 | INFO | app.agent.toolcall:think:81 - ✨ Manus's thoughts: Let me extract more detailed content from the page to get comprehensive information about Beijing travel.
2025-10-03 23:38:16.484 | INFO | app.agent.toolcall:think:82 - 🛠️ Manus selected 1 tools to use
2025-10-03 23:38:16.484 | INFO | app.agent.toolcall:think:86 - 🧰 Tools being prepared: ['browser_use']
2025-10-03 23:38:16.485 | INFO | app.agent.toolcall:think:89 - 🔧 Tool arguments: {"action": "extract_content", "goal": "Extract detailed information about Beijing's top attractions, best time to visit, accommodation options, popular activities, and travel tips"}
2025-10-03 23:38:16.485 | INFO | app.agent.toolcall:execute_tool:180 - 🔧 Activating tool: 'browser_use'...
2025-10-03 23:38:18.056 | ERROR | app.llm:ask_tool:756 - OpenAI API error: Error code: 429 - {'code': 429, 'reason': 'RATE_LIMIT_EXCEEDED', 'message': 'You have exceeded the request rate limit. Please wait a short period before retrying your request or contact the support to increase your request rate limit.', 'metadata': {}}
2025-10-03 23:38:18.056 | ERROR | app.llm:ask_tool:760 - Rate limit exceeded. Consider increasing retry attempts.
2025-10-03 23:38:20.390 | ERROR | app.llm:ask_tool:756 - OpenAI API error: Error code: 429 - {'code': 429, 'reason': 'RATE_LIMIT_EXCEEDED', 'message': 'You have exceeded the request rate limit. Please wait a short period before retrying your request or contact the support to increase your request rate limit.', 'metadata': {}}
2025-10-03 23:38:20.390 | ERROR | app.llm:ask_tool:760 - Rate limit exceeded. Consider increasing retry attempts.
2025-10-03 23:38:23.478 | ERROR | app.llm:ask_tool:756 - OpenAI API error: Error code: 429 - {'code': 429, 'reason': 'RATE_LIMIT_EXCEEDED', 'message': 'You have exceeded the request rate limit. Please wait a short period before retrying your request or contact the support to increase your request rate limit.', 'metadata': {}}
2025-10-03 23:38:23.479 | ERROR | app.llm:ask_tool:760 - Rate limit exceeded. Consider increasing retry attempts.
2025-10-03 23:38:27.565 | ERROR | app.llm:ask_tool:756 - OpenAI API error: Error code: 429 - {'code': 429, 'reason': 'RATE_LIMIT_EXCEEDED', 'message': 'You have exceeded the request rate limit. Please wait a short period before retrying your request or contact the support to increase your request rate limit.', 'metadata': {}}
2025-10-03 23:38:27.566 | ERROR | app.llm:ask_tool:760 - Rate limit exceeded. Consider increasing retry attempts.
2025-10-03 23:38:33.209 | ERROR | app.llm:ask_tool:756 - OpenAI API error: Error code: 429 - {'code': 429, 'reason': 'RATE_LIMIT_EXCEEDED', 'message': 'You have exceeded the request rate limit. Please wait a short period before retrying your request or contact the support to increase your request rate limit.', 'metadata': {}}
2025-10-03 23:38:33.209 | ERROR | app.llm:ask_tool:760 - Rate limit exceeded. Consider increasing retry attempts.
2025-10-03 23:38:36.439 | ERROR | app.llm:ask_tool:756 - OpenAI API error: Error code: 429 - {'code': 429, 'reason': 'RATE_LIMIT_EXCEEDED', 'message': 'You have exceeded the request rate limit. Please wait a short period before retrying your request or contact the support to increase your request rate limit.', 'metadata': {}}
2025-10-03 23:38:36.441 | ERROR | app.llm:ask_tool:760 - Rate limit exceeded. Consider increasing retry attempts.
2025-10-03 23:38:36.441 | INFO | app.agent.toolcall:act:150 - 🎯 Tool 'browser_use' completed its mission! Result: Observed output of cmd `browser_use` executed:
Error: Browser action 'extract_content' failed: RetryError[<Future at 0x149cc4d10 state=finished raised RateLimitError>]
过程中出现了 OpenAI API error: Error code: 429 错误,原因是 RATE_LIMIT_EXCEEDED 请求 PPIO OpenAI API Server 太快了被限速。这个问题可考虑提高 API Server 的 Rate Limit,或降低 API Client 请求频率。
- https://ppio.com/docs/model/llm-rate-limits
- Thinking & browser_use & go_to_url:第一个 go_to_url 失败后,尝试 go_to_url 第二个网站。
2025-10-03 23:38:36.441 | INFO | app.agent.base:run:140 - Executing step 7/20
2025-10-03 23:38:38.745 | ERROR | app.llm:ask_tool:756 - OpenAI API error: Error code: 429 - {'code': 429, 'reason': 'RATE_LIMIT_EXCEEDED', 'message': 'You have exceeded the request rate limit. Please wait a short period before retrying your request or contact the support to increase your request rate limit.', 'metadata': {}}
2025-10-03 23:38:38.745 | ERROR | app.llm:ask_tool:760 - Rate limit exceeded. Consider increasing retry attempts.
2025-10-03 23:38:41.271 | ERROR | app.llm:ask_tool:756 - OpenAI API error: Error code: 429 - {'code': 429, 'reason': 'RATE_LIMIT_EXCEEDED', 'message': 'You have exceeded the request rate limit. Please wait a short period before retrying your request or contact the support to increase your request rate limit.', 'metadata': {}}
2025-10-03 23:38:41.271 | ERROR | app.llm:ask_tool:760 - Rate limit exceeded. Consider increasing retry attempts.
2025-10-03 23:38:44.570 | ERROR | app.llm:ask_tool:756 - OpenAI API error: Error code: 429 - {'code': 429, 'reason': 'RATE_LIMIT_EXCEEDED', 'message': 'You have exceeded the request rate limit. Please wait a short period before retrying your request or contact the support to increase your request rate limit.', 'metadata': {}}
2025-10-03 23:38:44.571 | ERROR | app.llm:ask_tool:760 - Rate limit exceeded. Consider increasing retry attempts.
2025-10-03 23:38:49.971 | INFO | app.llm:update_token_count:243 - Token usage: Input=3748, Completion=58, Cumulative Input=19838, Cumulative Completion=512, Total=3806, Cumulative Total=20350
2025-10-03 23:38:49.972 | INFO | app.agent.toolcall:think:81 - ✨ Manus's thoughts: Let me try a different approach and navigate to a different travel website to gather information about Beijing travel planning.
2025-10-03 23:38:49.972 | INFO | app.agent.toolcall:think:82 - 🛠️ Manus selected 1 tools to use
2025-10-03 23:38:49.972 | INFO | app.agent.toolcall:think:86 - 🧰 Tools being prepared: ['browser_use']
2025-10-03 23:38:49.973 | INFO | app.agent.toolcall:think:89 - 🔧 Tool arguments: {"action": "go_to_url", "url": "https://www.lonelyplanet.com/china/beijing"}
2025-10-03 23:38:49.973 | INFO | app.agent.toolcall:execute_tool:180 - 🔧 Activating tool: 'browser_use'...
2025-10-03 23:39:05.201 | INFO | app.agent.toolcall:act:150 - 🎯 Tool 'browser_use' completed its mission! Result: Observed output of cmd `browser_use` executed:
Navigated to https://www.lonelyplanet.com/china/beijing
- Thinking & browser_use & extract_content:访问网站继续提取内容。
2025-10-03 23:39:05.202 | INFO | app.agent.base:run:140 - Executing step 8/20
2025-10-03 23:39:13.340 | INFO | app.llm:update_token_count:243 - Token usage: Input=4058, Completion=74, Cumulative Input=23896, Cumulative Completion=586, Total=4132, Cumulative Total=24482
2025-10-03 23:39:13.343 | INFO | app.agent.toolcall:think:81 - ✨ Manus's thoughts: Great! I'm now on the Lonely Planet Beijing page. Let me extract the content to gather comprehensive information about Beijing travel.
2025-10-03 23:39:13.343 | INFO | app.agent.toolcall:think:82 - 🛠️ Manus selected 1 tools to use
2025-10-03 23:39:13.343 | INFO | app.agent.toolcall:think:86 - 🧰 Tools being prepared: ['browser_use']
2025-10-03 23:39:13.343 | INFO | app.agent.toolcall:think:89 - 🔧 Tool arguments: {"action": "extract_content", "goal": "Extract detailed information about Beijing travel including attractions, best time to visit, accommodation, transportation, food, and travel tips"}
2025-10-03 23:39:13.344 | INFO | app.agent.toolcall:execute_tool:180 - 🔧 Activating tool: 'browser_use'...
2025-10-03 23:39:16.571 | INFO | app.llm:update_token_count:243 - Token usage: Input=941, Completion=115, Cumulative Input=24837, Cumulative Completion=701, Total=1056, Cumulative Total=25538
2025-10-03 23:39:16.572 | INFO | app.agent.toolcall:act:150 - 🎯 Tool 'browser_use' completed its mission! Result: Observed output of cmd `browser_use` executed:
Extracted from page:
{'text': 'Beijing travel - Lonely Planet | China, Asia\n\nBeijing travel information including attractions, best time to visit, accommodation, transportation, food, and travel tips from Lonely Planet', 'metadata': {'source': 'Lonely Planet Beijing travel page'}}
- Thinking & browser_use & scroll_down:继续滚动并提取,最终提取到
2025-10-03 23:39:16.572 | INFO | app.agent.base:run:140 - Executing step 9/20
2025-10-03 23:39:19.976 | INFO | app.llm:update_token_count:243 - Token usage: Input=4419, Completion=39, Cumulative Input=29256, Cumulative Completion=740, Total=4458, Cumulative Total=29996
2025-10-03 23:39:19.977 | INFO | app.agent.toolcall:think:81 - ✨ Manus's thoughts: Let me scroll down to see more detailed content about Beijing travel information.
2025-10-03 23:39:19.978 | INFO | app.agent.toolcall:think:82 - 🛠️ Manus selected 1 tools to use
2025-10-03 23:39:19.978 | INFO | app.agent.toolcall:think:86 - 🧰 Tools being prepared: ['browser_use']
2025-10-03 23:39:19.978 | INFO | app.agent.toolcall:think:89 - 🔧 Tool arguments: {"action": "scroll_down", "scroll_amount": 800}
2025-10-03 23:39:19.978 | INFO | app.agent.toolcall:execute_tool:180 - 🔧 Activating tool: 'browser_use'...
2025-10-03 23:39:19.986 | INFO | app.agent.toolcall:act:150 - 🎯 Tool 'browser_use' completed its mission! Result: Observed output of cmd `browser_use` executed:
Scrolled down by 800 pixels
2025-10-03 23:39:19.986 | INFO | app.agent.base:run:140 - Executing step 10/20
2025-10-03 23:39:24.736 | INFO | app.llm:update_token_count:243 - Token usage: Input=5222, Completion=77, Cumulative Input=34478, Cumulative Completion=817, Total=5299, Cumulative Total=35295
2025-10-03 23:39:24.736 | INFO | app.agent.toolcall:think:81 - ✨ Manus's thoughts:
2025-10-03 23:39:24.737 | INFO | app.agent.toolcall:think:82 - 🛠️ Manus selected 1 tools to use
2025-10-03 23:39:24.737 | INFO | app.agent.toolcall:think:86 - 🧰 Tools being prepared: ['browser_use']
2025-10-03 23:39:24.737 | INFO | app.agent.toolcall:think:89 - 🔧 Tool arguments: {"action": "extract_content", "goal": "Extract comprehensive Beijing travel information including must-see attractions, recommended itinerary, best time to visit, accommodation options, local transportation, food recommendations, and practical travel tips"}
2025-10-03 23:39:24.737 | INFO | app.agent.toolcall:execute_tool:180 - 🔧 Activating tool: 'browser_use'...
2025-10-03 23:39:26.354 | ERROR | app.llm:ask_tool:756 - OpenAI API error: Error code: 429 - {'code': 429, 'reason': 'RATE_LIMIT_EXCEEDED', 'message': 'You have exceeded the request rate limit. Please wait a short period before retrying your request or contact the support to increase your request rate limit.', 'metadata': {}}
2025-10-03 23:39:26.355 | ERROR | app.llm:ask_tool:760 - Rate limit exceeded. Consider increasing retry attempts.
2025-10-03 23:39:28.775 | ERROR | app.llm:ask_tool:756 - OpenAI API error: Error code: 429 - {'code': 429, 'reason': 'RATE_LIMIT_EXCEEDED', 'message': 'You have exceeded the request rate limit. Please wait a short period before retrying your request or contact the support to increase your request rate limit.', 'metadata': {}}
2025-10-03 23:39:28.776 | ERROR | app.llm:ask_tool:760 - Rate limit exceeded. Consider increasing retry attempts.
2025-10-03 23:39:32.385 | ERROR | app.llm:ask_tool:756 - OpenAI API error: Error code: 429 - {'code': 429, 'reason': 'RATE_LIMIT_EXCEEDED', 'message': 'You have exceeded the request rate limit. Please wait a short period before retrying your request or contact the support to increase your request rate limit.', 'metadata': {}}
2025-10-03 23:39:32.386 | ERROR | app.llm:ask_tool:760 - Rate limit exceeded. Consider increasing retry attempts.
2025-10-03 23:39:35.046 | ERROR | app.llm:ask_tool:756 - OpenAI API error: Error code: 429 - {'code': 429, 'reason': 'RATE_LIMIT_EXCEEDED', 'message': 'You have exceeded the request rate limit. Please wait a short period before retrying your request or contact the support to increase your request rate limit.', 'metadata': {}}
2025-10-03 23:39:35.047 | ERROR | app.llm:ask_tool:760 - Rate limit exceeded. Consider increasing retry attempts.
2025-10-03 23:39:41.059 | ERROR | app.llm:ask_tool:756 - OpenAI API error: Error code: 429 - {'code': 429, 'reason': 'RATE_LIMIT_EXCEEDED', 'message': 'You have exceeded the request rate limit. Please wait a short period before retrying your request or contact the support to increase your request rate limit.', 'metadata': {}}
2025-10-03 23:39:41.060 | ERROR | app.llm:ask_tool:760 - Rate limit exceeded. Consider increasing retry attempts.
2025-10-03 23:39:58.069 | INFO | app.llm:update_token_count:243 - Token usage: Input=950, Completion=367, Cumulative Input=35428, Cumulative Completion=1184, Total=1317, Cumulative Total=36612
2025-10-03 23:39:58.071 | INFO | app.agent.toolcall:act:150 - 🎯 Tool 'browser_use' completed its mission! Result: Observed output of cmd `browser_use` executed:
Extracted from page:
{'text': "Beijing travel - Lonely Planet | China, Asia\n\nMust-see attractions:\n- Forbidden City (Imperial Palace)\n- Great Wall of China\n- Temple of Heaven\n- Summer Palace\n- Tiananmen Square\n- Hutongs (traditional alleyways)\n\nRecommended itinerary:\n- Day 1: Tiananmen Square, Forbidden City\n- Day 2: Great Wall day trip\n- Day 3: Temple of Heaven, Summer Palace\n- Day 4: Hutongs exploration, local markets\n\nBest time to visit:\n- Spring (April-May) and Autumn (September-October) for pleasant weather\n- Avoid summer heat and winter cold\n\nAccommodation options:\n- Hotels in Wangfujing area (central location)\n- Traditional courtyard hotels in hutongs\n- International chain hotels\n\nLocal transportation:\n- Beijing Subway (extensive network)\n- Buses\n- Taxis and ride-sharing services\n- Bicycle rentals\n\nFood recommendations:\n- Peking Duck\n- Dumplings (jiaozi)\n- Beijing noodles (zhajiangmian)\n- Street food in Wangfujing Snack Street\n- Traditional tea houses\n\nPractical travel tips:\n- Learn basic Mandarin phrases\n- Carry cash (many places don't accept cards)\n- Download translation apps\n- Get a Beijing Transportation Card\n- Respect local customs and traditions\n- Book attractions in advance during peak seasons", 'metadata': {'source': 'Lonely Planet Beijing travel guide'}}
从网站提取到的详细信息如下,包括了日程、时间、地点、食物等内容:
# Beijing Travel Guide
*Source: Lonely Planet Beijing travel guide*
## Must-See Attractions
- Forbidden City (Imperial Palace)
- Great Wall of China
- Temple of Heaven
- Summer Palace
- Tiananmen Square
- Hutongs (traditional alleyways)
## Recommended Itinerary
- **Day 1**: Tiananmen Square, Forbidden City
- **Day 2**: Great Wall day trip
- **Day 3**: Temple of Heaven, Summer Palace
- **Day 4**: Hutongs exploration, local markets
## Best Time to Visit
- Spring (April-May) and Autumn (September-October) for pleasant weather
- Avoid summer heat and winter cold
## Accommodation Options
- Hotels in Wangfujing area (central location)
- Traditional courtyard hotels in hutongs
- International chain hotels
## Local Transportation
- Beijing Subway (extensive network)
- Buses
- Taxis and ride-sharing services
- Bicycle rentals
## Food Recommendations
- Peking Duck
- Dumplings (jiaozi)
- Beijing noodles (zhajiangmian)
- Street food in Wangfujing Snack Street
- Traditional tea houses
## Practical Travel Tips
- Learn basic Mandarin phrases
- Carry cash (many places don't accept cards)
- Download translation apps
- Get a Beijing Transportation Card
- Respect local customs and traditions
- Book attractions in advance during peak seasons
- Thinking & str_replace_editor & create:提取网页内容后,Agent 通过 str_replace_editor 想创建 beijing_travel_plan,md 文件。但发现没有 workspace 这个目录,所以 Error。
2025-10-03 23:39:58.071 | INFO | app.agent.base:run:140 - Executing step 11/20
2025-10-03 23:40:38.313 | INFO | app.llm:update_token_count:243 - Token usage: Input=5317, Completion=1441, Cumulative Input=40745, Cumulative Completion=2625, Total=6758, Cumulative Total=43370
2025-10-03 23:40:38.314 | INFO | app.agent.toolcall:think:81 - ✨ Manus's thoughts: Perfect! I've gathered comprehensive information about Beijing travel from Lonely Planet. Now let me create a detailed travel plan document for you based on this information.
2025-10-03 23:40:38.314 | INFO | app.agent.toolcall:think:82 - 🛠️ Manus selected 1 tools to use
2025-10-03 23:40:38.314 | INFO | app.agent.toolcall:think:86 - 🧰 Tools being prepared: ['str_replace_editor']
2025-10-03 23:40:38.314 | INFO | app.agent.toolcall:think:89 - 🔧 Tool arguments: {"command": "create", "path": "/Users/fanguiju/workspace/OpenManus/workspace/beijing_travel_plan.md", "file_text": "# Beijing Travel Plan\n\n## Overview\nBeijing, China's capital city, offers a perfect blend of ancient history and modern development. This comprehensive travel plan covers must-see attractions, recommended itinerary, accommodation, transportation, and practical tips.\n\n## Must-See Attractions\n\n### 1. Forbidden City (Imperial Palace)\n- **Location**: Central Beijing\n- **Highlights**: Imperial palace complex with 980 buildings, home to Chinese emperors for 500 years\n- **Recommended Time**: 3-4 hours\n- **Tips**: Book tickets online in advance, arrive early to avoid crowds\n\n### 2. Great Wall of China\n- **Popular Sections**: Badaling (most popular), Mutianyu (less crowded), Jinshanling (hiking)\n- **Transportation**: Day tours available or take public transport\n- **Best Time**: Early morning to avoid crowds\n- **Duration**: Full day trip\n\n### 3. Temple of Heaven\n- **Location**: Southern Beijing\n- **Significance**: Imperial complex for prayer ceremonies\n- **Features**: Hall of Prayer for Good Harvests, Echo Wall\n- **Time**: 2-3 hours\n\n### 4. Summer Palace\n- **Location**: Northwest Beijing\n- **Features**: Imperial gardens, Kunming Lake, Longevity Hill\n- **Activities**: Boating, walking through traditional gardens\n- **Time**: 3-4 hours\n\n### 5. Tiananmen Square\n- **Location**: City center\n- **Landmarks**: Monument to the People's Heroes, Mao Zedong Mausoleum\n- **Nearby**: Forbidden City entrance\n- **Time**: 1-2 hours\n\n### 6. Hutongs (Traditional Alleyways)\n- **Areas**: Nanluoguxiang, Shichahai area\n- **Experience**: Traditional courtyard houses, local life, street food\n- **Activities**: Rickshaw tours, tea houses, local markets\n\n## Recommended 4-Day Itinerary\n\n### Day 1: Imperial Beijing\n- **Morning**: Tiananmen Square\n- **Afternoon**: Forbidden City\n- **Evening**: Wangfujing Street for shopping and dinner\n\n### Day 2: Great Wall Adventure\n- **Full Day**: Great Wall of China (Badaling or Mutianyu section)\n- **Evening**: Rest and local cuisine\n\n### Day 3: Cultural Exploration\n- **Morning**: Temple of Heaven\n- **Afternoon**: Summer Palace\n- **Evening**: Traditional Peking Duck dinner\n\n### Day 4: Local Experience\n- **Morning**: Hutong exploration and rickshaw tour\n- **Afternoon**: Local markets and tea house experience\n- **Evening**: Departure preparation\n\n## Best Time to Visit\n\n### Recommended Seasons:\n- **Spring** (April-May): Pleasant weather, blooming flowers\n- **Autumn** (September-October): Cool temperatures, clear skies\n\n### Seasons to Avoid:\n- **Summer** (June-August): Hot and humid, peak tourist season\n- **Winter** (December-February): Very cold, potential air pollution\n\n## Accommodation Options\n\n### By Location:\n- **Wangfujing Area**: Central location, shopping, restaurants\n- **Hutongs**: Traditional courtyard hotels, cultural experience\n- **Sanlitun**: Modern area, nightlife, international hotels\n\n### By Type:\n- **Luxury Hotels**: International chains in central areas\n- **Boutique Hotels**: Traditional courtyard accommodations\n- **Budget Options**: Hostels and budget hotels near subway stations\n\n## Transportation\n\n### Getting Around:\n- **Beijing Subway**: Extensive network, affordable, efficient\n- **Buses**: Extensive routes, very cheap\n- **Taxis**: Metered, use ride-hailing apps (Didi)\n- **Bicycle Rentals**: Available throughout the city\n\n### Transportation Card:\n- **Yikatong Card**: Rechargeable card for subway and buses\n- **Purchase**: Subway stations, convenience stores\n- **Benefits**: Discounts on transfers\n\n## Food and Dining\n\n### Must-Try Dishes:\n- **Peking Duck**: Famous roasted duck with pancakes\n- **Dumplings (Jiaozi)**: Various fillings, steamed or fried\n- **Beijing Noodles (Zhajiangmian)**: Noodles with soybean paste\n- **Hot Pot**: Interactive dining experience\n\n### Food Streets:\n- **Wangfujing Snack Street**: Street food and snacks\n- **Ghost Street (Guijie)**: Late-night dining\n- **Qianmen Street**: Traditional restaurants\n\n## Practical Travel Tips\n\n### Essential Preparations:\n- **Visa**: Apply for Chinese tourist visa in advance\n- **Currency**: Chinese Yuan (CNY), carry cash\n- **Language**: Learn basic Mandarin phrases\n- **Apps**: Download translation and map apps\n\n### Health and Safety:\n- **Air Quality**: Check pollution levels, consider masks\n- **Water**: Drink bottled water\n- **Food Safety**: Eat at busy, clean establishments\n\n### Cultural Etiquette:\n- **Tipping**: Not customary in China\n- **Bargaining**: Expected in markets, not in department stores\n- **Temples**: Dress modestly, be respectful\n- **Photography**: Ask permission before taking photos of people\n\n### Booking and Reservations:\n- **Attractions**: Book major attractions online in advance\n- **Hotels**: Book 2-3 months ahead for peak seasons\n- **Restaurants**: Reserve popular restaurants in advance\n\n## Budget Planning\n\n### Estimated Costs (per person):\n- **Accommodation**: $50-200 per night\n- **Food**: $15-50 per day\n- **Transportation**: $5-15 per day\n- **Attractions**: $20-50 per day\n- **Total Daily**: $90-315\n\n## Emergency Information\n\n### Important Contacts:\n- **Police**: 110\n- **Ambulance**: 120\n- **Fire**: 119\n- **Tourist Hotline**: 12301\n\n### Embassies:\n- Keep embassy contact information handy\n- Register with embassy if staying long-term\n\nThis comprehensive travel plan provides all the essential information for an unforgettable trip to Beijing. Adjust the itinerary based on your interests and available time!"}
2025-10-03 23:40:38.315 | INFO | app.agent.toolcall:execute_tool:180 - 🔧 Activating tool: 'str_replace_editor'...
2025-10-03 23:40:38.316 | INFO | app.agent.toolcall:act:150 - 🎯 Tool 'str_replace_editor' completed its mission! Result: Observed output of cmd `str_replace_editor` executed:
Error: Failed to write to /Users/fanguiju/workspace/OpenManus/workspace/beijing_travel_plan.md: [Errno 2] No such file or directory: '/Users/fanguiju/workspace/OpenManus/workspace/beijing_travel_plan.md'
2025-10-03 23:40:38.316 | INFO | app.agent.base:run:140 - Executing step 12/20
2025-10-03 23:40:41.827 | INFO | app.llm:update_token_count:243 - Token usage: Input=5512, Completion=53, Cumulative Input=46257, Cumulative Completion=2678, Total=5565, Cumulative Total=48935
2025-10-03 23:40:41.827 | INFO | app.agent.toolcall:think:81 - ✨ Manus's thoughts: Let me first check the current workspace directory and then create the Beijing travel plan file.
2025-10-03 23:40:41.828 | INFO | app.agent.toolcall:think:82 - 🛠️ Manus selected 1 tools to use
2025-10-03 23:40:41.828 | INFO | app.agent.toolcall:think:86 - 🧰 Tools being prepared: ['str_replace_editor']
2025-10-03 23:40:41.829 | INFO | app.agent.toolcall:think:89 - 🔧 Tool arguments: {"command": "view", "path": "/Users/fanguiju/workspace/OpenManus/workspace"}
2025-10-03 23:40:41.830 | INFO | app.agent.toolcall:execute_tool:180 - 🔧 Activating tool: 'str_replace_editor'...
2025-10-03 23:40:41.830 | INFO | app.agent.toolcall:act:150 - 🎯 Tool 'str_replace_editor' completed its mission! Result: Observed output of cmd `str_replace_editor` executed:
Error: The path /Users/fanguiju/workspace/OpenManus/workspace does not exist. Please provide a valid path.
- Thinking & str_replace_editor & view:工具 str_replace_editor 开始找可以使用的文件路径,并创建了 .md 文件。
2025-10-03 23:40:41.830 | INFO | app.agent.base:run:140 - Executing step 13/20
2025-10-03 23:40:52.607 | INFO | app.llm:update_token_count:243 - Token usage: Input=5656, Completion=37, Cumulative Input=51913, Cumulative Completion=2715, Total=5693, Cumulative Total=54628
2025-10-03 23:40:52.607 | INFO | app.agent.toolcall:think:81 - ✨ Manus's thoughts: Let me check what directories are available and then create the Beijing travel plan.
2025-10-03 23:40:52.608 | INFO | app.agent.toolcall:think:82 - 🛠️ Manus selected 1 tools to use
2025-10-03 23:40:52.608 | INFO | app.agent.toolcall:think:86 - 🧰 Tools being prepared: ['str_replace_editor']
2025-10-03 23:40:52.608 | INFO | app.agent.toolcall:think:89 - 🔧 Tool arguments: {"command": "view", "path": "/"}
2025-10-03 23:40:52.608 | INFO | app.agent.toolcall:execute_tool:180 - 🔧 Activating tool: 'str_replace_editor'...
2025-10-03 23:40:52.646 | INFO | app.agent.toolcall:act:150 - 🎯 Tool 'str_replace_editor' completed its mission! Result: Observed output of cmd `str_replace_editor` executed:
Here's the files and directories up to 2 levels deep in /, excluding hidden items:
/
......
2025-10-03 23:40:52.648 | INFO | app.agent.base:run:140 - Executing step 14/20
2025-10-03 23:41:47.025 | INFO | app.llm:update_token_count:243 - Token usage: Input=9323, Completion=1772, Cumulative Input=61236, Cumulative Completion=4487, Total=11095, Cumulative Total=65723
2025-10-03 23:41:47.026 | INFO | app.agent.toolcall:think:81 - ✨ Manus's thoughts: I can see the directory structure. Let me navigate to the user's home directory and create the Beijing travel plan there.
2025-10-03 23:41:47.026 | INFO | app.agent.toolcall:think:82 - 🛠️ Manus selected 1 tools to use
2025-10-03 23:41:47.027 | INFO | app.agent.toolcall:think:86 - 🧰 Tools being prepared: ['str_replace_editor']
2025-10-03 23:41:47.027 | INFO | app.agent.toolcall:think:89 - 🔧 Tool arguments: {"command": "create", "path": "/Users/fanguiju/beijing_travel_plan.md", "file_text": "# Beijing Travel Plan - Comprehensive 5-Day Itinerary\n\n## Overview\nBeijing, China's capital city, offers a perfect blend of ancient history and modern development. This 5-day itinerary covers the must-see attractions while providing authentic cultural experiences.\n\n## Best Time to Visit\n- **Spring (April-May)**: Pleasant weather, blooming flowers\n- **Autumn (September-October)**: Cool temperatures, clear skies\n- **Avoid**: Summer heat (June-August) and winter cold (December-February)\n\n## 5-Day Itinerary\n\n### Day 1: Imperial Beijing\n**Morning (9:00 AM - 12:00 PM)**\n- **Tiananmen Square** - The world's largest public square\n- **Forbidden City (Imperial Palace)** - Explore the magnificent imperial palace complex\n\n**Afternoon (1:00 PM - 5:00 PM)**\n- Continue exploring Forbidden City\n- **Jingshan Park** - Climb the hill for panoramic views of the Forbidden City\n\n**Evening (6:00 PM - 8:00 PM)**\n- **Wangfujing Street** - Shopping and dinner\n- Try authentic **Peking Duck** at a traditional restaurant\n\n### Day 2: The Great Wall Experience\n**Full Day (8:00 AM - 6:00 PM)**\n- **Great Wall of China** day trip\n- Recommended sections:\n - **Mutianyu**: Less crowded, cable car available\n - **Badaling**: Most famous but busier\n - **Jinshanling**: For hiking enthusiasts\n\n**Evening (7:00 PM - 9:00 PM)**\n- Relax and recover from the hike\n- Local dinner near your accommodation\n\n### Day 3: Imperial Parks & Temples\n**Morning (9:00 AM - 12:00 PM)**\n- **Temple of Heaven** - Imperial prayer complex for good harvests\n- Watch locals practicing tai chi and other traditional activities\n\n**Afternoon (1:00 PM - 5:00 PM)**\n- **Summer Palace** - Imperial garden with beautiful lakes and pavilions\n- Boat ride on Kunming Lake (seasonal)\n\n**Evening (6:00 PM - 8:00 PM)**\n- **Houhai Lake** area - Bars, restaurants, and nightlife\n- Traditional tea house experience\n\n### Day 4: Traditional Culture & Markets\n**Morning (9:00 AM - 12:00 PM)**\n- **Hutongs exploration** - Traditional alleyways\n- **Nanluoguxiang** - Famous hutong with shops and cafes\n- **Drum and Bell Towers** - Historical timekeeping towers\n\n**Afternoon (1:00 PM - 5:00 PM)**\n- **Panjiayuan Antique Market** (weekends only) or **Hongqiao Market**\n- **Silk Market** - Shopping for souvenirs\n\n**Evening (6:00 PM - 8:00 PM)**\n- **Wangfujing Snack Street** - Street food adventure\n- Try various local snacks and delicacies\n\n### Day 5: Modern Beijing & Departure\n**Morning (9:00 AM - 12:00 PM)**\n- **Olympic Park** - Bird's Nest Stadium and Water Cube\n- **798 Art District** - Contemporary art galleries\n\n**Afternoon (1:00 PM - 4:00 PM)**\n- Last-minute souvenir shopping\n- Prepare for departure\n\n## Accommodation Recommendations\n\n### Central Location (Wangfujing Area)\n- Luxury: The Peninsula Beijing, Grand Hyatt Beijing\n- Mid-range: Novotel Beijing Peace, Hilton Beijing Wangfujing\n- Budget: Holiday Inn Express Beijing Dongzhimen\n\n### Traditional Experience\n- **Courtyard hotels in hutongs** - Authentic traditional accommodation\n- **Sihe Hotel** - Traditional courtyard experience\n\n## Transportation Guide\n\n### Getting Around\n- **Beijing Subway**: Extensive network, affordable, efficient\n- **Buses**: Extensive routes, very cheap\n- **Taxis**: Metered, convenient for short distances\n- **Ride-sharing**: Didi (Chinese Uber)\n- **Bicycle rentals**: Available throughout the city\n\n### Essential Apps\n- **Didi** - Ride-hailing app\n- **Baidu Maps** or **Amap** - Navigation\n- **Pleco** - Chinese dictionary\n- **WeChat** - Payment and communication\n\n## Food & Dining\n\n### Must-Try Dishes\n- **Peking Duck** - The signature dish of Beijing\n- **Dumplings (Jiaozi)** - Various fillings and cooking styles\n- **Beijing Noodles (Zhajiangmian)** - Noodles with soybean paste\n- **Hot Pot** - Interactive dining experience\n- **Mongolian Barbecue** - DIY grilling\n\n### Recommended Areas\n- **Wangfujing Snack Street** - Street food\n- **Ghost Street (Guijie)** - Late-night dining\n- **Sanlitun** - International cuisine\n\n## Practical Information\n\n### Visa Requirements\n- Most visitors need a tourist visa (L visa)\n- Apply through Chinese embassy/consulate\n- Allow 4-6 weeks for processing\n\n### Currency & Payments\n- **Currency**: Chinese Yuan (CNY/RMB)\n- **Cash**: Essential - many places don't accept cards\n- **Mobile payments**: WeChat Pay and Alipay widely used\n- **ATMs**: Available but notify your bank before travel\n\n### Language\n- **Official language**: Mandarin Chinese\n- **Useful phrases**:\n - Hello: Nǐ hǎo (你好)\n - Thank you: Xièxiè (谢谢)\n - How much?: Duōshǎo qián? (多少钱?)\n - I don't understand: Wǒ tīng bù dǒng (我听不懂)\n\n### Health & Safety\n- **Tap water**: Not drinkable - buy bottled water\n- **Air quality**: Check AQI, consider masks if needed\n- **Emergency numbers**:\n - Police: 110\n - Ambulance: 120\n - Fire: 119\n\n## Budget Estimate (Per Person)\n\n### Accommodation (5 nights)\n- Budget: $200-300\n- Mid-range: $400-600\n- Luxury: $800+\n\n### Food & Dining\n- Street food: $5-10 per meal\n- Local restaurants: $10-20 per meal\n- Fine dining: $30+ per meal\n\n### Transportation\n- Subway/bus: $1-2 per trip\n- Taxis: $5-15 per trip\n- Great Wall tour: $50-100\n\n### Attractions\n- Forbidden City: $8-15\n- Great Wall: $10-20 (plus transportation)\n- Temple of Heaven: $5-10\n- Summer Palace: $5-10\n\n### Total Estimated Cost\n- Budget traveler: $500-700\n- Mid-range: $800-1200\n- Luxury: $1500+\n\n## Packing List\n- Comfortable walking shoes\n- Weather-appropriate clothing\n- Power adapter (Type A/I)\n- Portable charger\n- Hand sanitizer\n- Copies of important documents\n- Basic first aid kit\n- Reusable water bottle\n\n## Additional Tips\n- **Book in advance**: Popular attractions require advance booking\n- **Download offline maps**: Google Maps may not work well\n- **Learn basic phrases**: English is not widely spoken\n- **Respect local customs**: Remove shoes when entering homes/temples\n- **Bargain at markets**: Common practice except in fixed-price stores\n\nEnjoy your trip to Beijing! This ancient capital offers an unforgettable blend of history, culture, and modern Chinese life."}
2025-10-03 23:41:47.027 | INFO | app.agent.toolcall:execute_tool:180 - 🔧 Activating tool: 'str_replace_editor'...
2025-10-03 23:41:47.028 | INFO | app.agent.toolcall:act:150 - 🎯 Tool 'str_replace_editor' completed its mission! Result: Observed output of cmd `str_replace_editor` executed:
File created successfully at: /Users/fanguiju/beijing_travel_plan.md
- Thinking & str_replace_editor & str_replace:工具 str_replace_editor 开始 str_replace 编辑 .md 文件。
2025-10-03 23:41:47.028 | INFO | app.agent.base:run:140 - Executing step 15/20
2025-10-03 23:42:25.937 | INFO | app.llm:update_token_count:243 - Token usage: Input=9463, Completion=1482, Cumulative Input=70699, Cumulative Completion=5969, Total=10945, Cumulative Total=76668
2025-10-03 23:42:25.938 | INFO | app.agent.toolcall:think:81 - ✨ Manus's thoughts: Perfect! I've successfully created the Beijing travel plan file. Now let me add the comprehensive travel plan content based on the information I gathered from Lonely Planet.
2025-10-03 23:42:25.938 | INFO | app.agent.toolcall:think:82 - 🛠️ Manus selected 1 tools to use
2025-10-03 23:42:25.938 | INFO | app.agent.toolcall:think:86 - 🧰 Tools being prepared: ['str_replace_editor']
2025-10-03 23:42:25.939 | INFO | app.agent.toolcall:think:89 - 🔧 Tool arguments: {"command": "str_replace", "path": "/Users/fanguiju/beijing_travel_plan.md", "old_str": "", "new_str": "# Beijing Travel Plan\n\n## Overview\nBeijing, the capital of China, offers a perfect blend of ancient history and modern development. This comprehensive travel plan covers must-see attractions, itinerary suggestions, accommodation options, transportation, food recommendations, and practical travel tips.\n\n## Must-See Attractions\n\n### Historical & Cultural Sites\n- **Forbidden City (Imperial Palace)** - The world's largest palace complex, home to Chinese emperors for nearly 500 years\n- **Great Wall of China** - Visit Mutianyu or Badaling sections for breathtaking views\n- **Temple of Heaven** - Imperial complex where emperors prayed for good harvests\n- **Summer Palace** - Beautiful imperial garden with lakes, palaces, and temples\n- **Tiananmen Square** - The world's largest public square\n- **Hutongs** - Traditional alleyways offering glimpse into old Beijing life\n\n### Additional Notable Sites\n- **Lama Temple** - Magnificent Tibetan Buddhist temple\n- **Beihai Park** - Ancient imperial garden with a beautiful lake\n- **Ming Tombs** - Burial site of Ming Dynasty emperors\n- **798 Art District** - Contemporary art galleries in a former factory complex\n\n## Recommended Itinerary (4-5 Days)\n\n### Day 1: Imperial Beijing\n- **Morning**: Tiananmen Square and Forbidden City\n- **Afternoon**: Jingshan Park for panoramic city views\n- **Evening**: Wangfujing Street for shopping and dinner\n\n### Day 2: The Great Wall\n- **Full Day**: Great Wall day trip (Mutianyu section recommended)\n- **Evening**: Rest and local dinner\n\n### Day 3: Temple & Gardens\n- **Morning**: Temple of Heaven\n- **Afternoon**: Summer Palace\n- **Evening**: Houhai Lake area for bars and nightlife\n\n### Day 4: Traditional Beijing\n- **Morning**: Hutong exploration by rickshaw\n- **Afternoon**: Lama Temple and Confucius Temple\n- **Evening**: Peking Duck dinner at a traditional restaurant\n\n### Optional Day 5: Modern Beijing\n- **Morning**: 798 Art District\n- **Afternoon**: Silk Market or Panjiayuan Antique Market\n- **Evening**: Olympic Park (Bird's Nest and Water Cube)\n\n## Best Time to Visit\n\n### Ideal Seasons\n- **Spring (April-May)**: Pleasant weather, blooming flowers\n- **Autumn (September-October)**: Cool temperatures, clear skies\n\n### Seasons to Avoid\n- **Summer (June-August)**: Hot, humid, and crowded\n- **Winter (December-February)**: Very cold, but fewer tourists\n\n## Accommodation Options\n\n### By Area\n- **Wangfujing Area**: Central location, luxury hotels, shopping\n- **Hutongs**: Traditional courtyard hotels, cultural experience\n- **Sanlitun**: Modern area with international hotels and nightlife\n- **Dongcheng District**: Close to major attractions\n\n### Hotel Types\n- Luxury: Peninsula Beijing, Waldorf Astoria\n- Mid-range: Novotel, Holiday Inn\n- Budget: Hostels, traditional courtyard hotels\n\n## Local Transportation\n\n### Getting Around\n- **Beijing Subway**: Extensive network, affordable, efficient\n- **Buses**: Extensive routes, very cheap\n- **Taxis**: Metered, use ride-hailing apps (Didi)\n- **Bicycle Rentals**: Available throughout the city\n\n### Transportation Cards\n- **Beijing Transportation Card**: Convenient for subway and buses\n- **Single Journey Tickets**: Available at subway stations\n\n## Food & Dining\n\n### Must-Try Dishes\n- **Peking Duck** - The city's signature dish\n- **Dumplings (Jiaozi)** - Various fillings and cooking styles\n- **Beijing Noodles (Zhajiangmian)** - Noodles with soybean paste\n- **Hot Pot** - Interactive dining experience\n- **Mongolian Barbecue** - DIY grilling\n\n### Food Streets & Markets\n- **Wangfujing Snack Street**: Street food and snacks\n- **Ghost Street (Guijie)**: Late-night dining\n- **Qianmen Street**: Traditional snacks and restaurants\n\n### Dining Tips\n- Try local breakfast foods like jianbing (savory crepes)\n- Visit tea houses for traditional tea ceremonies\n- Don't miss the street food culture\n\n## Practical Travel Tips\n\n### Before You Go\n- **Visa**: Most visitors need a Chinese tourist visa\n- **Currency**: Chinese Yuan (CNY), carry cash as many places don't accept cards\n- **Language**: Learn basic Mandarin phrases\n- **Apps**: Download translation apps and maps\n\n### During Your Stay\n- **Health**: Drink bottled water, be cautious with street food\n- **Safety**: Generally safe, but beware of pickpockets in crowded areas\n- **Etiquette**: Respect local customs, temples, and traditions\n- **Bargaining**: Common in markets, not in department stores\n\n### Booking & Reservations\n- Book major attractions in advance during peak seasons\n- Consider guided tours for historical sites\n- Reserve popular restaurants in advance\n\n## Budget Planning\n\n### Estimated Daily Costs\n- **Budget**: ¥300-500 per day (hostels, street food, public transport)\n- **Mid-range**: ¥800-1500 per day (hotels, restaurants, some taxis)\n- **Luxury**: ¥2000+ per day (5-star hotels, fine dining, private tours)\n\n### Major Expenses\n- Accommodation: ¥200-2000+ per night\n- Attraction tickets: ¥30-60 per site\n- Food: ¥50-300 per meal\n- Transportation: ¥5-50 per trip\n\n## Emergency Information\n\n### Important Numbers\n- Police: 110\n- Fire: 119\n- Ambulance: 120\n- Tourist Hotline: 12301\n\n### Embassies\n- Keep embassy contact information handy\n- Register with your embassy if staying long-term\n\n## Packing List\n\n### Essentials\n- Passport and visa\n- Cash and credit cards\n- Comfortable walking shoes\n- Weather-appropriate clothing\n- Power adapter (Type A/I)\n\n### Recommended\n- Translation app\n- Offline maps\n- Hand sanitizer\n- Reusable water bottle\n- Small backpack for day trips\n\n---\n\n*This travel plan is based on current information and should be verified closer to your travel dates. Enjoy your trip to Beijing!*"}
2025-10-03 23:42:25.939 | INFO | app.agent.toolcall:execute_tool:180 - 🔧 Activating tool: 'str_replace_editor'...
2025-10-03 23:42:25.940 | INFO | app.agent.toolcall:act:150 - 🎯 Tool 'str_replace_editor' completed its mission! Result: Observed output of cmd `str_replace_editor` executed:
Error: No replacement was performed. Multiple occurrences of old_str `` in lines [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, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188]. Please ensure it is unique
2025-10-03 23:42:25.941 | INFO | app.agent.base:run:140 - Executing step 16/20
2025-10-03 23:42:29.428 | INFO | app.llm:update_token_count:243 - Token usage: Input=15474, Completion=55, Cumulative Input=86173, Cumulative Completion=6024, Total=15529, Cumulative Total=92197
2025-10-03 23:42:29.428 | INFO | app.agent.toolcall:think:81 - ✨ Manus's thoughts:
2025-10-03 23:42:29.428 | INFO | app.agent.toolcall:think:82 - 🛠️ Manus selected 1 tools to use
2025-10-03 23:42:29.429 | INFO | app.agent.toolcall:think:86 - 🧰 Tools being prepared: ['str_replace_editor']
2025-10-03 23:42:29.429 | INFO | app.agent.toolcall:think:89 - 🔧 Tool arguments: {"command": "view", "path": "/Users/fanguiju/beijing_travel_plan.md"}
2025-10-03 23:42:29.429 | INFO | app.agent.toolcall:execute_tool:180 - 🔧 Activating tool: 'str_replace_editor'...
2025-10-03 23:42:29.430 | INFO | app.agent.toolcall:act:150 - 🎯 Tool 'str_replace_editor' completed its mission! Result: Observed output of cmd `str_replace_editor` executed:
Here's the result of running `cat -n` on /Users/fanguiju/beijing_travel_plan.md:
1 # Beijing Travel Plan - Comprehensive 5-Day Itinerary
2
3 ## Overview
4 Beijing, China's capital city, offers a perfect blend of ancient history and modern development. This 5-day itinerary covers the must-see attractions while providing authentic cultural experiences.
5
6 ## Best Time to Visit
7 - **Spring (April-May)**: Pleasant weather, blooming flowers
8 - **Autumn (September-October)**: Cool temperatures, clear skies
9 - **Avoid**: Summer heat (June-August) and winter cold (December-February)
10
11 ## 5-Day Itinerary
12
13 ### Day 1: Imperial Beijing
14 **Morning (9:00 AM - 12:00 PM)**
15 - **Tiananmen Square** - The world's largest public square
16 - **Forbidden City (Imperial Palace)** - Explore the magnificent imperial palace complex
17
18 **Afternoon (1:00 PM - 5:00 PM)**
19 - Continue exploring Forbidden City
20 - **Jingshan Park** - Climb the hill for panoramic views of the Forbidden City
21
22 **Evening (6:00 PM - 8:00 PM)**
23 - **Wangfujing Street** - Shopping and dinner
24 - Try authentic **Peking Duck** at a traditional restaurant
25
26 ### Day 2: The Great Wall Experience
27 **Full Day (8:00 AM - 6:00 PM)**
28 - **Great Wall of China** day trip
29 - Recommended sections:
30 - **Mutianyu**: Less crowded, cable car available
31 - **Badaling**: Most famous but busier
32 - **Jinshanling**: For hiking enthusiasts
33
34 **Evening (7:00 PM - 9:00 PM)**
35 - Relax and recover from the hike
36 - Local dinner near your accommodation
37
38 ### Day 3: Imperial Parks & Temples
39 **Morning (9:00 AM - 12:00 PM)**
40 - **Temple of Heaven** - Imperial prayer complex for good harvests
41 - Watch locals practicing tai chi and other traditional activities
42
43 **Afternoon (1:00 PM - 5:00 PM)**
44 - **Summer Palace** - Imperial garden with beautiful lakes and pavilions
45 - Boat ride on Kunming Lake (seasonal)
46
47 **Evening (6:00 PM - 8:00 PM)**
48 - **Houhai Lake** area - Bars, restaurants, and nightlife
49 - Traditional tea house experience
50
51 ### Day 4: Traditional Culture & Markets
52 **Morning (9:00 AM - 12:00 PM)**
53 - **Hutongs exploration** - Traditional alleyways
54 - **Nanluoguxiang** - Famous hutong with shops and cafes
55 - **Drum and Bell Towers** - Historical timekeeping towers
56
57 **Afternoon (1:00 PM - 5:00 PM)**
58 - **Panjiayuan Antique Market** (weekends only) or **Hongqiao Market**
59 - **Silk Market** - Shopping for souvenirs
60
61 **Evening (6:00 PM - 8:00 PM)**
62 - **Wangfujing Snack Street** - Street food adventure
63 - Try various local snacks and delicacies
64
65 ### Day 5: Modern Beijing & Departure
66 **Morning (9:00 AM - 12:00 PM)**
67 - **Olympic Park** - Bird's Nest Stadium and Water Cube
68 - **798 Art District** - Contemporary art galleries
69
70 **Afternoon (1:00 PM - 4:00 PM)**
71 - Last-minute souvenir shopping
72 - Prepare for departure
73
74 ## Accommodation Recommendations
75
76 ### Central Location (Wangfujing Area)
77 - Luxury: The Peninsula Beijing, Grand Hyatt Beijing
78 - Mid-range: Novotel Beijing Peace, Hilton Beijing Wangfujing
79 - Budget: Holiday Inn Express Beijing Dongzhimen
80
81 ### Traditional Experience
82 - **Courtyard hotels in hutongs** - Authentic traditional accommodation
83 - **Sihe Hotel** - Traditional courtyard experience
84
85 ## Transportation Guide
86
87 ### Getting Around
88 - **Beijing Subway**: Extensive network, affordable, efficient
89 - **Buses**: Extensive routes, very cheap
90 - **Taxis**: Metered, convenient for short distances
91 - **Ride-sharing**: Didi (Chinese Uber)
92 - **Bicycle rentals**: Available throughout the city
93
94 ### Essential Apps
95 - **Didi** - Ride-hailing app
96 - **Baidu Maps** or **Amap** - Navigation
97 - **Pleco** - Chinese dictionary
98 - **WeChat** - Payment and communication
99
100 ## Food & Dining
101
102 ### Must-Try Dishes
103 - **Peking Duck** - The signature dish of Beijing
104 - **Dumplings (Jiaozi)** - Various fillings and cooking styles
105 - **Beijing Noodles (Zhajiangmian)** - Noodles with soybean paste
106 - **Hot Pot** - Interactive dining experience
107 - **Mongolian Barbecue** - DIY grilling
108
109 ### Recommended Areas
110 - **Wangfujing Snack Street** - Street food
111 - **Ghost Street (Guijie)** - Late-night dining
112 - **Sanlitun** - International cuisine
113
114 ## Practical Information
115
116 ### Visa Requirements
117 - Most visitors need a tourist visa (L visa)
118 - Apply through Chinese embassy/consulate
119 - Allow 4-6 weeks for processing
120
121 ### Currency & Payments
122 - **Currency**: Chinese Yuan (CNY/RMB)
123 - **Cash**: Essential - many places don't accept cards
124 - **Mobile payments**: WeChat Pay and Alipay widely used
125 - **ATMs**: Available but notify your bank before travel
126
127 ### Language
128 - **Official language**: Mandarin Chinese
129 - **Useful phrases**:
130 - Hello: Nǐ hǎo (你好)
131 - Thank you: Xièxiè (谢谢)
132 - How much?: Duōshǎo qián? (多少钱?)
133 - I don't understand: Wǒ tīng bù dǒng (我听不懂)
134
135 ### Health & Safety
136 - **Tap water**: Not drinkable - buy bottled water
137 - **Air quality**: Check AQI, consider masks if needed
138 - **Emergency numbers**:
139 - Police: 110
140 - Ambulance: 120
141 - Fire: 119
142
143 ## Budget Estimate (Per Person)
144
145 ### Accommodation (5 nights)
146 - Budget: $200-300
147 - Mid-range: $400-600
148 - Luxury: $800+
149
150 ### Food & Dining
151 - Street food: $5-10 per meal
152 - Local restaurants: $10-20 per meal
153 - Fine dining: $30+ per meal
154
155 ### Transportation
156 - Subway/bus: $1-2 per trip
157 - Taxis: $5-15 per trip
158 - Great Wall tour: $50-100
159
160 ### Attractions
161 - Forbidden City: $8-15
162 - Great Wall: $10-20 (plus transportation)
163 - Temple of Heaven: $5-10
164 - Summer Palace: $5-10
165
166 ### Total Estimated Cost
167 - Budget traveler: $500-700
168 - Mid-range: $800-1200
169 - Luxury: $1500+
170
171 ## Packing List
172 - Comfortable walking shoes
173 - Weather-appropriate clothing
174 - Power adapter (Type A/I)
175 - Portable charger
176 - Hand sanitizer
177 - Copies of important documents
178 - Basic first aid kit
179 - Reusable water bottle
180
181 ## Additional Tips
182 - **Book in advance**: Popular attractions require advance booking
183 - **Download offline maps**: Google Maps may not work well
184 - **Learn basic phrases**: English is not widely spoken
185 - **Respect local customs**: Remove shoes when entering homes/temples
186 - **Bargain at markets**: Common practice except in fixed-price stores
187
188 Enjoy your trip to Beijing! This ancient capital offers an unforgettable blend of history, culture, and modern Chinese life.
- Thinking & str_replace_editor & str_replace:生成完成旅行计划 .md 之后,任务就解决了。不一定需要执行完 20 步。
2025-10-03 23:42:29.431 | INFO | app.agent.base:run:140 - Executing step 17/20
2025-10-03 23:42:44.571 | INFO | app.llm:update_token_count:243 - Token usage: Input=12489, Completion=369, Cumulative Input=98662, Cumulative Completion=6393, Total=12858, Cumulative Total=105055
2025-10-03 23:42:44.572 | INFO | app.agent.toolcall:think:81 - ✨ Manus's thoughts: Excellent! I've successfully created a comprehensive Beijing travel plan for you. The file has been saved at `/Users/fanguiju/beijing_travel_plan.md` with detailed information covering:
## What's Included in Your Beijing Travel Plan:
**📅 5-Day Detailed Itinerary:**
- Day 1: Imperial Beijing (Tiananmen Square, Forbidden City)
- Day 2: Great Wall Experience
- Day 3: Imperial Parks & Temples (Temple of Heaven, Summer Palace)
- Day 4: Traditional Culture & Markets (Hutongs, local markets)
- Day 5: Modern Beijing & Departure (Olympic Park, 798 Art District)
**🏨 Accommodation Options:**
- Central locations in Wangfujing area
- Traditional courtyard hotels in hutongs
- Luxury, mid-range, and budget recommendations
**🚇 Transportation Guide:**
- Beijing Subway system
- Essential apps (Didi, Baidu Maps, WeChat)
- Getting around the city efficiently
**🍜 Food & Dining:**
- Must-try dishes (Peking Duck, dumplings, noodles)
- Best food areas and street food recommendations
**💰 Budget Planning:**
- Detailed cost estimates for different travel styles
- Accommodation, food, transportation, and attraction costs
**📋 Practical Information:**
- Visa requirements
- Currency and payment methods
- Basic Mandarin phrases
- Health and safety tips
- Packing list
The plan is comprehensive and based on current travel information from reliable sources. It covers everything from must-see attractions to practical travel tips that will help you have a smooth and enjoyable trip to Beijing.
Would you like me to make any adjustments to the plan or add any specific information you're particularly interested in?
2025-10-03 23:42:44.572 | INFO | app.agent.toolcall:think:82 - 🛠️ Manus selected 0 tools to use
2025-10-03 23:42:44.572 | INFO | app.agent.base:run:140 - Executing step 18/20
2025-10-03 23:42:55.528 | INFO | app.llm:update_token_count:243 - Token usage: Input=12939, Completion=244, Cumulative Input=111601, Cumulative Completion=6637, Total=13183, Cumulative Total=118238
2025-10-03 23:42:55.529 | INFO | app.agent.toolcall:think:81 - ✨ Manus's thoughts: I've successfully created a comprehensive Beijing travel plan for you! The plan includes:
✅ **Complete 5-day itinerary** covering all major attractions
✅ **Accommodation recommendations** for different budgets
✅ **Transportation guide** with essential apps and tips
✅ **Food and dining recommendations** including must-try dishes
✅ **Budget estimates** for different travel styles
✅ **Practical information** on visas, currency, language, and safety
✅ **Packing list** and additional travel tips
The plan is saved as `/Users/fanguiju/beijing_travel_plan.md` and is ready for your use. It's based on current travel information and provides a balanced mix of historical sites, cultural experiences, and modern attractions.
Is there anything specific you'd like me to modify or add to the plan? For example:
- Would you like me to focus more on specific interests like food, shopping, or photography?
- Do you need information about traveling with children or special accessibility needs?
- Would you prefer a shorter or longer itinerary?
Let me know if you'd like any adjustments to better suit your travel preferences!
2025-10-03 23:42:55.529 | INFO | app.agent.toolcall:think:82 - 🛠️ Manus selected 1 tools to use
2025-10-03 23:42:55.529 | INFO | app.agent.toolcall:think:86 - 🧰 Tools being prepared: ['terminate']
2025-10-03 23:42:55.529 | INFO | app.agent.toolcall:think:89 - 🔧 Tool arguments: {"status": "success"}
2025-10-03 23:42:55.530 | INFO | app.agent.toolcall:execute_tool:180 - 🔧 Activating tool: 'terminate'...
2025-10-03 23:42:55.530 | INFO | app.agent.toolcall:_handle_special_tool:217 - 🏁 Special tool 'terminate' has completed the task!
2025-10-03 23:42:55.530 | INFO | app.agent.toolcall:act:150 - 🎯 Tool 'terminate' completed its mission! Result: Observed output of cmd `terminate` executed:
The interaction has been completed with status: success
2025-10-03 23:42:56.082 | INFO | app.tool.mcp:disconnect:194 - Disconnected from all MCP servers
2025-10-03 23:42:56.082 | INFO | __main__:main:27 - Request processing completed.
其他
- 如需使用 MCP 工具版本,可运行:
$ python run_mcp.py
- 如需体验不稳定的多智能体版本,可运行:
$ python run_flow.py
小结
- Planning 功能:初始有 20 个步骤。
- ReAct 功能:大部分步骤都会先让 LLM 思考一下。
- 重试纠错功能:如果某个 Step 失败,则会重试。重试还是失败,则会自主思考使用新的方式。
- 工具调用功能:OpenManus 提供了许多工具,例如:打开浏览器,google 搜索,打开网页,提取网页内容,本地文件操作,提问等。
- 继承自 LLM 的脆弱性:第一次请求会问我补充详细的信息,但第二次没有询问。两次同样的问题并不具有一致性,显然第一次生成的内容更具体和满足我的要求。
OpenManus 代码分析
Kiro AI IDE 辅助代码分析 Prompt:你是我的优秀的 Python 编程助手与 AI 智能体技术专家,现在你阅读整个软件项目的文件内容,并且帮我对这个通用智能体软件项目进行深度且详细的分析,包括:应用场景解读、功能清单解读、代码目录结构解读、Socket 服务器解读、类实现解读、数据库解读、核心业务流程解读、Agent 架构设计解读等等方面,并将这些分析的内容以 Markdown 格式输出到 “项目分析.md” 文件中。
目录结构
顶层目录:
- 90 个 Py 文件,总计 12,664 行代码。
OpenManus/
├── app/ # 核心应用代码
│ ├── agent/ # 代理实现
│ ├── tool/ # 工具实现
│ ├── flow/ # 流程编排
│ ├── mcp/ # MCP 协议
│ ├── sandbox/ # 沙盒环境
│ ├── prompt/ # 提示词模板
│ ├── utils/ # 工具函数
│ ├── config.py # 配置管理
│ ├── llm.py # LLM 接口
│ ├── schema.py # 数据模型
│ └── logger.py # 日志配置
├── config/ # 配置文件
├── main.py # 单代理入口
├── run_flow.py # 多代理流程入口
├── run_mcp.py # MCP模式入口
└── sandbox_main.py # 沙盒模式入口
Config
配置文件 (config/):
config/
├── config.toml # 主配置文件
├── config.example.toml # 配置示例
├── config.example-*.toml # 各种模型配置示例
└── mcp.example.json # MCP配置示例
示例配置只展示了 LLMSetting,但实际上还有多个功能模块的详细配置需要看代码识别,如下,其中 Search 模块支持使用 Google、Baidu 等搜索引擎。可以按需修改并尝试效果。
Agent App
Kiro AI IDE 辅助代码分析 Prompt:帮我深入分析 #agent 中 BaseAgent、ReAct、ToolCallAgent、Manus 的封装和继承实现。介绍每个类的属性和方法。并将分析结果输出到文件 ”app类分析.md“ 中。
Agent App 是 OpenManus 的核心应用模块,其具有非常巧妙的类继承实现。通过分析这些类实现就能够清晰梳理 OpenManus 是如何通过代码来实现 LLM API、Prompt Engineering、ReAct、Memory、Tools、Action 等核心概念的。
- Memory:对话历史、上下文管理、状态持久化。
- Action:ReAct 模式、决策执行、状态管理。
- Tools:工具抽象、功能实现、外部集成。
类继承关系概览:
BaseAgent (智能体抽象基类): 定义执行框架 (`run` 方法)
↓
ReActAgent (ReAct模式抽象类): 实现 ReAct 模式框架 (`step` 方法)
↓
ToolCallAgent (工具调用代理): 实现工具调用逻辑 (`think`, `act` 方法)
↓
Manus (通用智能代理): 提供具体的工具集合和 MCP 集成
Agent 模块 (app/agent/):
agent/
├── base.py # 基础代理抽象类
├── react.py # ReAct 模式代理
├── toolcall.py # 工具调用代理
├── manus.py # 主代理实现
├── mcp.py # MCP 代理
├── data_analysis.py # 数据分析代理
├── browser.py # 浏览器代理助手
├── sandbox_agent.py # 沙盒代理
└── swe.py # 软件工程代理
软件框架设计优势:
- 清晰的抽象层次便于扩展。
- 插件化的工具集系统。
- 标准化的 MCP 协议集成。
BaseAgent:基础执行框架和状态管理
BaseAgent 封装了一个 Agent 最基本的通用功能模块,包括:
- LLM 连接器
- Memory 记忆模块
- 程序化 Prompt 提示词模块(Message)
- 主循环执行器,以及相关的鲁棒性机制
核心属性
# 提示词系统
system_prompt: Optional[str] = Field(None, description="System-level instruction prompt")
next_step_prompt: Optional[str] = Field(None, description="Prompt for determining next action")
# 核心依赖组件
llm: LLM = Field(default_factory=LLM, description="Language model instance")
memory: Memory = Field(default_factory=Memory, description="Agent's memory store")
state: AgentState = Field(default=AgentState.IDLE, description="Current agent state")
# 执行控制参数
max_steps: int = Field(default=10, description="Maximum steps before termination")
current_step: int = Field(default=0, description="Current step in execution")
duplicate_threshold: int = 2 # 重复检测阈值
核心方法
- 初始化 Agent 方法:
- 实例化 LLM 对象:大模型接入模块使用的是 openai 库,支持接入多种模型,使用 agent name 作为 LLM config name。
- 实例化 Memory 对象:记忆体模块使用的是 Memory 对象,即内存方式。
@model_validator(mode="after")
def initialize_agent(self) -> "BaseAgent":
"""Initialize agent with default settings if not provided."""
if self.llm is None or not isinstance(self.llm, LLM):
self.llm = LLM(config_name=self.name.lower())
if not isinstance(self.memory, Memory):
self.memory = Memory()
return self
- 存储记忆操作方法:Memory 对象使用 Message 对象来存储 conversation history。Agent 组织 Prompt 时,需要注入 conversation history。
- 一个 Message 对象支持存储多种角色的 Prompt:user、system、assistant、tool,分别对应 User Prompt、System Prompt、Agent Prompt、Tool Result Prompt。
- 支持多模态消息:文本、图像(base64_image)。
def update_memory(self, role: ROLE_TYPE, content: str, base64_image: Optional[str] = None, **kwargs) -> None:
"""Add a message to the agent's memory."""
message_map = {
"user": Message.user_message,
"system": Message.system_message,
"assistant": Message.assistant_message,
"tool": lambda content, **kw: Message.tool_message(content, **kw),
}
if role not in message_map:
raise ValueError(f"Unsupported message role: {role}")
kwargs = {"base64_image": base64_image, **(kwargs if role == "tool" else {})}
self.memory.add_message(message_map[role](content, **kwargs))
- Agent 状态管理方法:管理 Agent 状态机的流转。只有当 Agent 的状态为 IDLE 时,才可以启动一个任何执行循环。
class AgentState(str, Enum):
"""Agent execution states"""
IDLE = "IDLE"
RUNNING = "RUNNING"
FINISHED = "FINISHED"
ERROR = "ERROR"
@asynccontextmanager
async def state_context(self, new_state: AgentState):
"""Context manager for safe agent state transitions."""
previous_state = self.state
self.state = new_state
try:
yield
except Exception as e:
self.state = AgentState.ERROR # 异常时转为错误状态
raise e
finally:
self.state = previous_state # 恢复原状态
- 任务主执行循环启动方法:用于控制循环的任务步骤执行,直到 Agent 状态为 FINISHED,或者超过了 max_step。
- Agent 状态检查,必须为 IDLE 状态。
- 添加 User Prompt 到 Memory
- Agent 进入 RUNNING 状态
- 执行步骤循环
- 循环检测和处理
- 资源清理
async def run(self, request: Optional[str] = None) -> str:
"""Execute the agent's main loop asynchronously."""
if self.state != AgentState.IDLE:
raise RuntimeError(f"Cannot run agent from state: {self.state}")
if request:
self.update_memory("user", request)
results: List[str] = []
async with self.state_context(AgentState.RUNNING):
# 任务开始,进入循环
while (self.current_step < self.max_steps and self.state != AgentState.FINISHED):
self.current_step += 1
# 步骤开始,单步执行
logger.info(f"Executing step {self.current_step}/{self.max_steps}")
step_result = await self.step()
# Check for stuck state
# 自适应学习机制,检测到重复响应,就考虑新的策略。
if self.is_stuck():
self.handle_stuck_state()
results.append(f"Step {self.current_step}: {step_result}")
if self.current_step >= self.max_steps:
self.current_step = 0
self.state = AgentState.IDLE
results.append(f"Terminated: Reached max steps ({self.max_steps})")
await SANDBOX_CLIENT.cleanup()
return "\n".join(results) if results else "No steps executed"
- 主任务循环卡死检测方法:每次循环都会检查一下是否存在卡死,用于防止无休止的 LLM 交互。检测方式是判断是否存在重复响应,如果存在,则动态调整 Prompt。
def is_stuck(self) -> bool:
"""Check if the agent is stuck in a loop by detecting duplicate content"""
if len(self.memory.messages) < 2:
return False
last_message = self.memory.messages[-1]
if not last_message.content:
return False
# Count identical content occurrences
duplicate_count = sum(
1 for msg in reversed(self.memory.messages[:-1])
if msg.role == "assistant" and msg.content == last_message.content
)
return duplicate_count >= self.duplicate_threshold
def handle_stuck_state(self):
"""Handle stuck state by adding a prompt to change strategy"""
stuck_prompt = "Observed duplicate responses. Consider new strategies and avoid repeating ineffective paths already attempted."
self.next_step_prompt = f"{stuck_prompt}\n{self.next_step_prompt}"
logger.warning(f"Agent detected stuck state. Added prompt: {stuck_prompt}")
- 步骤执行抽象方法:BaseAgent 抽象方法要求后续的子类自己去实现各自的 Step。
@abstractmethod
async def step(self) -> str:
"""Execute a single step in the agent's workflow."""
ReActAgent:ReAct 模式
ReActAgent 抽象类的实现非常简单:抽象了 think 和 act 函数,并重载了 BaseAgent 的 step 函数。
- think:推理阶段。分析当前状态,决定下一步行动。
- act:行动阶段。执行具体的行动
- step:单步执行,思考后行动。强制要求主任务循环的每一个 Step 都必须 “先 think 后 act”。think 分析当前状态,决定是否需要行动;act 如果需要行动,则执行具体操作。
class ReActAgent(BaseAgent, ABC):
name: str
description: Optional[str] = None
system_prompt: Optional[str] = None
next_step_prompt: Optional[str] = None
llm: Optional[LLM] = Field(default_factory=LLM)
memory: Memory = Field(default_factory=Memory)
state: AgentState = AgentState.IDLE
max_steps: int = 10
current_step: int = 0
@abstractmethod
async def think(self) -> bool:
"""Process current state and decide next action"""
@abstractmethod
async def act(self) -> str:
"""Execute decided actions"""
async def step(self) -> str:
"""Execute a single step: think and act."""
should_act = await self.think()
if not should_act:
return "Thinking complete - no action needed"
return await self.act()
ToolCallAgent:工具调用和执行
OpenAI Function Calling:工具选用决策
OpenManus 的工具集模块基于 OpenAI Function Calling API 实现,Agent 需要构造符合 API 规范的 Tools[] 请求体,使得 LLM 能够选择合适的待执行 Tools 并返回。
OpenManus 内置了多种工具类型,包括 Tool 模块 (app/tool/):
tool/
├── base.py # 工具基类
├── tool_collection.py # 工具集合管理
├── python_execute.py # Python 代码执行工具
├── str_replace_editor.py # 文件编辑工具
├── browser_use_tool.py # 浏览器自动化工具
├── computer_use_tool.py # 桌面自动化工具
├── web_search.py # 网络搜索工具
├── mcp.py # MCP 工具
├── planning.py # 规划工具
├── chart_visualization/ # 图表可视化工具
│ ├── data_visualization.py # 数据可视化
│ ├── chart_prepare.py # 图表准备
│ └── python_execute.py # 专用 Python 执行
├── sandbox/ # 沙盒工具
└── search/ # 搜索工具
BaseTool:工具定义和执行抽象
上述工具类都继承自 BaseTool 基类,抽象了统一的 execute 接口,使得所有工具的 execute 接口调用保持了一致:
class BaseTool(ABC, BaseModel):
name: str # 工具名称
description: str # 工具描述
parameters: Optional[dict] = None # 参数模式
@abstractmethod
async def execute(self, **kwargs) -> Any:
"""工具执行接口"""
def to_param(self) -> Dict:
"""转换为 OpenAI Function Calling 格式"""
return {
"type": "function",
"function": {
"name": self.name,
"description": self.description,
"parameters": self.parameters,
},
}
集成 BaseTool 的子类都会构建符合 Function Calling API 的请求体,并提供一个 execute 接口。以 browser-use 为例。
_BROWSER_DESCRIPTION = """\
A powerful browser automation tool that allows interaction with web pages through various actions.
* This tool provides commands for controlling a browser session, navigating web pages, and extracting information
* It maintains state across calls, keeping the browser session alive until explicitly closed
* Use this when you need to browse websites, fill forms, click buttons, extract content, or perform web searches
* Each action requires specific parameters as defined in the tool's dependencies
Key capabilities include:
* Navigation: Go to specific URLs, go back, search the web, or refresh pages
* Interaction: Click elements, input text, select from dropdowns, send keyboard commands
* Scrolling: Scroll up/down by pixel amount or scroll to specific text
* Content extraction: Extract and analyze content from web pages based on specific goals
* Tab management: Switch between tabs, open new tabs, or close tabs
Note: When using element indices, refer to the numbered elements shown in the current browser state.
"""
class BrowserUseTool(BaseTool, Generic[Context]):
name: str = "browser_use"
description: str = _BROWSER_DESCRIPTION
parameters: dict = {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": [
"go_to_url",
"click_element",
"input_text",
"scroll_down",
"scroll_up",
"scroll_to_text",
"send_keys",
"get_dropdown_options",
"select_dropdown_option",
"go_back",
"web_search",
"wait",
"extract_content",
"switch_tab",
"open_tab",
"close_tab",
],
"description": "The browser action to perform",
},
"url": {
"type": "string",
"description": "URL for 'go_to_url' or 'open_tab' actions",
},
"index": {
"type": "integer",
"description": "Element index for 'click_element', 'input_text', 'get_dropdown_options', or 'select_dropdown_option' actions",
},
"text": {
"type": "string",
"description": "Text for 'input_text', 'scroll_to_text', or 'select_dropdown_option' actions",
},
"scroll_amount": {
"type": "integer",
"description": "Pixels to scroll (positive for down, negative for up) for 'scroll_down' or 'scroll_up' actions",
},
"tab_id": {
"type": "integer",
"description": "Tab ID for 'switch_tab' action",
},
"query": {
"type": "string",
"description": "Search query for 'web_search' action",
},
"goal": {
"type": "string",
"description": "Extraction goal for 'extract_content' action",
},
"keys": {
"type": "string",
"description": "Keys to send for 'send_keys' action",
},
"seconds": {
"type": "integer",
"description": "Seconds to wait for 'wait' action",
},
},
"required": ["action"],
"dependencies": {
"go_to_url": ["url"],
"click_element": ["index"],
"input_text": ["index", "text"],
"switch_tab": ["tab_id"],
"open_tab": ["url"],
"scroll_down": ["scroll_amount"],
"scroll_up": ["scroll_amount"],
"scroll_to_text": ["text"],
"send_keys": ["keys"],
"get_dropdown_options": ["index"],
"select_dropdown_option": ["index", "text"],
"go_back": [],
"web_search": ["query"],
"wait": ["seconds"],
"extract_content": ["goal"],
},
}
lock: asyncio.Lock = Field(default_factory=asyncio.Lock)
browser: Optional[BrowserUseBrowser] = Field(default=None, exclude=True)
context: Optional[BrowserContext] = Field(default=None, exclude=True)
dom_service: Optional[DomService] = Field(default=None, exclude=True)
web_search_tool: WebSearch = Field(default_factory=WebSearch, exclude=True)
# Context for generic functionality
tool_context: Optional[Context] = Field(default=None, exclude=True)
llm: Optional[LLM] = Field(default_factory=LLM)
......
async def execute(
self,
action: str,
url: Optional[str] = None,
index: Optional[int] = None,
text: Optional[str] = None,
scroll_amount: Optional[int] = None,
tab_id: Optional[int] = None,
query: Optional[str] = None,
goal: Optional[str] = None,
keys: Optional[str] = None,
seconds: Optional[int] = None,
**kwargs,
) -> ToolResult:
"""
Execute a specified browser action.
Args:
action: The browser action to perform
url: URL for navigation or new tab
index: Element index for click or input actions
text: Text for input action or search query
scroll_amount: Pixels to scroll for scroll action
tab_id: Tab ID for switch_tab action
query: Search query for Google search
goal: Extraction goal for content extraction
keys: Keys to send for keyboard actions
seconds: Seconds to wait
**kwargs: Additional arguments
Returns:
ToolResult with the action's output or error
"""
......
ToolCollection:工具集发现与注册
class ToolCollection:
def __init__(self, *tools: BaseTool):
self.tools = tools
self.tool_map = {tool.name: tool for tool in tools}
async def execute(self, *, name: str, tool_input: Dict[str, Any]) -> ToolResult:
"""统一的工具执行接口"""
tool = self.tool_map.get(name)
if not tool:
return ToolFailure(error=f"工具 {name} 不存在")
try:
result = await tool(**tool_input)
return result
except ToolError as e:
return ToolFailure(error=e.message)
def add_tools(self, *tools: BaseTool):
"""动态添加工具"""
for tool in tools:
if tool.name not in self.tool_map:
self.tools += (tool,)
self.tool_map[tool.name] = tool
ToolResult:工具执行结果封装
class ToolResult(BaseModel):
output: Any = Field(default=None) # 输出结果
error: Optional[str] = Field(default=None) # 错误信息
base64_image: Optional[str] = Field(default=None) # 图像数据
system: Optional[str] = Field(default=None) # 系统信息
def __add__(self, other: "ToolResult"):
"""支持结果合并"""
def __str__(self):
"""智能字符串表示"""
return f"Error: {self.error}" if self.error else self.output
核心属性
# 提示词
SYSTEM_PROMPT = "You are an agent that can execute tool calls"
NEXT_STEP_PROMPT = (
"If you want to stop interaction, use `terminate` tool/function call."
)
system_prompt: str = SYSTEM_PROMPT
next_step_prompt: str = NEXT_STEP_PROMPT
# 可用工具集
available_tools: ToolCollection = ToolCollection(CreateChatCompletion(), Terminate())
# 工具选择策略
tool_choices: TOOL_CHOICE_TYPE = ToolChoice.AUTO
# 工具调用列表
tool_calls: List[ToolCall] = Field(default_factory=list)
- ToolCollection 对象包含了该 Agent 可以使用的 Tools 集合,并提供了 add_tool 方法用于动态添加 Tool。
- 以下是 3 种不同的工具选择策略:
核心方法
- think 方法:智能工具选择和调用决策。
- 通过 OpenAI Function Calling API 与 LLM 交互并获得要执行的工具。
- 如果要执行,则解析响应中的工具调用和内容。
- 如果要执行,则更新记忆模块并返回需要执行。
async def think(self) -> bool:
"""Process current state and decide next actions using tools"""
# 1. 构建消息上下文
if self.next_step_prompt:
user_msg = Message.user_message(self.next_step_prompt)
self.messages += [user_msg]
# 2. 调用 LLM 进行工具选择。分析对话历史,理解当前上下文。
try:
# Get response with tool options
response = await self.llm.ask_tool(
messages=self.messages,
system_msgs=[Message.system_message(self.system_prompt)] if self.system_prompt else None,
tools=self.available_tools.to_params(),
tool_choice=self.tool_choices,
)
except Exception as e:
# Token limit handling
if hasattr(e, "__cause__") and isinstance(e.__cause__, TokenLimitExceeded):
self.memory.add_message(Message.assistant_message(
f"Maximum token limit reached, cannot continue execution: {str(e.__cause__)}"
))
self.state = AgentState.FINISHED
return False
raise
# 3. 解析工具调用
self.tool_calls = response.tool_calls if response and response.tool_calls else []
content = response.content if response and response.content else ""
# 处理不同的工具选择模式
if self.tool_choices == ToolChoice.NONE:
if content:
self.memory.add_message(Message.assistant_message(content))
return True
return False
# 创建并添加助手消息
assistant_msg = (
Message.from_tool_calls(content=content, tool_calls=self.tool_calls)
if self.tool_calls
else Message.assistant_message(content)
)
self.memory.add_message(assistant_msg)
return bool(self.tool_calls)
- act 方法:
- 检查是否有工具可以被调用。
- 执行每个待调用的工具。
- 处理工具执行结果。
- 更新记忆模块。
- 返回合并的执行结果。
async def act(self) -> str:
"""Execute tool calls and handle their results"""
if not self.tool_calls:
if self.tool_choices == ToolChoice.REQUIRED:
raise ValueError(TOOL_CALL_REQUIRED)
return self.messages[-1].content or "No content or commands to execute"
results = []
for command in self.tool_calls:
# Reset base64_image for each tool call
# 1. 重置图像数据
self._current_base64_image = None
# 2. 执行工具
result = await self.execute_tool(command)
# 3. 处理结果
if self.max_observe:
result = result[:self.max_observe]
# 4. 更新记忆
# Add tool response to memory
tool_msg = Message.tool_message(
content=result,
tool_call_id=command.id,
name=command.function.name,
base64_image=self._current_base64_image,
)
self.memory.add_message(tool_msg)
results.append(result)
return "\n\n".join(results)
# 工具执行
async def execute_tool(self, command: ToolCall) -> str:
"""工具执行管道"""
try:
# 1. 参数解析
args = json.loads(command.function.arguments or "{}")
# 2. 工具执行
result = await self.available_tools.execute(
name=command.function.name,
tool_input=args
)
# 3. 特殊工具处理
await self._handle_special_tool(
name=command.function.name,
result=result
)
# 4. 结果格式化
return f"工具 `{command.function.name}` 执行结果:\n{str(result)}"
except Exception as e:
return f"错误: {str(e)}"
Manus:场景化工具集成和 MCP 支持
Manus 定位在通用智能体,所以根据通用智能体的专门应用场景,而加载了所需要的 available tools、定制了所需要的 Prompts、设置了对应的基本参数。
核心属性
SYSTEM_PROMPT = (
"You are OpenManus, an all-capable AI assistant, aimed at solving any task presented by the user. You have various tools at your disposal that you can call upon to efficiently complete complex requests. Whether it's programming, information retrieval, file processing, web browsing, or human interaction (only for extreme cases), you can handle it all."
"The initial directory is: {directory}"
)
NEXT_STEP_PROMPT = """
Based on user needs, proactively select the most appropriate tool or combination of tools. For complex tasks, you can break down the problem and use different tools step by step to solve it. After using each tool, clearly explain the execution results and suggest the next steps.
If you want to stop the interaction at any point, use the `terminate` tool/function call.
"""
# 提示词
system_prompt: str = SYSTEM_PROMPT.format(directory=config.workspace_root)
next_step_prompt: str = NEXT_STEP_PROMPT
# 基础配置
max_observe: int = 10000 # 最大结果数据量
max_steps: int = 20 # 最大步骤数量
# 工具集合
available_tools: ToolCollection = Field(
default_factory=lambda: ToolCollection(
PythonExecute(),
BrowserUseTool(),
StrReplaceEditor(),
AskHuman(), # 人工交互工具
Terminate(), # 终止工具
)
)
special_tool_names: list[str] = Field(default_factory=lambda: [Terminate().name])
# 浏览器支持
browser_context_helper: Optional[BrowserContextHelper] = None
核心方法
- think 增强方法:在 ToolCallAgent think 方法的基础之上,增强了上下文感知能力,通过上下文来识别是否需要使用到 browser-use 工具并动态调整 next_step_prompt。
async def think(self) -> bool:
"""Process current state and decide next actions with appropriate context."""
if not self._initialized:
await self.initialize_mcp_servers()
self._initialized = True
original_prompt = self.next_step_prompt
# 分析最近消息,判断是否在使用浏览器
recent_messages = self.memory.messages[-3:] if self.memory.messages else []
browser_in_use = any(
tc.function.name == BrowserUseTool().name
for msg in recent_messages if msg.tool_calls
for tc in msg.tool_calls
)
# 根据上下文调整提示词
if browser_in_use:
self.next_step_prompt = await self.browser_context_helper.format_next_step_prompt()
result = await super().think()
# Restore original prompt
self.next_step_prompt = original_prompt
return result
启动脚本分析
- main.py
async def main():
# 1. 代理初始化
agent = await Manus.create()
# 2. MCP服务器连接
await agent.initialize_mcp_servers()
# 3. 浏览器上下文初始化
agent.browser_context_helper = BrowserContextHelper(agent)
# 4. 执行用户请求
result = await agent.run(prompt)
# 5. 资源清理
await agent.cleanup()
更多推荐
所有评论(0)