Stagehand 도구
Stagehand 도구 (StagehandTool)
CrewAI의 StagehandTool은 Stagehand 프레임워크를 CrewAI와 통합해, 에이전트가 자연어 지침으로 웹사이트와 상호작용하고 브라우저 태스크를 자동화할 수 있게 해주는 도구예요. 클릭·폼 입력·데이터 추출 등을 자연어로 명령할 수 있습니다.
출처: 문서
본문
StagehandTool은 Browserbase가 만든 강력한 브라우저 자동화 프레임워크인 Stagehand를 CrewAI와 통합합니다. 이를 통해 AI 에이전트는:
- 웹사이트로 이동
- 버튼, 링크, 기타 요소 클릭
- 폼 채우기
- 웹 페이지에서 데이터 추출
- 요소 관찰 및 식별
- 복잡한 워크플로 수행
StagehandTool은 Stagehand Python SDK를 감싸 CrewAI 에이전트에게 세 가지 핵심 프리미티브를 통한 브라우저 제어 능력을 제공합니다.
- Act(액션): 클릭, 타이핑, 이동 같은 동작 수행
- Extract(추출): 웹 페이지에서 구조화된 데이터 추출
- Observe(관찰): 페이지의 요소 식별 및 분석
사전 요구사항 (Prerequisites)
이 도구를 사용하기 전에 다음이 있는지 확인하세요.
- API 키와 프로젝트 ID가 있는 Browserbase 계정
- LLM용 API 키 (OpenAI 또는 Anthropic Claude)
- Stagehand Python SDK 설치
필요한 의존성을 설치하세요.
pip install stagehand-py
사용법 (Usage)
기본 구현 (Basic Implementation)
StagehandTool은 두 가지 방식으로 구현할 수 있습니다.
1. 컨텍스트 매니저 사용 (권장)
예외가 발생해도 리소스가 제대로 정리되도록 컨텍스트 매니저 방식을 권장합니다.
from crewai import Agent, Task, Crew
from crewai_tools import StagehandTool
from stagehand.schemas import AvailableModel
# 컨텍스트 매니저로 API 키와 함께 도구 초기화
with StagehandTool(
api_key="your-browserbase-api-key",
project_id="your-browserbase-project-id",
model_api_key="your-llm-api-key", # OpenAI 또는 Anthropic API 키
model_name=AvailableModel.CLAUDE_3_7_SONNET_LATEST, # 선택: 사용할 모델 지정
) as stagehand_tool:
# 이 도구를 사용하는 에이전트 생성
researcher = Agent(
role="Web Researcher",
goal="Find and summarize information from websites",
backstory="I'm an expert at finding information online.",
verbose=True,
tools=[stagehand_tool],
)
# 이 도구를 사용하는 태스크 생성
research_task = Task(
description="Go to https://www.example.com and tell me what you see on the homepage.",
agent=researcher,
)
# 크루 실행
crew = Crew(
agents=[researcher],
tasks=[research_task],
verbose=True,
)
result = crew.kickoff()
print(result)
2. 수동 리소스 관리 (Manual Resource Management)
from crewai import Agent, Task, Crew
from crewai_tools import StagehandTool
from stagehand.schemas import AvailableModel
# API 키로 도구 초기화
stagehand_tool = StagehandTool(
api_key="your-browserbase-api-key",
project_id="your-browserbase-project-id",
model_api_key="your-llm-api-key",
model_name=AvailableModel.CLAUDE_3_7_SONNET_LATEST,
)
try:
# 이 도구를 사용하는 에이전트 생성
researcher = Agent(
role="Web Researcher",
goal="Find and summarize information from websites",
backstory="I'm an expert at finding information online.",
verbose=True,
tools=[stagehand_tool],
)
# 이 도구를 사용하는 태스크 생성
research_task = Task(
description="Go to https://www.example.com and tell me what you see on the homepage.",
agent=researcher,
)
# 크루 실행
crew = Crew(
agents=[researcher],
tasks=[research_task],
verbose=True,
)
result = crew.kickoff()
print(result)
finally:
# 리소스를 명시적으로 정리
stagehand_tool.close()
명령 유형 (Command Types)
StagehandTool은 특정 웹 자동화 태스크를 위한 세 가지 명령 유형을 지원합니다.
1. Act 명령 (Act Command)
act 명령 유형(기본값)은 버튼 클릭, 폼 채우기, 이동 같은 웹 페이지 상호작용을 가능하게 합니다.
# 동작 수행 (기본 동작)
result = stagehand_tool.run(
instruction="Click the login button",
url="https://example.com",
command_type="act" # 기본값이므로 생략 가능
)
# 폼 채우기
result = stagehand_tool.run(
instruction="Fill the contact form with name 'John Doe', email '[email protected]', and message 'Hello world'",
url="https://example.com/contact"
)
2. Extract 명령 (Extract Command)
extract 명령 유형은 웹 페이지에서 구조화된 데이터를 가져옵니다.
# 모든 상품 정보 추출
result = stagehand_tool.run(
instruction="Extract all product names, prices, and descriptions",
url="https://example.com/products",
command_type="extract"
)
# 선택자로 특정 정보 추출
result = stagehand_tool.run(
instruction="Extract the main article title and content",
url="https://example.com/blog/article",
command_type="extract",
selector=".article-container" # 선택적 CSS 선택자
)
3. Observe 명령 (Observe Command)
observe 명령 유형은 웹 페이지 요소를 식별하고 분석합니다.
# 상호작용 요소 찾기
result = stagehand_tool.run(
instruction="Find all interactive elements in the navigation menu",
url="https://example.com",
command_type="observe"
)
# 폼 필드 식별
result = stagehand_tool.run(
instruction="Identify all the input fields in the registration form",
url="https://example.com/register",
command_type="observe",
selector="#registration-form"
)
설정 옵션 (Configuration Options)
다음 파라미터로 StagehandTool 동작을 커스터마이즈할 수 있습니다.
stagehand_tool = StagehandTool(
api_key="your-browserbase-api-key",
project_id="your-browserbase-project-id",
model_api_key="your-llm-api-key",
model_name=AvailableModel.CLAUDE_3_7_SONNET_LATEST,
dom_settle_timeout_ms=5000, # DOM이 안정될 때까지 더 오래 대기
headless=True, # 헤드리스 모드로 브라우저 실행
self_heal=True, # 오류에서 복구 시도
wait_for_captcha_solves=True, # CAPTCHA 해결 대기
verbose=1, # 로깅 상세 정도 제어 (0-3)
)
모범 사례 (Best Practices)
- 구체적으로 작성: 더 나은 결과를 위해 상세한 지침을 제공하세요
- 적절한 명령 유형 선택: 태스크에 맞는 명령 유형을 고르세요
- 선택자 사용: CSS 선택자를 활용해 정확도를 높이세요
- 복잡한 태스크 분해: 복잡한 워크플로를 여러 도구 호출로 나누세요
- 에러 처리 구현: 잠재적 문제에 대한 에러 처리를 추가하세요
문제 해결 (Troubleshooting)
일반적인 문제와 해결책:
- 세션 문제: Browserbase와 LLM 제공자 양쪽의 API 키 확인
- 요소를 찾을 수 없음: 느린 페이지는
dom_settle_timeout_ms증가 - 액션 실패: 먼저
observe로 올바른 요소를 식별 - 불완전한 데이터: 지침을 다듬거나 구체적 선택자 제공
추가 리소스 (Additional Resources)
CrewAI 통합에 대한 질문:
- Stagehand의 Slack 커뮤니티 참여
- Stagehand 저장소에 이슈 등록
- Stagehand 문서 방문