本文將詳細闡述如何基於阿里雲無影AgentBay的Computer Use Linux鏡像,構建一個功能完備的All-in-One Sandbox環境。
背景介紹
All-in-One Sandbox是一個高度整合的雲端開發與執行環境,整合了Linux案頭自動化、瀏覽器以及代碼執行引擎,為自動化任務(尤其是 AI Agent)、雲端開發和安全的程式碼執行提供標準化、開箱即用的運行環境。
該方案通過統一容器化架構,消除傳統分散工具鏈中環境差異、檔案傳輸複雜性和組件間互動障礙,實現全流程一體化與無縫操作。
方案概述
本方案使用Linux沙箱會話作為一體化沙箱。使用linux_latest鏡像以完成:
session.computer用於案頭自動化。session.browser用於瀏覽器自動化。session.code用於代碼執行(例如,Python)。
當需要在單一會話中同時進行使用者介面互動與指令碼執行(或快速擷取網路內容)而無需切換鏡像時,該環境尤為適用。
核心亮點
環境一致性:將瀏覽器、終端、檔案系統、開發工具封裝在統一環境中,消除環境差異問題。
開箱即用:預裝常用語言、架構、構建工具,避免環境搭建時間消耗。
安全隔離:基於VPC網路隔離和獨立容器環境,確保任務執行安全性與資料可控性。
Auto Scaling:支援秒級環境建立與銷毀,按需資源配置,最佳化成本效益。
多模態整合:在單一Linux鏡像中整合Browser Use、CodeSpace、Computer Use能力,實現工具鏈無縫協同。
準備工作
在環境中完成API 金鑰設定。
實現樣本
以下樣本使用相同的linux_latest會話類型並示範:
通過
session.code.run_code()運行代碼。通過
session.browser使用瀏覽器代理API。
樣本1:在linux_latest內運行代碼(類似Codespace)
import os
from agentbay import AgentBay, CreateSessionParams
def main() -> None:
api_key = os.getenv("AGENTBAY_API_KEY")
if not api_key:
raise RuntimeError("AGENTBAY_API_KEY environment variable not set")
ab = AgentBay(api_key=api_key)
create_result = ab.create(CreateSessionParams(image_id="linux_latest"))
if not create_result.success:
raise RuntimeError(create_result.error_message)
session = create_result.session
try:
code = """
print("RUN_CODE_OK")
print(6 * 7)
""".strip()
result = session.code.run_code(code, "python")
if not result.success:
raise RuntimeError(result.error_message)
print(result.result)
finally:
session.delete()
if __name__ == "__main__":
main()
樣本2:在linux_latest內使用瀏覽器API
此樣本使用瀏覽器代理API(無需本地Playwright):導航到頁面並截取螢幕截圖。
import os
from agentbay import AgentBay, BrowserOption, CreateSessionParams
def main() -> None:
api_key = os.getenv("AGENTBAY_API_KEY")
if not api_key:
raise RuntimeError("AGENTBAY_API_KEY environment variable not set")
ab = AgentBay(api_key=api_key)
create_result = ab.create(CreateSessionParams(image_id="linux_latest"))
if not create_result.success:
raise RuntimeError(create_result.error_message)
session = create_result.session
try:
if not session.browser.initialize(BrowserOption()):
raise RuntimeError("Failed to initialize browser")
session.browser.agent.navigate("https://example.com")
data = session.browser.agent.screenshot(full_page=False)
print("Screenshot data prefix:", data[:30])
finally:
session.delete()
if __name__ == "__main__":
main()