ai-agent-book 精选快照(<2MB 代码与文档,来自 github.com/bojieli/ai-agent-book)
Build latest book artifacts / build (push) Canceled after 0s
dependency resolution / resolve (3.11) (push) Canceled after 0s
dependency resolution / resolve (3.13) (push) Canceled after 0s
deploy-pages / build (push) Canceled after 0s
deploy-pages / deploy (push) Canceled after 0s
i18n consistency check / check (push) Canceled after 0s
provider adoption tests / test (chapter2/context-compression) (push) Canceled after 0s
provider adoption tests / test (chapter2/prompt-injection) (push) Canceled after 0s
provider adoption tests / test (chapter2/system-hint) (push) Canceled after 0s
provider adoption tests / test (chapter3/log-sanitization) (push) Canceled after 0s
web-search-agent tests / test (push) Canceled after 0s
web-search-agent tests / agentbook (push) Canceled after 0s
Build latest book artifacts / build (push) Canceled after 0s
dependency resolution / resolve (3.11) (push) Canceled after 0s
dependency resolution / resolve (3.13) (push) Canceled after 0s
deploy-pages / build (push) Canceled after 0s
deploy-pages / deploy (push) Canceled after 0s
i18n consistency check / check (push) Canceled after 0s
provider adoption tests / test (chapter2/context-compression) (push) Canceled after 0s
provider adoption tests / test (chapter2/prompt-injection) (push) Canceled after 0s
provider adoption tests / test (chapter2/system-hint) (push) Canceled after 0s
provider adoption tests / test (chapter3/log-sanitization) (push) Canceled after 0s
web-search-agent tests / test (push) Canceled after 0s
web-search-agent tests / agentbook (push) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
---
|
||||
title: "All Parameters"
|
||||
description: "Complete reference for all agent configuration options"
|
||||
icon: "sliders"
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## Available Parameters
|
||||
|
||||
### Core Settings
|
||||
- `tools`: Registry of [our tools](https://github.com/browser-use/browser-use/blob/main/browser_use/tools/service.py) the agent can call. [Example for custom tools](https://github.com/browser-use/browser-use/tree/main/examples/custom-functions)
|
||||
- `browser`: Browser object where you can specify the browser settings.
|
||||
- `output_model_schema`: Pydantic model class for structured output validation. [Example](https://github.com/browser-use/browser-use/blob/main/examples/features/custom_output.py)
|
||||
|
||||
### Vision & Processing
|
||||
- `use_vision` (default: `True`): Enable/disable vision capabilities for processing screenshots
|
||||
- `vision_detail_level` (default: `'auto'`): Screenshot detail level - `'low'`, `'high'`, or `'auto'`
|
||||
- `page_extraction_llm`: Separate LLM model for page content extraction. You can choose a small & fast model because it only needs to extract text from the page (default: same as `llm`)
|
||||
|
||||
### Actions & Behavior
|
||||
- `initial_actions`: List of actions to run before the main task without LLM. [Example](https://github.com/browser-use/browser-use/blob/main/examples/features/initial_actions.py)
|
||||
- `max_actions_per_step` (default: `10`): Maximum actions per step, e.g. for form filling the agent can output 10 fields at once. We execute the actions until the page changes.
|
||||
- `max_failures` (default: `3`): Maximum retries for steps with errors
|
||||
- `final_response_after_failure` (default: `True`): If True, attempt to force one final model call with intermediate output after max_failures is reached
|
||||
- `use_thinking` (default: `True`): Controls whether the agent uses its internal "thinking" field for explicit reasoning steps.
|
||||
- `flash_mode` (default: `False`): Fast mode that skips evaluation, next goal and thinking and only uses memory. If `flash_mode` is enabled, it overrides `use_thinking` and disables the thinking process entirely. [Example](https://github.com/browser-use/browser-use/blob/main/examples/getting_started/05_fast_agent.py)
|
||||
|
||||
### System Messages
|
||||
- `override_system_message`: Completely replace the default system prompt.
|
||||
- `extend_system_message`: Add additional instructions to the default system prompt. [Example](https://github.com/browser-use/browser-use/blob/main/examples/features/custom_system_prompt.py)
|
||||
|
||||
### File & Data Management
|
||||
- `save_conversation_path`: Path to save complete conversation history
|
||||
- `save_conversation_path_encoding` (default: `'utf-8'`): Encoding for saved conversations
|
||||
- `available_file_paths`: List of file paths the agent can access
|
||||
- `sensitive_data`: Dictionary of sensitive data to handle carefully. [Example](https://github.com/browser-use/browser-use/blob/main/examples/features/sensitive_data.py)
|
||||
|
||||
### Visual Output
|
||||
- `generate_gif` (default: `False`): Generate GIF of agent actions. Set to `True` or string path
|
||||
- `include_attributes`: List of HTML attributes to include in page analysis
|
||||
|
||||
### Performance & Limits
|
||||
- `max_history_items`: Maximum number of last steps to keep in the LLM memory. If `None`, we keep all steps.
|
||||
- `llm_timeout` (default: `90`): Timeout in seconds for LLM calls
|
||||
- `step_timeout` (default: `120`): Timeout in seconds for each step
|
||||
- `directly_open_url` (default: `True`): If we detect a url in the task, we directly open it.
|
||||
|
||||
### Advanced Options
|
||||
- `calculate_cost` (default: `False`): Calculate and track API costs
|
||||
- `display_files_in_done_text` (default: `True`): Show file information in completion messages
|
||||
|
||||
### Backwards Compatibility
|
||||
- `controller`: Alias for `tools` for backwards compatibility.
|
||||
- `browser_session`: Alias for `browser` for backwards compatibility.
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
title: "Basics"
|
||||
description: ""
|
||||
icon: "play"
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
|
||||
```python
|
||||
from browser_use import Agent, ChatOpenAI
|
||||
|
||||
agent = Agent(
|
||||
task="Search for latest news about AI",
|
||||
llm=ChatOpenAI(model="gpt-4.1-mini"),
|
||||
)
|
||||
|
||||
async def main():
|
||||
history = await agent.run(max_steps=100)
|
||||
```
|
||||
|
||||
- `task`: The task you want to automate.
|
||||
- `llm`: Your favorite LLM. See <a href="/customize/supported-models">Supported Models</a>.
|
||||
|
||||
|
||||
The agent is executed using the async `run()` method:
|
||||
|
||||
- `max_steps` (default: `100`): Maximum number of steps an agent can take.
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
title: "Output Format"
|
||||
description: ""
|
||||
icon: "arrow-right-to-bracket"
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## Agent History
|
||||
|
||||
The `run()` method returns an `AgentHistoryList` object with the complete execution history:
|
||||
|
||||
```python
|
||||
history = await agent.run()
|
||||
|
||||
# Access useful information
|
||||
history.urls() # List of visited URLs
|
||||
history.screenshot_paths() # List of screenshot paths
|
||||
history.screenshots() # List of screenshots as base64 strings
|
||||
history.action_names() # Names of executed actions
|
||||
history.extracted_content() # List of extracted content from all actions
|
||||
history.errors() # List of errors (with None for steps without errors)
|
||||
history.model_actions() # All actions with their parameters
|
||||
history.model_outputs() # All model outputs from history
|
||||
history.last_action() # Last action in history
|
||||
|
||||
# Analysis methods
|
||||
history.final_result() # Get the final extracted content (last step)
|
||||
history.is_done() # Check if agent completed successfully
|
||||
history.is_successful() # Check if agent completed successfully (returns None if not done)
|
||||
history.has_errors() # Check if any errors occurred
|
||||
history.model_thoughts() # Get the agent's reasoning process (AgentBrain objects)
|
||||
history.action_results() # Get all ActionResult objects from history
|
||||
history.action_history() # Get truncated action history with essential fields
|
||||
history.number_of_steps() # Get the number of steps in the history
|
||||
history.total_duration_seconds() # Get total duration of all steps in seconds
|
||||
|
||||
# Structured output (when using output_model_schema)
|
||||
history.structured_output # Property that returns parsed structured output
|
||||
```
|
||||
|
||||
See all helper methods in the [AgentHistoryList source code](https://github.com/browser-use/browser-use/blob/main/browser_use/agent/views.py#L301).
|
||||
|
||||
## Structured Output
|
||||
|
||||
For structured output, use the `output_model_schema` parameter with a Pydantic model. [Example](https://github.com/browser-use/browser-use/blob/main/examples/features/custom_output.py).
|
||||
@@ -0,0 +1,92 @@
|
||||
---
|
||||
title: "Prompting Guide"
|
||||
description: "Tips and tricks "
|
||||
icon: "lightbulb"
|
||||
---
|
||||
|
||||
Prompting can trasticly improve performance and solve existing limitations of the library.
|
||||
|
||||
### 1. Be Specific vs Open-Ended
|
||||
|
||||
**✅ Specific (Recommended)**
|
||||
```python
|
||||
task = """
|
||||
1. Go to https://quotes.toscrape.com/
|
||||
2. Use extract_structured_data action with the query "first 3 quotes with their authors"
|
||||
3. Save results to quotes.csv using write_file action
|
||||
4. Do a google search for the first quote and find when it was written
|
||||
"""
|
||||
```
|
||||
|
||||
**❌ Open-Ended**
|
||||
```python
|
||||
task = "Go to web and make money"
|
||||
```
|
||||
|
||||
### 2. Name Actions Directly
|
||||
|
||||
When you know exactly what the agent should do, reference actions by name:
|
||||
|
||||
```python
|
||||
task = """
|
||||
1. Use search_google action to find "Python tutorials"
|
||||
2. Use click_element_by_index to open first result in a new tab
|
||||
3. Use scroll action to scroll down 2 pages
|
||||
4. Use extract_structured_data to extract the names of the first 5 items
|
||||
5. Wait for 2 seconds if the page is not loaded, refresh it and wait 10 sec
|
||||
6. Use send_keys action with "Tab Tab ArrowDown Enter"
|
||||
"""
|
||||
```
|
||||
|
||||
See [Available Tools](/customize/tools/available) for the complete list of actions.
|
||||
|
||||
|
||||
### 3. Handle interaction problems via keyboard navigation
|
||||
|
||||
Sometimes buttons can't be clicked (you found a bug in the library - open an issue).
|
||||
Good news - often you can work around it with keyboard navigation!
|
||||
|
||||
```python
|
||||
task = """
|
||||
If the submit button cannot be clicked:
|
||||
1. Use send_keys action with "Tab Tab Enter" to navigate and activate
|
||||
2. Or use send_keys with "ArrowDown ArrowDown Enter" for form submission
|
||||
"""
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
### 4. Custom Actions Integration
|
||||
|
||||
```python
|
||||
# When you have custom actions
|
||||
@controller.action("Get 2FA code from authenticator app")
|
||||
async def get_2fa_code():
|
||||
# Your implementation
|
||||
pass
|
||||
|
||||
task = """
|
||||
Login with 2FA:
|
||||
1. Enter username/password
|
||||
2. When prompted for 2FA, use get_2fa_code action
|
||||
3. NEVER try to extract 2FA codes from the page manually
|
||||
4. ALWAYS use the get_2fa_code action for authentication codes
|
||||
"""
|
||||
```
|
||||
|
||||
### 5. Error Recovery
|
||||
|
||||
```python
|
||||
task = """
|
||||
Robust data extraction:
|
||||
1. Go to openai.com to find their CEO
|
||||
2. If navigation fails due to anti-bot protection:
|
||||
- Use google search to find the CEO
|
||||
3. If page times out, use go_back and try alternative approach
|
||||
"""
|
||||
```
|
||||
|
||||
|
||||
|
||||
The key to effective prompting is being specific about actions.
|
||||
@@ -0,0 +1,254 @@
|
||||
---
|
||||
title: "Supported Models"
|
||||
description: "Choose your favorite LLM"
|
||||
icon: "robot"
|
||||
|
||||
---
|
||||
|
||||
### Recommendations
|
||||
|
||||
- Best accuracy: `O3`
|
||||
- Fastest: `llama4` on groq
|
||||
- Balanced: fast + cheap + clever: `gemini-2.5-flash` or `gpt-4.1-mini`
|
||||
|
||||
|
||||
### OpenAI [example](https://github.com/browser-use/browser-use/blob/main/examples/models/gpt-4.1.py)
|
||||
|
||||
`O3` model is recommended for best performance.
|
||||
|
||||
```python
|
||||
from browser_use import Agent, ChatOpenAI
|
||||
|
||||
# Initialize the model
|
||||
llm = ChatOpenAI(
|
||||
model="o3",
|
||||
)
|
||||
|
||||
# Create agent with the model
|
||||
agent = Agent(
|
||||
task="...", # Your task here
|
||||
llm=llm
|
||||
)
|
||||
```
|
||||
|
||||
Required environment variables:
|
||||
|
||||
```bash .env
|
||||
OPENAI_API_KEY=
|
||||
```
|
||||
|
||||
<Info>
|
||||
You can use any OpenAI compatible model by passing the model name to the
|
||||
`ChatOpenAI` class using a custom URL (or any other parameter that would go
|
||||
into the normal OpenAI API call).
|
||||
</Info>
|
||||
|
||||
### Anthropic [example](https://github.com/browser-use/browser-use/blob/main/examples/models/claude-4-sonnet.py)
|
||||
|
||||
```python
|
||||
from browser_use import Agent, ChatAnthropic
|
||||
|
||||
# Initialize the model
|
||||
llm = ChatAnthropic(
|
||||
model="claude-sonnet-4-0",
|
||||
)
|
||||
|
||||
# Create agent with the model
|
||||
agent = Agent(
|
||||
task="...", # Your task here
|
||||
llm=llm
|
||||
)
|
||||
```
|
||||
|
||||
And add the variable:
|
||||
|
||||
```bash .env
|
||||
ANTHROPIC_API_KEY=
|
||||
```
|
||||
|
||||
### Azure OpenAI [example](https://github.com/browser-use/browser-use/blob/main/examples/models/azure_openai.py)
|
||||
|
||||
```python
|
||||
from browser_use import Agent, ChatAzureOpenAI
|
||||
from pydantic import SecretStr
|
||||
import os
|
||||
|
||||
# Initialize the model
|
||||
llm = ChatAzureOpenAI(
|
||||
model="o4-mini",
|
||||
)
|
||||
|
||||
# Create agent with the model
|
||||
agent = Agent(
|
||||
task="...", # Your task here
|
||||
llm=llm
|
||||
)
|
||||
```
|
||||
|
||||
Required environment variables:
|
||||
|
||||
```bash .env
|
||||
AZURE_OPENAI_ENDPOINT=https://your-endpoint.openai.azure.com/
|
||||
AZURE_OPENAI_API_KEY=
|
||||
```
|
||||
|
||||
### Gemini [example](https://github.com/browser-use/browser-use/blob/main/examples/models/gemini.py)
|
||||
|
||||
> [!IMPORTANT] `GEMINI_API_KEY` was the old environment var name, it should be called `GOOGLE_API_KEY` as of 2025-05.
|
||||
|
||||
```python
|
||||
from browser_use import Agent, ChatGoogle
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Read GOOGLE_API_KEY into env
|
||||
load_dotenv()
|
||||
|
||||
# Initialize the model
|
||||
llm = ChatGoogle(model='gemini-2.5-flash')
|
||||
|
||||
# Create agent with the model
|
||||
agent = Agent(
|
||||
task="Your task here",
|
||||
llm=llm
|
||||
)
|
||||
```
|
||||
|
||||
Required environment variables:
|
||||
|
||||
```bash .env
|
||||
GOOGLE_API_KEY=
|
||||
```
|
||||
|
||||
### AWS Bedrock [example](https://github.com/browser-use/browser-use/blob/main/examples/models/aws.py)
|
||||
|
||||
AWS Bedrock provides access to multiple model providers through a single API. We support both a general AWS Bedrock client and provider-specific convenience classes.
|
||||
|
||||
#### General AWS Bedrock (supports all providers)
|
||||
|
||||
```python
|
||||
from browser_use import Agent, ChatAWSBedrock
|
||||
|
||||
# Works with any Bedrock model (Anthropic, Meta, AI21, etc.)
|
||||
llm = ChatAWSBedrock(
|
||||
model="anthropic.claude-3-5-sonnet-20240620-v1:0", # or any Bedrock model
|
||||
aws_region="us-east-1",
|
||||
)
|
||||
|
||||
# Create agent with the model
|
||||
agent = Agent(
|
||||
task="Your task here",
|
||||
llm=llm
|
||||
)
|
||||
```
|
||||
|
||||
#### Anthropic Claude via AWS Bedrock (convenience class)
|
||||
|
||||
```python
|
||||
from browser_use import Agent, ChatAnthropicBedrock
|
||||
|
||||
# Anthropic-specific class with Claude defaults
|
||||
llm = ChatAnthropicBedrock(
|
||||
model="anthropic.claude-3-5-sonnet-20240620-v1:0",
|
||||
aws_region="us-east-1",
|
||||
)
|
||||
|
||||
# Create agent with the model
|
||||
agent = Agent(
|
||||
task="Your task here",
|
||||
llm=llm
|
||||
)
|
||||
```
|
||||
|
||||
#### AWS Authentication
|
||||
|
||||
Required environment variables:
|
||||
|
||||
```bash .env
|
||||
AWS_ACCESS_KEY_ID=
|
||||
AWS_SECRET_ACCESS_KEY=
|
||||
AWS_DEFAULT_REGION=us-east-1
|
||||
```
|
||||
|
||||
You can also use AWS profiles or IAM roles instead of environment variables. The implementation supports:
|
||||
|
||||
- Environment variables (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_DEFAULT_REGION`)
|
||||
- AWS profiles and credential files
|
||||
- IAM roles (when running on EC2)
|
||||
- Session tokens for temporary credentials
|
||||
- AWS SSO authentication (`aws_sso_auth=True`)
|
||||
|
||||
## Groq [example](https://github.com/browser-use/browser-use/blob/main/examples/models/llama4-groq.py)
|
||||
|
||||
```python
|
||||
from browser_use import Agent, ChatGroq
|
||||
|
||||
llm = ChatGroq(model="meta-llama/llama-4-maverick-17b-128e-instruct")
|
||||
|
||||
agent = Agent(
|
||||
task="Your task here",
|
||||
llm=llm
|
||||
)
|
||||
```
|
||||
|
||||
Required environment variables:
|
||||
|
||||
```bash .env
|
||||
GROQ_API_KEY=
|
||||
```
|
||||
|
||||
## Ollama
|
||||
|
||||
1. Install Ollama: https://github.com/ollama/ollama
|
||||
2. Run `ollama serve` to start the server
|
||||
3. In a new terminal, install the model you want to use: `ollama pull llama3.1:8b` (this has 4.9GB)
|
||||
|
||||
```python
|
||||
from browser_use import Agent, ChatOllama
|
||||
|
||||
llm = ChatOllama(model="llama3.1:8b")
|
||||
```
|
||||
|
||||
## Langchain
|
||||
|
||||
[Example](https://github.com/browser-use/browser-use/blob/main/examples/models/langchain) on how to use Langchain with Browser Use.
|
||||
|
||||
## Qwen [example](https://github.com/browser-use/browser-use/blob/main/examples/models/qwen.py)
|
||||
|
||||
Currently, only `qwen-vl-max` is recommended for Browser Use. Other Qwen models, including `qwen-max`, have issues with the action schema format.
|
||||
Smaller Qwen models may return incorrect action schema formats (e.g., `actions: [{"go_to_url": "google.com"}]` instead of `[{"go_to_url": {"url": "google.com"}}]`). If you want to use other models, add concrete examples of the correct action format to your prompt.
|
||||
|
||||
```python
|
||||
from browser_use import Agent, ChatOpenAI
|
||||
from dotenv import load_dotenv
|
||||
import os
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# Get API key from https://modelstudio.console.alibabacloud.com/?tab=playground#/api-key
|
||||
api_key = os.getenv('ALIBABA_CLOUD')
|
||||
base_url = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1'
|
||||
|
||||
llm = ChatOpenAI(model='qwen-vl-max', api_key=api_key, base_url=base_url)
|
||||
|
||||
agent = Agent(
|
||||
task="Your task here",
|
||||
llm=llm,
|
||||
use_vision=True
|
||||
)
|
||||
```
|
||||
|
||||
Required environment variables:
|
||||
|
||||
```bash .env
|
||||
ALIBABA_CLOUD=
|
||||
```
|
||||
|
||||
|
||||
## Other models (DeepSeek, Novita, X...)
|
||||
|
||||
We support all other models that can be called via OpenAI compatible API. We are open to PRs for more providers.
|
||||
|
||||
**Examples available:**
|
||||
- [DeepSeek](https://github.com/browser-use/browser-use/blob/main/examples/models/deepseek-chat.py)
|
||||
- [Novita](https://github.com/browser-use/browser-use/blob/main/examples/models/novita.py)
|
||||
- [OpenRouter](https://github.com/browser-use/browser-use/blob/main/examples/models/openrouter.py)
|
||||
Reference in New Issue
Block a user