-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
211 lines (177 loc) · 5.6 KB
/
Copy pathcli.py
File metadata and controls
211 lines (177 loc) · 5.6 KB
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
"""
CLI Interface for Browser Agent
Provides command-line interface with argument parsing and task generation.
"""
import sys
import asyncio
import argparse
from typing import Optional
from browser_agent import (
run_browser_agent,
GOOGLE_API_KEY,
MODEL,
MAX_STEPS,
OUTPUT_DIR,
HEADLESS
)
from task_generator import generate_task
def create_parser() -> argparse.ArgumentParser:
"""Create and configure argument parser."""
parser = argparse.ArgumentParser(
prog="browser-agent",
description="AI-powered browser automation with natural language commands",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
browser-agent "Go to example.com and save as example.pdf"
browser-agent "find python docs" --generate
browser-agent "search for AI" --generate --headless --max-steps 20
browser-agent "Go to github.com" --quiet --output-dir ./pdfs
For more information, visit: https://github.com/yourusername/browser-agent
"""
)
# Positional argument
parser.add_argument(
"task",
nargs="?",
help="Task description in natural language"
)
# Optional flags
parser.add_argument(
"--generate", "-g",
action="store_true",
help="Use LLM to refine task into structured steps"
)
parser.add_argument(
"--headless",
action="store_true",
help="Run browser invisibly (default: visible)"
)
parser.add_argument(
"--max-steps",
type=int,
metavar="N",
help=f"Maximum agent loop iterations (default: {MAX_STEPS})"
)
parser.add_argument(
"--output-dir",
type=str,
metavar="DIR",
help=f"Directory for saving PDFs (default: {OUTPUT_DIR})"
)
parser.add_argument(
"--model",
type=str,
metavar="NAME",
help=f"Gemini model name (default: {MODEL})"
)
# Verbosity control (mutually exclusive)
verbosity = parser.add_mutually_exclusive_group()
verbosity.add_argument(
"--verbose", "-v",
action="store_true",
help="Print step-by-step progress (default)"
)
verbosity.add_argument(
"--quiet", "-q",
action="store_true",
help="Suppress step-by-step output"
)
return parser
async def async_main(args: argparse.Namespace) -> int:
"""
Main async entry point for CLI.
Args:
args: Parsed command-line arguments
Returns:
int: Exit code (0 for success, 1 for failure)
"""
# 1. Validate API key exists
if not GOOGLE_API_KEY:
print("ERROR: GOOGLE_API_KEY not found in environment variables", file=sys.stderr)
print("Please set GOOGLE_API_KEY in your .env file or environment", file=sys.stderr)
return 1
# 2. Validate task provided
if not args.task:
print("ERROR: No task provided", file=sys.stderr)
print("\nUsage: browser-agent \"task description\"", file=sys.stderr)
print("Run 'browser-agent --help' for more information", file=sys.stderr)
return 1
# Determine verbosity (default is verbose unless --quiet)
verbose = not args.quiet
# 3. Optional task generation
task = args.task
if args.generate:
if verbose:
print("Generating structured task...")
try:
refined_task = await generate_task(
user_input=args.task,
api_key=GOOGLE_API_KEY,
model=args.model or MODEL,
verbose=verbose
)
# Only show refined task if it's different from original
if refined_task != args.task:
if verbose:
print("\nRefined task:")
print("-" * 60)
print(refined_task)
print("-" * 60)
print()
task = refined_task
else:
if verbose:
print("Using original task (generation did not refine it)\n")
except Exception as e:
if verbose:
print(f"Warning: Task generation failed ({e}), continuing with original task\n")
# Continue with original task
# 4. Run browser agent
try:
result = await run_browser_agent(
task=task,
output_dir=args.output_dir,
model=args.model,
max_steps=args.max_steps,
headless=args.headless or HEADLESS,
verbose=verbose
)
except KeyboardInterrupt:
if verbose:
print("\n\nInterrupted by user (Ctrl+C)")
return 1
except Exception as e:
print(f"ERROR: Unexpected error: {e}", file=sys.stderr)
return 1
# 5. Display results
if verbose:
print(f"\n{'='*60}")
if result['success']:
success_msg = f"✅ Completed in {result['steps']} steps"
if result.get('message'):
success_msg += f": {result['message']}"
print(success_msg)
if verbose:
print(f"{'='*60}")
return 0
else:
failure_msg = f"❌ Failed after {result['steps']} steps"
if result.get('message'):
failure_msg += f": {result['message']}"
print(failure_msg)
if verbose:
print(f"{'='*60}")
return 1
def main() -> None:
"""
Synchronous entry point for CLI.
Parses arguments and runs async_main with asyncio.
"""
parser = create_parser()
args = parser.parse_args()
# Run async main
exit_code = asyncio.run(async_main(args))
sys.exit(exit_code)
if __name__ == "__main__":
main()