Full Code of huggingface/smolagents for AI

main edb04feae012 cached
183 files
1.8 MB
444.9k tokens
1426 symbols
1 requests
Download .txt
Showing preview only (1,874K chars total). Download the full file or copy to clipboard to get everything.
Repository: huggingface/smolagents
Branch: main
Commit: edb04feae012
Files: 183
Total size: 1.8 MB

Directory structure:
gitextract_wncyz_3h/

├── .github/
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug_report.md
│   │   ├── doc_improvement.md
│   │   └── feature_request.md
│   └── workflows/
│       ├── build_documentation.yml
│       ├── build_pr_documentation.yml
│       ├── quality.yml
│       ├── tests.yml
│       ├── trufflehog.yml
│       └── upload_pr_documentation.yml
├── .gitignore
├── .pre-commit-config.yaml
├── AGENTS.md
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── Makefile
├── README.md
├── SECURITY.md
├── docs/
│   ├── README.md
│   └── source/
│       ├── en/
│       │   ├── _config.py
│       │   ├── _toctree.yml
│       │   ├── conceptual_guides/
│       │   │   ├── intro_agents.md
│       │   │   └── react.md
│       │   ├── examples/
│       │   │   ├── async_agent.md
│       │   │   ├── multiagents.md
│       │   │   ├── plan_customization.md
│       │   │   ├── rag.md
│       │   │   ├── text_to_sql.md
│       │   │   ├── using_different_models.md
│       │   │   └── web_browser.md
│       │   ├── guided_tour.md
│       │   ├── index.md
│       │   ├── installation.md
│       │   ├── reference/
│       │   │   ├── agents.md
│       │   │   ├── default_tools.md
│       │   │   ├── models.md
│       │   │   ├── python_executors.md
│       │   │   └── tools.md
│       │   └── tutorials/
│       │       ├── building_good_agents.md
│       │       ├── inspect_runs.md
│       │       ├── memory.md
│       │       ├── secure_code_execution.md
│       │       └── tools.md
│       ├── es/
│       │   ├── _config.py
│       │   ├── _toctree.yml
│       │   ├── index.md
│       │   └── installation.md
│       ├── hi/
│       │   ├── _config.py
│       │   ├── _toctree.yml
│       │   ├── conceptual_guides/
│       │   │   ├── intro_agents.md
│       │   │   └── react.md
│       │   ├── examples/
│       │   │   ├── multiagents.md
│       │   │   ├── rag.md
│       │   │   └── text_to_sql.md
│       │   ├── guided_tour.md
│       │   ├── index.md
│       │   ├── reference/
│       │   │   ├── agents.md
│       │   │   └── tools.md
│       │   └── tutorials/
│       │       ├── building_good_agents.md
│       │       ├── inspect_runs.md
│       │       ├── secure_code_execution.md
│       │       └── tools.md
│       ├── ko/
│       │   ├── _config.py
│       │   ├── _toctree.yml
│       │   ├── conceptual_guides/
│       │   │   └── react.md
│       │   ├── examples/
│       │   │   ├── async_agent.md
│       │   │   ├── multiagents.md
│       │   │   ├── plan_customization.md
│       │   │   ├── rag.md
│       │   │   ├── text_to_sql.md
│       │   │   ├── using_different_models.md
│       │   │   └── web_browser.md
│       │   ├── guided_tour.md
│       │   ├── index.md
│       │   ├── installation.md
│       │   ├── reference/
│       │   │   ├── agents.md
│       │   │   ├── models.md
│       │   │   └── tools.md
│       │   └── tutorials/
│       │       ├── building_good_agents.md
│       │       ├── inspect_runs.md
│       │       └── memory.md
│       └── zh/
│           ├── _config.py
│           ├── _toctree.yml
│           ├── conceptual_guides/
│           │   ├── intro_agents.md
│           │   └── react.md
│           ├── examples/
│           │   ├── multiagents.md
│           │   ├── rag.md
│           │   ├── text_to_sql.md
│           │   └── web_browser.md
│           ├── guided_tour.md
│           ├── index.md
│           ├── reference/
│           │   ├── agents.md
│           │   ├── models.md
│           │   └── tools.md
│           └── tutorials/
│               ├── building_good_agents.md
│               ├── inspect_runs.md
│               ├── memory.md
│               ├── secure_code_execution.md
│               └── tools.md
├── e2b.toml
├── examples/
│   ├── agent_from_any_llm.py
│   ├── async_agent/
│   │   ├── README.md
│   │   ├── main.py
│   │   └── requirements.txt
│   ├── gradio_ui.py
│   ├── inspect_multiagent_run.py
│   ├── multi_llm_agent.py
│   ├── multiple_tools.py
│   ├── open_deep_research/
│   │   ├── README.md
│   │   ├── analysis.ipynb
│   │   ├── app.py
│   │   ├── requirements.txt
│   │   ├── run.py
│   │   ├── run_gaia.py
│   │   ├── scripts/
│   │   │   ├── cookies.py
│   │   │   ├── gaia_scorer.py
│   │   │   ├── mdconvert.py
│   │   │   ├── reformulator.py
│   │   │   ├── run_agents.py
│   │   │   ├── text_inspector_tool.py
│   │   │   ├── text_web_browser.py
│   │   │   └── visual_qa.py
│   │   └── visual_vs_text_browser.ipynb
│   ├── plan_customization/
│   │   ├── README.md
│   │   └── plan_customization.py
│   ├── rag.py
│   ├── rag_using_chromadb.py
│   ├── sandboxed_execution.py
│   ├── server/
│   │   ├── README.md
│   │   └── main.py
│   ├── smolagents_benchmark/
│   │   ├── run.py
│   │   └── score.ipynb
│   ├── structured_output_tool.py
│   └── text_to_sql.py
├── pyproject.toml
├── src/
│   └── smolagents/
│       ├── __init__.py
│       ├── _function_type_hints_utils.py
│       ├── agent_types.py
│       ├── agents.py
│       ├── cli.py
│       ├── default_tools.py
│       ├── gradio_ui.py
│       ├── local_python_executor.py
│       ├── mcp_client.py
│       ├── memory.py
│       ├── models.py
│       ├── monitoring.py
│       ├── prompts/
│       │   ├── code_agent.yaml
│       │   ├── structured_code_agent.yaml
│       │   └── toolcalling_agent.yaml
│       ├── remote_executors.py
│       ├── serialization.py
│       ├── tool_validation.py
│       ├── tools.py
│       ├── utils.py
│       └── vision_web_browser.py
└── tests/
    ├── __init__.py
    ├── conftest.py
    ├── fixtures/
    │   ├── agents.py
    │   └── tools.py
    ├── test_agents.py
    ├── test_all_docs.py
    ├── test_cli.py
    ├── test_default_tools.py
    ├── test_final_answer.py
    ├── test_function_type_hints_utils.py
    ├── test_gradio_ui.py
    ├── test_import.py
    ├── test_local_python_executor.py
    ├── test_mcp_client.py
    ├── test_memory.py
    ├── test_models.py
    ├── test_monitoring.py
    ├── test_remote_executors.py
    ├── test_search.py
    ├── test_serialization.py
    ├── test_telemetry.py
    ├── test_tool_validation.py
    ├── test_tools.py
    ├── test_types.py
    ├── test_utils.py
    ├── test_vision_web_browser.py
    └── utils/
        └── markers.py

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.md
================================================
---
name: Bug report
about: The clearer your bug report, the faster it will be fixed!
title: "BUG: "
labels: bug
assignees: ''

---

<!--
Thank you for reporting a bug!
Please provide as much detail as possible to help us identify and fix the issue.
-->

**Problem**
A clear and concise description of what the bug is.

**Steps to reproduce**
Please provide a minimal, self-contained, and reproducible example of the bug.
1.  ...
2.  ...
3.  ...

```python
# Your code to reproduce the bug here
```

**Actual behavior and error logs**
A clear and concise description of what actually happened. Please include the full traceback if an exception was raised.
```shell

```

**Expected behavior**
A clear and concise description of what you expected to happen.

**Environment:**
Please complete the following information:
- OS: [e.g., Linux, macOS, Windows]
- Python version: [e.g., 3.10]
- Package version: (output of `pip show smolagents`)
```

```

**Additional context (optional)**
Add any other context, screenshots, or links about the bug here.

---

### Checklist
- [ ] I have searched the existing issues and have not found a similar bug report.
- [ ] I have provided a minimal, reproducible example.
- [ ] I have provided the full traceback of the error.
- [ ] I have provided my environment details.
- [ ] I am willing to work on this issue and submit a pull request. (optional)


================================================
FILE: .github/ISSUE_TEMPLATE/doc_improvement.md
================================================
---
name: Documentation Improvement
about: Report wrong or missing documentation
title: 'DOC: '
labels: documentation
assignees: ''

---

<!--
Thank you for contributing to our documentation!
Please provide as much detail as possible.
-->

**Problem**
A clear and description of what is wrong or missing in the documentation.

**Location of the documentation**
Provide the specific location of the documentation that needs improvement. Select what is applicable:
- Function/Class/Method name:  (if applicable: e.g., `module.ClassName.method_name`)
- URL: (if applicable: e.g. `https://huggingface.co/docs/smolagents/installation`)

**Suggested improvement**
A clear and concise description of the fix and improvement you suggest and why it is better.

**Additional context (optional)**
Add any other context or screenshots about the documentation improvement here.

---

### Checklist
- [ ] I have searched the existing issues and have not found a similar issue.
- [ ] I am willing to work on this issue and submit a pull request. (optional)


================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.md
================================================
---
name: Feature request
about: Suggest an idea for this project
title: 'ENH: '
labels: enhancement
assignees: ''

---

<!--
Thank you for suggesting an idea to improve this project!
Please provide as much detail as possible.
-->

**Problem**
A clear and concise description of what the problem is that this feature would solve. For example, "I'm always frustrated when..."

**Proposed solution**
A clear and concise description of what you want to happen.

**Is this not possible with the current options.**
Make sure to consider if what you're requesting can be done with current abstractions.

**Alternatives considered**
A clear and concise description of any alternative solutions or features you've considered.
Please also describe if what you're requesting can be achieved with the current abstractions, and if so, why a new feature is still needed.

**Additional context (optional)**
Add any other context, screenshots, or links about the feature request here.

---

### Checklist
- [ ] I have searched the existing issues and have not found a similar feature request.
- [ ] I have verified that this feature is not already implemented in the latest version.
- [ ] I am willing to work on this feature and submit a pull request. (optional)


================================================
FILE: .github/workflows/build_documentation.yml
================================================
name: Build documentation

on:
  push:
    branches:
      - main
      - doc-builder*
      - v*-release
      - use_templates
    paths:
      - 'docs/source/**'
      - 'assets/**'
      - '.github/workflows/doc-build.yml'
      - 'pyproject.toml'

jobs:
   build:
    uses: huggingface/doc-builder/.github/workflows/build_main_documentation.yml@main
    with:
      commit_sha: ${{ github.sha }}
      package: smolagents
      languages: en hi ko zh
      notebook_folder: smolagents_doc
      # additional_args: --not_python_module # use this arg if repository is documentation only
    secrets:
      token: ${{ secrets.HUGGINGFACE_PUSH }}
      hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }}

================================================
FILE: .github/workflows/build_pr_documentation.yml
================================================
name: Build PR Documentation

on:
  pull_request:
    paths:
      - 'docs/source/**'
      - 'assets/**'
      - '.github/workflows/doc-pr-build.yml'

concurrency:
  group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
  cancel-in-progress: true

jobs:
  build:
    uses: huggingface/doc-builder/.github/workflows/build_pr_documentation.yml@main
    with:
      commit_sha: ${{ github.event.pull_request.head.sha }}
      pr_number: ${{ github.event.number }}
      package: smolagents
      languages: en hi ko zh
      # additional_args: --not_python_module # use this arg if repository is documentation only

================================================
FILE: .github/workflows/quality.yml
================================================
name: Quality Check

on: [pull_request]

env:
  UV_SYSTEM_PYTHON: 1

jobs:
  check_code_quality:
    runs-on: ubuntu-latest
    env:
      UV_HTTP_TIMEOUT: 600 # max 10min to install deps

    steps:
      - uses: actions/checkout@v6
      - name: Set up Python
        uses: actions/setup-python@v6
        with:
          python-version: "3.12"

      # Setup venv
      - name: Setup uv
        run: |
          pip install --upgrade uv

      - name: Install dependencies
        run: uv pip install "smolagents[quality] @ ."

      # Equivalent of "make quality" but step by step
      - run: ruff check examples src tests  # linter
      - run: ruff format --check examples src tests  # formatter


================================================
FILE: .github/workflows/tests.yml
================================================
name: Python tests

on:
  pull_request:
  push:
    branches:
      - ci-*

env:
  UV_SYSTEM_PYTHON: 1

jobs:
  build-ubuntu:
    runs-on: ubuntu-latest
    env:
      UV_HTTP_TIMEOUT: 600 # max 10min to install deps

    strategy:
      fail-fast: false
      matrix:
        python-version: ["3.10", "3.12"]

    steps:
      - uses: actions/checkout@v6
      - name: Set up Python ${{ matrix.python-version }}
        uses: actions/setup-python@v6
        with:
          python-version: ${{ matrix.python-version }}

      # Setup venv
      - name: Setup uv
        run: |
          pip install --upgrade uv

      # Install dependencies
      - name: Install dependencies
        run: |
          uv pip install "smolagents[test] @ ."

      # Run tests
      - name: Test with pytest
        run: |
          pytest ./tests/


================================================
FILE: .github/workflows/trufflehog.yml
================================================
on:
  push:

name: Secret Leaks

permissions:
  contents: read

jobs:
  trufflehog:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v6
        with:
          fetch-depth: 0
      - name: Secret Scanning
        uses: trufflesecurity/trufflehog@main

================================================
FILE: .github/workflows/upload_pr_documentation.yml
================================================
name: Upload PR Documentation

on:
  workflow_run:
    workflows: ["Build PR Documentation"]
    types:
      - completed

jobs:
  build:
    uses: huggingface/doc-builder/.github/workflows/upload_pr_documentation.yml@main
    with:
      package_name: smolagents
    secrets:
      hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }}
      comment_bot_token: ${{ secrets.COMMENT_BOT_TOKEN }}

================================================
FILE: .gitignore
================================================
# Logging
logs
tmp
wandb

# Data
data
outputs
data/

# Apple
.DS_Store

# VS Code
.vscode

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
node_modules/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
uv.lock

# Translations
*.mo
*.pot

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# .python-version

# pipenv
#Pipfile.lock

# poetry
#poetry.lock

# pdm
.pdm.toml
.pdm-python
.pdm-build/

# PEP 582
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/


# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
.idea/

# Interpreter
interpreter_workspace/

# Archive
archive/
savedir/
output/
tool_output/

# Gradio runtime
.gradio/

================================================
FILE: .pre-commit-config.yaml
================================================
repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.2.1
    hooks:
      - id: ruff
        args:
          - --fix
      - id: ruff-format
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.5.0
    hooks:
      - id: check-merge-conflict
      - id: check-yaml


================================================
FILE: AGENTS.md
================================================
# Contributor Guidelines
- Follow OOP principles
- Be Pythonic: follow Python best practices and idiomatic patterns
- Write unit tests for new functionality


================================================
FILE: CODE_OF_CONDUCT.md
================================================

# Contributor Covenant Code of Conduct

## Our Pledge

We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, caste, color, religion, or sexual
identity and orientation.

We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.

## Our Standards

Examples of behavior that contributes to a positive environment for our
community include:

* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
  and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall
  community

Examples of unacceptable behavior include:

* The use of sexualized language or imagery, and sexual attention or advances of
  any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email address,
  without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
  professional setting

## Enforcement Responsibilities

Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.

Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.

## Scope

This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
feedback@huggingface.co.
All complaints will be reviewed and investigated promptly and fairly.

All community leaders are obligated to respect the privacy and security of the
reporter of any incident.

## Enforcement Guidelines

Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:

### 1. Correction

**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.

**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.

### 2. Warning

**Community Impact**: A violation through a single incident or series of
actions.

**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or permanent
ban.

### 3. Temporary Ban

**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.

**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.

### 4. Permanent Ban

**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.

**Consequence**: A permanent ban from any sort of public interaction within the
community.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.1, available at
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].

Community Impact Guidelines were inspired by
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].

For answers to common questions about this code of conduct, see the FAQ at
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
[https://www.contributor-covenant.org/translations][translations].

[homepage]: https://www.contributor-covenant.org
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
[Mozilla CoC]: https://github.com/mozilla/diversity
[FAQ]: https://www.contributor-covenant.org/faq
[translations]: https://www.contributor-covenant.org/translations

================================================
FILE: CONTRIBUTING.md
================================================
<!---
Copyright 2025 The HuggingFace Team. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

# Contribute to smolagents

Everyone is welcome to contribute, and we value everybody's contribution. Code
contributions are not the only way to help the community. Answering questions, helping
others, and improving the documentation are also immensely valuable.

It also helps us if you spread the word! Reference the library in blog posts
about the awesome projects it made possible, shout out on Twitter every time it has
helped you, or simply ⭐️ the repository to say thank you.

However you choose to contribute, please be mindful and respect our
[code of conduct](https://github.com/huggingface/smolagents/blob/main/CODE_OF_CONDUCT.md).

**This guide was heavily inspired by the awesome [scikit-learn guide to contributing](https://github.com/scikit-learn/scikit-learn/blob/main/CONTRIBUTING.md).**

## Ways to contribute

There are several ways you can contribute to smolagents.

* Submit issues related to bugs or desired new features.
* Contribute to the examples or to the documentation.
* Fix outstanding issues with the existing code.

> All contributions are equally valuable to the community. 🥰

## Submitting a bug-related issue or feature request

At any moment, feel welcome to open an issue, citing your exact error traces and package versions if it's a bug.
It's often even better to open a PR with your proposed fixes/changes!

Do your best to follow these guidelines when submitting a bug-related issue or a feature
request. It will make it easier for us to come back to you quickly and with good
feedback.

### Did you find a bug?

The smolagents library is robust and reliable thanks to users who report the problems they encounter.

Before you report an issue, we would really appreciate it if you could **make sure the bug was not
already reported** (use the search bar on GitHub under Issues). Your issue should also be related to bugs in the 
library itself, and not your code. 

Once you've confirmed the bug hasn't already been reported, please include the following information in your issue so 
we can quickly resolve it:

* Your **OS type and version**, as well as your environment versions (versions of rust, python, and dependencies).
* A short, self-contained, code snippet that allows us to reproduce the bug.
* The *full* traceback if an exception is raised.
* Attach any other additional information, like screenshots, you think may help.

### Do you want a new feature?

If there is a new feature you'd like to see in smolagents, please open an issue and describe:

1. What is the *motivation* behind this feature? Is it related to a problem or frustration with the library? Is it 
   a feature related to something you need for a project? Is it something you worked on and think it could benefit 
   the community?

   Whatever it is, we'd love to hear about it!

2. Describe your requested feature in as much detail as possible. The more you can tell us about it, the better 
   we'll be able to help you.
3. Provide a *code snippet* that demonstrates the feature's usage.
4. If the feature is related to a paper, please include a link.

If your issue is well written we're already 80% of the way there by the time you create it.

## Do you want to add documentation?

We're always looking for improvements to the documentation that make it more clear and accurate. Please let us know 
how the documentation can be improved such as typos and any content that is missing, unclear or inaccurate. We'll be 
happy to make the changes or help you make a contribution if you're interested!

## Fixing outstanding issues

If you notice an issue with the existing code and have a fix in mind, feel free to [start contributing](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request) and open
a Pull Request!

### Making code changes

To install dev dependencies, run:
<details>
<summary><strong>Using pip</strong></summary>

```
pip install -e ".[dev]"
```

</details>
<details>
<summary><strong>Using uv</strong></summary>

```
uv pip install -e "smolagents[dev] @ ."
```

</details>

When making changes to the codebase, please check that it follows the repo's code quality requirements by running:
To check code quality of the source code:
```
make quality
```

If the checks fail, you can run the formatter with:
```
make style
```

And commit the changes.

To run tests locally, run this command:
```bash
make test
```
</details>

## I want to become a maintainer of the project. How do I get there?

smolagents is a project led and managed by Hugging Face. We are more than
happy to have motivated individuals from other organizations join us as maintainers with the goal of helping smolagents
make a dent in the world of Agents.

If you are such an individual (or organization), please reach out to us and let's collaborate.


================================================
FILE: LICENSE
================================================
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.


================================================
FILE: Makefile
================================================
.PHONY: quality style test docs

check_dirs := examples src tests

# Check code quality of the source code
quality:
	ruff check $(check_dirs)
	ruff format --check $(check_dirs)

# Format source code automatically
style:
	ruff check $(check_dirs) --fix
	ruff format $(check_dirs)
	
# Run smolagents tests
test:
	pytest ./tests/

================================================
FILE: README.md
================================================
<!---
Copyright 2024 The HuggingFace Team. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<p align="center">
    <!-- Uncomment when CircleCI is set up
    <a href="https://circleci.com/gh/huggingface/accelerate"><img alt="Build" src="https://img.shields.io/circleci/build/github/huggingface/transformers/master"></a>
    -->
    <a href="https://github.com/huggingface/smolagents/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/github/license/huggingface/smolagents.svg?color=blue"></a>
    <a href="https://huggingface.co/docs/smolagents"><img alt="Documentation" src="https://img.shields.io/website/http/huggingface.co/docs/smolagents/index.html.svg?down_color=red&down_message=offline&up_message=online"></a>
    <a href="https://github.com/huggingface/smolagents/releases"><img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/smolagents.svg"></a>
    <a href="https://github.com/huggingface/smolagents/blob/main/CODE_OF_CONDUCT.md"><img alt="Contributor Covenant" src="https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg"></a>
    <a href="https://deepwiki.com/huggingface/smolagents"><img src="https://deepwiki.com/badge.svg" alt="Ask DeepWiki"></a>
</p>

<h3 align="center">
  <div style="display:flex;flex-direction:row;">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/smolagents/smolagents.png" alt="Hugging Face mascot as James Bond" width=400px>
    <p>Agents that think in code!</p>
  </div>
</h3>

`smolagents` is a library that enables you to run powerful agents in a few lines of code. It offers:

✨ **Simplicity**: the logic for agents fits in ~1,000 lines of code (see [agents.py](https://github.com/huggingface/smolagents/blob/main/src/smolagents/agents.py)). We kept abstractions to their minimal shape above raw code!

🧑‍💻 **First-class support for Code Agents**. Our [`CodeAgent`](https://huggingface.co/docs/smolagents/reference/agents#smolagents.CodeAgent) writes its actions in code (as opposed to "agents being used to write code"). To make it secure, we support executing in sandboxed environments via [Blaxel](https://blaxel.ai), [E2B](https://e2b.dev/), [Modal](https://modal.com/), Docker, or Pyodide+Deno WebAssembly sandbox.

🤗 **Hub integrations**: you can [share/pull tools or agents to/from the Hub](https://huggingface.co/docs/smolagents/reference/tools#smolagents.Tool.from_hub) for instant sharing of the most efficient agents!

🌐 **Model-agnostic**: smolagents supports any LLM. It can be a local `transformers` or `ollama` model, one of [many providers on the Hub](https://huggingface.co/blog/inference-providers), or any model from OpenAI, Anthropic and many others via our [LiteLLM](https://www.litellm.ai/) integration.

👁️ **Modality-agnostic**: Agents support text, vision, video, even audio inputs! Cf [this tutorial](https://huggingface.co/docs/smolagents/examples/web_browser) for vision.

🛠️ **Tool-agnostic**: you can use tools from any [MCP server](https://huggingface.co/docs/smolagents/reference/tools#smolagents.ToolCollection.from_mcp), from [LangChain](https://huggingface.co/docs/smolagents/reference/tools#smolagents.Tool.from_langchain), you can even use a [Hub Space](https://huggingface.co/docs/smolagents/reference/tools#smolagents.Tool.from_space) as a tool.

Full documentation can be found [here](https://huggingface.co/docs/smolagents/index).

> [!NOTE]
> Check the our [launch blog post](https://huggingface.co/blog/smolagents) to learn more about `smolagents`!

## Quick demo

First install the package with a default set of tools:
```bash
pip install "smolagents[toolkit]"
```
Then define your agent, give it the tools it needs and run it!
```py
from smolagents import CodeAgent, WebSearchTool, InferenceClientModel

model = InferenceClientModel()
agent = CodeAgent(tools=[WebSearchTool()], model=model, stream_outputs=True)

agent.run("How many seconds would it take for a leopard at full speed to run through Pont des Arts?")
```

https://github.com/user-attachments/assets/84b149b4-246c-40c9-a48d-ba013b08e600

You can even share your agent to the Hub, as a Space repository:
```py
agent.push_to_hub("m-ric/my_agent")

# agent.from_hub("m-ric/my_agent") to load an agent from Hub
```

Our library is LLM-agnostic: you could switch the example above to any inference provider.

<details>
<summary> <b>InferenceClientModel, gateway for all <a href="https://huggingface.co/docs/inference-providers/index">inference providers</a> supported on HF</b></summary>

```py
from smolagents import InferenceClientModel

model = InferenceClientModel(
    model_id="deepseek-ai/DeepSeek-R1",
    provider="together",
)
```
</details>
<details>
<summary> <b>LiteLLM to access 100+ LLMs</b></summary>

```py
from smolagents import LiteLLMModel

model = LiteLLMModel(
    model_id="anthropic/claude-4-sonnet-latest",
    temperature=0.2,
    api_key=os.environ["ANTHROPIC_API_KEY"]
)
```
</details>
<details>
<summary> <b>OpenAI-compatible servers: Together AI</b></summary>

```py
import os
from smolagents import OpenAIModel

model = OpenAIModel(
    model_id="deepseek-ai/DeepSeek-R1",
    api_base="https://api.together.xyz/v1/", # Leave this blank to query OpenAI servers.
    api_key=os.environ["TOGETHER_API_KEY"], # Switch to the API key for the server you're targeting.
)
```
</details>
<details>
<summary> <b>OpenAI-compatible servers: OpenRouter</b></summary>

```py
import os
from smolagents import OpenAIModel

model = OpenAIModel(
    model_id="openai/gpt-4o",
    api_base="https://openrouter.ai/api/v1", # Leave this blank to query OpenAI servers.
    api_key=os.environ["OPENROUTER_API_KEY"], # Switch to the API key for the server you're targeting.
)
```

</details>
<details>
<summary> <b>Local `transformers` model</b></summary>

```py
from smolagents import TransformersModel

model = TransformersModel(
    model_id="Qwen/Qwen3-Next-80B-A3B-Thinking",
    max_new_tokens=4096,
    device_map="auto"
)
```
</details>
<details>
<summary> <b>Azure models</b></summary>

```py
import os
from smolagents import AzureOpenAIModel

model = AzureOpenAIModel(
    model_id = os.environ.get("AZURE_OPENAI_MODEL"),
    azure_endpoint=os.environ.get("AZURE_OPENAI_ENDPOINT"),
    api_key=os.environ.get("AZURE_OPENAI_API_KEY"),
    api_version=os.environ.get("OPENAI_API_VERSION")    
)
```
</details>
<details>
<summary> <b>Amazon Bedrock models</b></summary>

```py
import os
from smolagents import AmazonBedrockModel

model = AmazonBedrockModel(
    model_id = os.environ.get("AMAZON_BEDROCK_MODEL_ID") 
)
```
</details>

## CLI

You can run agents from CLI using two commands: `smolagent` and `webagent`.

`smolagent` is a generalist command to run a multi-step `CodeAgent` that can be equipped with various tools.

```bash
# Run with direct prompt and options
smolagent "Plan a trip to Tokyo, Kyoto and Osaka between Mar 28 and Apr 7."  --model-type "InferenceClientModel" --model-id "Qwen/Qwen3-Next-80B-A3B-Thinking" --imports pandas numpy --tools web_search

# Run in interactive mode (launches setup wizard when no prompt provided)
smolagent
```

Interactive mode guides you through:
- Agent type selection (CodeAgent vs ToolCallingAgent)  
- Tool selection from available toolbox
- Model configuration (type, ID, API settings)
- Advanced options like additional imports
- Task prompt input

Meanwhile `webagent` is a specific web-browsing agent using [helium](https://github.com/mherrmann/helium) (read more [here](https://github.com/huggingface/smolagents/blob/main/src/smolagents/vision_web_browser.py)).

For instance:
```bash
webagent "go to xyz.com/men, get to sale section, click the first clothing item you see. Get the product details, and the price, return them. note that I'm shopping from France" --model-type "LiteLLMModel" --model-id "gpt-5"
```

## How do Code agents work?

Our [`CodeAgent`](https://huggingface.co/docs/smolagents/reference/agents#smolagents.CodeAgent) works mostly like classical ReAct agents - the exception being that the LLM engine writes its actions as Python code snippets.

```mermaid
flowchart TB
    Task[User Task]
    Memory[agent.memory]
    Generate[Generate from agent.model]
    Execute[Execute Code action - Tool calls are written as functions]
    Answer[Return the argument given to 'final_answer']

    Task -->|Add task to agent.memory| Memory

    subgraph ReAct[ReAct loop]
        Memory -->|Memory as chat messages| Generate
        Generate -->|Parse output to extract code action| Execute
        Execute -->|No call to 'final_answer' tool => Store execution logs in memory and keep running| Memory
    end
    
    Execute -->|Call to 'final_answer' tool| Answer

    %% Styling
    classDef default fill:#d4b702,stroke:#8b7701,color:#ffffff
    classDef io fill:#4a5568,stroke:#2d3748,color:#ffffff
    
    class Task,Answer io
```

Actions are now Python code snippets. Hence, tool calls will be performed as Python function calls. For instance, here is how the agent can perform web search over several websites in one single action:
```py
requests_to_search = ["gulf of mexico america", "greenland denmark", "tariffs"]
for request in requests_to_search:
    print(f"Here are the search results for {request}:", web_search(request))
```

Writing actions as code snippets is demonstrated to work better than the current industry practice of letting the LLM output a dictionary of the tools it wants to call: [uses 30% fewer steps](https://huggingface.co/papers/2402.01030) (thus 30% fewer LLM calls) and [reaches higher performance on difficult benchmarks](https://huggingface.co/papers/2411.01747). Head to [our high-level intro to agents](https://huggingface.co/docs/smolagents/conceptual_guides/intro_agents) to learn more on that.

Since code execution can be a serious security concern (arbitrary code execution!), **you should run agent code in a sandbox**. We support several options:
  - [E2B](https://e2b.dev/), [Blaxel](https://blaxel.ai), [Modal](https://modal.com/) — managed cloud sandboxes, simplest to set up
  - [Docker](https://www.docker.com/) — self-hosted container isolation
  - Pyodide+Deno WebAssembly — lightweight sandbox for browser or edge environments

The built-in `LocalPythonExecutor` is **not a security sandbox**. It applies some restrictions but can be bypassed and must not be used as a security boundary.

Alongside [`CodeAgent`](https://huggingface.co/docs/smolagents/reference/agents#smolagents.CodeAgent), we also provide the standard [`ToolCallingAgent`](https://huggingface.co/docs/smolagents/reference/agents#smolagents.ToolCallingAgent) which writes actions as JSON/text blobs. You can pick whichever style best suits your use case.

## How smol is this library?

We strived to keep abstractions to a strict minimum: the main code in `agents.py` has <1,000 lines of code.
Still, we implement several types of agents: `CodeAgent` writes its actions as Python code snippets, and the more classic `ToolCallingAgent` leverages built-in tool calling methods. We also have multi-agent hierarchies, import from tool collections, remote code execution, vision models...

By the way, why use a framework at all? Well, because a big part of this stuff is non-trivial. For instance, the code agent has to keep a consistent format for code throughout its system prompt, its parser, the execution. So our framework handles this complexity for you. But of course we still encourage you to hack into the source code and use only the bits that you need, to the exclusion of everything else!

## How strong are open models for agentic workflows?

We've created [`CodeAgent`](https://huggingface.co/docs/smolagents/reference/agents#smolagents.CodeAgent) instances with some leading models, and compared them on [this benchmark](https://huggingface.co/datasets/m-ric/agents_medium_benchmark_2) that gathers questions from a few different benchmarks to propose a varied blend of challenges.

[Find the benchmarking code here](https://github.com/huggingface/smolagents/blob/main/examples/smolagents_benchmark/run.py) for more detail on the agentic setup used, and see a comparison of using LLMs code agents compared to vanilla (spoilers: code agents works better).

<p align="center">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/smolagents/benchmark_code_agents.jpeg" alt="benchmark of different models on agentic workflows. Open model DeepSeek-R1 beats closed-source models." width=60% max-width=500px>
</p>

This comparison shows that open-source models can now take on the best closed models!

## Security

Security is a critical consideration when working with code-executing agents. Ensure you are using one of the sandboxed execution options that provide isolation from untrusted code.

**Warning:** `LocalPythonExecutor` provides best-effort mitigations only and is **not a security boundary**. Do not use it to run untrusted code.

For security policies, vulnerability reporting, and more information on secure agent execution, please see our [Security Policy](SECURITY.md).

## Contribute

Everyone is welcome to contribute, get started with our [contribution guide](https://github.com/huggingface/smolagents/blob/main/CONTRIBUTING.md).

## Cite smolagents

If you use `smolagents` in your publication, please cite it by using the following BibTeX entry.

```bibtex
@Misc{smolagents,
  title =        {`smolagents`: a smol library to build great agentic systems.},
  author =       {Aymeric Roucher and Albert Villanova del Moral and Thomas Wolf and Leandro von Werra and Erik Kaunismäki},
  howpublished = {\url{https://github.com/huggingface/smolagents}},
  year =         {2025}
}
```


================================================
FILE: SECURITY.md
================================================
# Security Policy

## Reporting a Vulnerability

To report a security vulnerability, please contact: security@huggingface.co

## Learning More About Security

To learn more about running agents more securely, please see the [Secure Code Execution tutorial](docs/source/en/tutorials/secure_code_execution.mdx) which covers sandboxing with E2B, Docker, and WebAssembly.

### Secure Execution Options

`smolagents` provides several options for secure code execution:

1. **E2B Sandbox**: Uses [E2B](https://e2b.dev/) to run code in a secure, isolated environment.

2. **Modal Sandbox**: Uses [Modal](https://modal.com/) to run code in a secure, isolated environment.

3. **Docker Sandbox**: Runs code in an isolated Docker container.

4. **WebAssembly Sandbox**: Executes Python code securely in a sandboxed WebAssembly environment using Pyodide and Deno's secure runtime.

We recommend using one of these sandboxed execution options when running untrusted code.


================================================
FILE: docs/README.md
================================================
<!---
Copyright 2024 The HuggingFace Team. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

# Generating the documentation

To generate the documentation, you have to build it. Several packages are necessary to build the doc.

First, you need to install the project itself by running the following command at the root of the code repository:

```bash
pip install -e .
```

You also need to install 2 extra packages:

```bash
# `hf-doc-builder` to build the docs
pip install git+https://github.com/huggingface/doc-builder@main
```

---
**NOTE**

You only need to generate the documentation to inspect it locally (if you're planning changes and want to
check how they look before committing for instance). You don't have to commit the built documentation.

---

## Building the documentation

Once you have setup the `doc-builder` and additional packages with the pip install command above,
you can generate the documentation by typing the following command:

```bash
doc-builder build smolagents docs/source/en/ --build_dir ~/tmp/test-build
```

You can adapt the `--build_dir` to set any temporary folder that you prefer. This command will create it and generate
the MDX files that will be rendered as the documentation on the main website. You can inspect them in your favorite
Markdown editor.

## Previewing the documentation

To preview the docs, run the following command:

```bash
doc-builder preview smolagents docs/source/en/
```

The docs will be viewable at [http://localhost:5173](http://localhost:5173). You can also preview the docs once you
have opened a PR. You will see a bot add a comment to a link where the documentation with your changes lives.

---
**NOTE**

The `preview` command only works with existing doc files. When you add a completely new file, you need to update
`_toctree.yml` & restart `preview` command (`ctrl-c` to stop it & call `doc-builder preview ...` again).

---

## Adding a new element to the navigation bar

Accepted files are Markdown (.md).

Create a file with its extension and put it in the source directory. You can then link it to the toc-tree by putting
the filename without the extension in the [`_toctree.yml`](https://github.com/huggingface/smolagents/blob/main/docs/source/_toctree.yml) file.

## Renaming section headers and moving sections

It helps to keep the old links working when renaming the section header and/or moving sections from one document to another. This is because the old links are likely to be used in Issues, Forums, and Social media and it'd make for a much more superior user experience if users reading those months later could still easily navigate to the originally intended information.

Therefore, we simply keep a little map of moved sections at the end of the document where the original section was. The key is to preserve the original anchor.

So if you renamed a section from: "Section A" to "Section B", then you can add at the end of the file:

```
Sections that were moved:

[ <a href="#section-b">Section A</a><a id="section-a"></a> ]
```
and of course, if you moved it to another file, then:

```
Sections that were moved:

[ <a href="../new-file#section-b">Section A</a><a id="section-a"></a> ]
```

Use the relative style to link to the new file so that the versioned docs continue to work.

For an example of a rich moved section set please see the very end of [the transformers Trainer doc](https://github.com/huggingface/transformers/blob/main/docs/source/en/main_classes/trainer.md).


## Writing Documentation - Specification

The `huggingface/smolagents` documentation follows the
[Google documentation](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html) style for docstrings,
although we can write them directly in Markdown.

### Adding a new tutorial

Adding a new tutorial or section is done in two steps:

- Add a new Markdown (.md) file under `./source`.
- Link that file in `./source/_toctree.yml` on the correct toc-tree.

Make sure to put your new file under the proper section. If you have a doubt, feel free to ask in a Github Issue or PR.

### Writing source documentation

Values that should be put in `code` should either be surrounded by backticks: \`like so\`. Note that argument names
and objects like True, None, or any strings should usually be put in `code`.

When mentioning a class, function, or method, it is recommended to use our syntax for internal links so that our tool
adds a link to its documentation with this syntax: \[\`XXXClass\`\] or \[\`function\`\]. This requires the class or
function to be in the main package.

If you want to create a link to some internal class or function, you need to
provide its path. For instance: \[\`utils.ModelOutput\`\]. This will be converted into a link with
`utils.ModelOutput` in the description. To get rid of the path and only keep the name of the object you are
linking to in the description, add a ~: \[\`~utils.ModelOutput\`\] will generate a link with `ModelOutput` in the description.

The same works for methods so you can either use \[\`XXXClass.method\`\] or \[~\`XXXClass.method\`\].

#### Defining arguments in a method

Arguments should be defined with the `Args:` (or `Arguments:` or `Parameters:`) prefix, followed by a line return and
an indentation. The argument should be followed by its type, with its shape if it is a tensor, a colon, and its
description:

```
    Args:
        n_layers (`int`): The number of layers of the model.
```

If the description is too long to fit in one line, another indentation is necessary before writing the description
after the argument.

Here's an example showcasing everything so far:

```
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary.

            Indices can be obtained using [`AlbertTokenizer`]. See [`~PreTrainedTokenizer.encode`] and
            [`~PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
```

For optional arguments or arguments with defaults we follow the following syntax: imagine we have a function with the
following signature:

```
def my_function(x: str = None, a: float = 1):
```

then its documentation should look like this:

```
    Args:
        x (`str`, *optional*):
            This argument controls ...
        a (`float`, *optional*, defaults to 1):
            This argument is used to ...
```

Note that we always omit the "defaults to \`None\`" when None is the default for any argument. Also note that even
if the first line describing your argument type and its default gets long, you can't break it on several lines. You can
however write as many lines as you want in the indented description (see the example above with `input_ids`).

#### Writing a multi-line code block

Multi-line code blocks can be useful for displaying examples. They are done between two lines of three backticks as usual in Markdown:


````
```
# first line of code
# second line
# etc
```
````

#### Writing a return block

The return block should be introduced with the `Returns:` prefix, followed by a line return and an indentation.
The first line should be the type of the return, followed by a line return. No need to indent further for the elements
building the return.

Here's an example of a single value return:

```
    Returns:
        `List[int]`: A list of integers in the range [0, 1] --- 1 for a special token, 0 for a sequence token.
```

Here's an example of a tuple return, comprising several objects:

```
    Returns:
        `tuple(torch.FloatTensor)` comprising various elements depending on the configuration ([`BertConfig`]) and inputs:
        - ** loss** (*optional*, returned when `masked_lm_labels` is provided) `torch.FloatTensor` of shape `(1,)` --
          Total loss is the sum of the masked language modeling loss and the next sequence prediction (classification) loss.
        - **prediction_scores** (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`) --
          Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
```

#### Adding an image

Due to the rapidly growing repository, it is important to make sure that no files that would significantly weigh down the repository are added. This includes images, videos, and other non-text files. We prefer to leverage a hf.co hosted `dataset` like
the ones hosted on [`hf-internal-testing`](https://huggingface.co/hf-internal-testing) in which to place these files and reference
them by URL. We recommend putting them in the following dataset: [huggingface/documentation-images](https://huggingface.co/datasets/huggingface/documentation-images).
If an external contribution, feel free to add the images to your PR and ask a Hugging Face member to migrate your images
to this dataset.

#### Writing documentation examples

The syntax for Example docstrings can look as follows:

```
    Example:

    ```python
    >>> from transformers import Wav2Vec2Processor, Wav2Vec2ForCTC
    >>> from datasets import load_dataset
    >>> import torch

    >>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation")
    >>> dataset = dataset.sort("id")
    >>> sampling_rate = dataset.features["audio"].sampling_rate

    >>> processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-base-960h")
    >>> model = Wav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-base-960h")

    >>> # audio file is decoded on the fly
    >>> inputs = processor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="pt")
    >>> with torch.no_grad():
    ...     logits = model(**inputs).logits
    >>> predicted_ids = torch.argmax(logits, dim=-1)

    >>> # transcribe speech
    >>> transcription = processor.batch_decode(predicted_ids)
    >>> transcription[0]
    'MISTER QUILTER IS THE APOSTLE OF THE MIDDLE CLASSES AND WE ARE GLAD TO WELCOME HIS GOSPEL'
    ```
```

The docstring should give a minimal, clear example of how the respective model
is to be used in inference and also include the expected (ideally sensible)
output.
Often, readers will try out the example before even going through the function
or class definitions. Therefore, it is of utmost importance that the example
works as expected.



================================================
FILE: docs/source/en/_config.py
================================================
# docstyle-ignore
INSTALL_CONTENT = """
# Installation
! pip install smolagents
# To install from source instead of the last release, comment the command above and uncomment the following one.
# ! pip install git+https://github.com/huggingface/smolagents.git
"""

notebook_first_cells = [{"type": "code", "content": INSTALL_CONTENT}]
black_avoid_patterns = {
    "{processor_class}": "FakeProcessorClass",
    "{model_class}": "FakeModelClass",
    "{object_class}": "FakeObjectClass",
}


================================================
FILE: docs/source/en/_toctree.yml
================================================
- title: Get started
  sections:
  - local: index
    title: Introduction
  - local: installation
    title: Installation options
  - local: guided_tour
    title: Guided tour
- title: Tutorials
  sections:
  - local: tutorials/building_good_agents
    title: ✨ Building good agents
  - local: tutorials/inspect_runs
    title: 📊 Inspect your agent runs using telemetry
  - local: tutorials/tools
    title: 🛠️ Tools - in-depth guide
  - local: tutorials/secure_code_execution
    title: 🛡️ Secure code execution
  - local: tutorials/memory
    title: 📚 Manage your agent's memory
- title: Conceptual guides
  sections:
  - local: conceptual_guides/intro_agents
    title: 🤖 What are agents?
  - local: conceptual_guides/react
    title: 🤔 How do Multi-step agents work?
- title: Examples
  sections:
  - local: examples/text_to_sql
    title: Self-correcting Text-to-SQL
  - local: examples/rag
    title: Master your knowledge base with agentic RAG
  - local: examples/multiagents
    title: Orchestrate a multi-agent system
  - local: examples/web_browser
    title: Build a web browser agent using vision models
  - local: examples/using_different_models
    title: Using different models
  - local: examples/plan_customization
    title: "Human-in-the-Loop: Customize agent plan interactively"
  - local: examples/async_agent
    title: Async Applications with Agents
- title: Reference
  sections:
  - title: Agent-related objects
    sections:
    - title: Agents
      local: reference/agents
    - title: Python executors
      local: reference/python_executors
  - local: reference/models
    title: Model-related objects
  - title: Tools
    sections:
    - title: Tool-related objects
      local: reference/tools
    - title: Built-in Tools
      local: reference/default_tools


================================================
FILE: docs/source/en/conceptual_guides/intro_agents.md
================================================
# What are agents? 🤔

## An introduction to agentic systems.

Any efficient system using AI will need to provide LLMs some kind of access to the real world: for instance the possibility to call a search tool to get external information, or to act on certain programs in order to solve a task. In other words, LLMs should have ***agency***. Agentic programs are the gateway to the outside world for LLMs.

> [!TIP]
> AI Agents are **programs where LLM outputs control the workflow**.

Any system leveraging LLMs will integrate the LLM outputs into code. The influence of the LLM's input on the code workflow is the level of agency of LLMs in the system.

Note that with this definition, "agent" is not a discrete, 0 or 1 definition: instead, "agency" evolves on a continuous spectrum, as you give more or less power to the LLM on your workflow.

See in the table below how agency can vary across systems:

| Agency Level | Description                                                     | Short name       | Example Code                                       |
| ------------ | --------------------------------------------------------------- | ---------------- | -------------------------------------------------- |
| ☆☆☆          | LLM output has no impact on program flow                        | Simple processor | `process_llm_output(llm_response)`                 |
| ★☆☆          | LLM output controls an if/else switch                           | Router           | `if llm_decision(): path_a() else: path_b()`       |
| ★★☆          | LLM output controls function execution                          | Tool call        | `run_function(llm_chosen_tool, llm_chosen_args)`   |
| ★★☆          | LLM output controls iteration and program continuation          | Multi-step Agent | `while llm_should_continue(): execute_next_step()` |
| ★★★          | One agentic workflow can start another agentic workflow         | Multi-Agent      | `if llm_trigger(): execute_agent()`                |
| ★★★          | LLM acts in code, can define its own tools / start other agents | Code Agents      | `def custom_tool(args): ...`                       |

The multi-step agent has this code structure:

```python
memory = [user_defined_task]
while llm_should_continue(memory): # this loop is the multi-step part
    action = llm_get_next_action(memory) # this is the tool-calling part
    observations = execute_action(action)
    memory += [action, observations]
```

This agentic system runs in a loop, executing a new action at each step (the action can involve calling some pre-determined *tools* that are just functions), until its observations make it apparent that a satisfactory state has been reached to solve the given task. Here’s an example of how a multi-step agent can solve a simple math question:

<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/Agent_ManimCE.gif"/>
</div>


## ✅ When to use agents / ⛔ when to avoid them

Agents are useful when you need an LLM to determine the workflow of an app. But they’re often overkill. The question is: do I really need flexibility in the workflow to efficiently solve the task at hand?
If the pre-determined workflow falls short too often, that means you need more flexibility.
Let's take an example: say you're making an app that handles customer requests on a surfing trip website.

You could know in advance that the requests will belong to either of 2 buckets (based on user choice), and you have a predefined workflow for each of these 2 cases.

1. Want some knowledge on the trips? ⇒ give them access to a search bar to search your knowledge base
2. Wants to talk to sales? ⇒ let them type in a contact form.

If that deterministic workflow fits all queries, by all means just code everything! This will give you a 100% reliable system with no risk of error introduced by letting unpredictable LLMs meddle in your workflow. For the sake of simplicity and robustness, it's advised to regularize towards not using any agentic behaviour. 

But what if the workflow can't be determined that well in advance? 

For instance, a user wants to ask: `"I can come on Monday, but I forgot my passport so risk being delayed to Wednesday, is it possible to take me and my stuff to surf on Tuesday morning, with a cancellation insurance?"` This question hinges on many factors, and probably none of the predetermined criteria above will suffice for this request.

If the pre-determined workflow falls short too often, that means you need more flexibility.

That is where an agentic setup helps.

In the above example, you could just make a multi-step agent that has access to a weather API for weather forecasts, Google Maps API to compute travel distance, an employee availability dashboard and a RAG system on your knowledge base.

Until recently, computer programs were restricted to pre-determined workflows, trying to handle complexity by piling up  if/else switches. They focused on extremely narrow tasks, like "compute the sum of these numbers" or "find the shortest path in this graph". But actually, most real-life tasks, like our trip example above, do not fit in pre-determined workflows. Agentic systems open up the vast world of real-world tasks to programs!

## Why `smolagents`?

For some low-level agentic use cases, like chains or routers, you can write all the code yourself. You'll be much better that way, since it will let you control and understand your system better.

But once you start going for more complicated behaviours like letting an LLM call a function (that's "tool calling") or letting an LLM run a while loop ("multi-step agent"), some abstractions become necessary:
- For tool calling, you need to parse the agent's output, so this output needs a predefined format like "Thought: I should call tool 'get_weather'. Action: get_weather(Paris).", that you parse with a predefined function, and system prompt given to the LLM should notify it about this format.
- For a multi-step agent where the LLM output determines the loop, you need to give a different prompt to the LLM based on what happened in the last loop iteration: so you need some kind of memory.

See? With these two examples, we already found the need for a few items to help us:

- Of course, an LLM that acts as the engine powering the system
- A list of tools that the agent can access
- A system prompt guiding the LLM on the agent logic: ReAct loop of Reflection -> Action -> Observation, available tools, tool calling format to use...
- A parser that extracts tool calls from the LLM output, in the format indicated by system prompt above.
- A memory

But wait, since we give room to LLMs in decisions, surely they will make mistakes: so we need error logging and retry mechanisms.

All these elements need tight coupling to make a well-functioning system. That's why we decided we needed to make basic building blocks to make all this stuff work together.

## Code agents

In a multi-step agent, at each step, the LLM can write an action, in the form of some calls to external tools. A common format (used by Anthropic, OpenAI, and many others) for writing these actions is generally different shades of "writing actions as a JSON of tools names and arguments to use, which you then parse to know which tool to execute and with which arguments".

[Multiple](https://huggingface.co/papers/2402.01030) [research](https://huggingface.co/papers/2411.01747) [papers](https://huggingface.co/papers/2401.00812) have shown that having the LLMs actions written as code snippets is a more natural and flexible way of writing them.

The reason for this simply that *we crafted our code languages specifically to express the actions performed by a computer*.
In other words, our agent is going to write programs in order to solve the user's issues : do you think their programming will be easier in blocks of Python or JSON?

The figure below, taken from [Executable Code Actions Elicit Better LLM Agents](https://huggingface.co/papers/2402.01030), illustrates some advantages of writing actions in code:

<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/code_vs_json_actions.png">

Writing actions in code rather than JSON-like snippets provides better:

- **Composability:** could you nest JSON actions within each other, or define a set of JSON actions to re-use later, the same way you could just define a python function?
- **Object management:** how do you store the output of an action like `generate_image` in JSON?
- **Generality:** code is built to express simply anything you can have a computer do.
- **Representation in LLM training data:** plenty of quality code actions are already included in LLMs’ training data which means they’re already trained for this!


================================================
FILE: docs/source/en/conceptual_guides/react.md
================================================
# How do multi-step agents work?

The ReAct framework ([Yao et al., 2022](https://huggingface.co/papers/2210.03629)) is currently the main approach to building agents.

The name is based on the concatenation of two words, "Reason" and "Act." Indeed, agents following this architecture will solve their task in as many steps as needed, each step consisting of a Reasoning step, then an Action step where it formulates tool calls that will bring it closer to solving the task at hand.

All agents in `smolagents` are based on singular `MultiStepAgent` class, which is an abstraction of ReAct framework.

On a basic level, this class performs actions on a cycle of following steps, where existing variables and knowledge is incorporated into the agent logs like below: 

Initialization: the system prompt is stored in a `SystemPromptStep`, and the user query is logged into a `TaskStep` .

While loop (ReAct loop):

- Use `agent.write_memory_to_messages()` to write the agent logs into a list of LLM-readable [chat messages](https://huggingface.co/docs/transformers/en/chat_templating).
- Send these messages to a `Model` object to get its completion. Parse the completion to get the action (a JSON blob for `ToolCallingAgent`, a code snippet for `CodeAgent`).
- Execute the action and logs result into memory (an `ActionStep`).
- At the end of each step, we run all callback functions defined in `agent.step_callbacks` .

Optionally, when planning is activated, a plan can be periodically revised and stored in a `PlanningStep` . This includes feeding facts about the task at hand to the memory.

For a `CodeAgent`, it looks like the figure below.

<div class="flex justify-center">
    <img
        src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/smolagents/codeagent_docs.png"
    />
</div>

Here is a video overview of how that works:

<div class="flex justify-center">
    <img
        class="block dark:hidden"
        src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/Agent_ManimCE.gif"
    />
    <img
        class="hidden dark:block"
        src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/Agent_ManimCE.gif"
    />
</div>

We implement two versions of agents:
- [`CodeAgent`] generates its tool calls as Python code snippets.
- [`ToolCallingAgent`] writes its tool calls as JSON, as is common in many frameworks. Depending on your needs, either approach can be used. For instance, web browsing often requires waiting after each page interaction, so JSON tool calls can fit well.

> [!TIP]
> Read [Open-source LLMs as LangChain Agents](https://huggingface.co/blog/open-source-llms-as-agents) blog post to learn more about multi-step agents.


================================================
FILE: docs/source/en/examples/async_agent.md
================================================
# Async Applications with Agents

This guide demonstrates how to integrate a synchronous agent from the `smolagents` library into an asynchronous Python web application using Starlette.
The example is designed to help users new to async Python and agent integration understand best practices for combining synchronous agent logic with async web servers.

## Overview

- **Starlette**: A lightweight ASGI framework for building asynchronous web applications in Python.
- **anyio.to_thread.run_sync**: Utility to run blocking (synchronous) code in a background thread, preventing it from blocking the async event loop.
- **CodeAgent**: An agent from the `smolagents` library capable of programmatically solving tasks.

## Why Use a Background Thread?

`CodeAgent.run()` executes Python code synchronously. If called directly in an async endpoint, it would block Starlette's event loop, reducing performance and scalability. By offloading this operation to a background thread with `anyio.to_thread.run_sync`, you keep the app responsive and efficient, even under high concurrency.

## Example Workflow

- The Starlette app exposes a `/run-agent` endpoint that accepts a JSON payload with a `task` string.
- When a request is received, the agent is run in a background thread using `anyio.to_thread.run_sync`.
- The result is returned as a JSON response.

## Building a Starlette App with a CodeAgent

### 1. Install Dependencies

```bash
pip install smolagents starlette anyio uvicorn
```

### 2. Application Code (`main.py`)

```python
import anyio.to_thread
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Route

from smolagents import CodeAgent, InferenceClientModel

agent = CodeAgent(
    model=InferenceClientModel(model_id="Qwen/Qwen3-Next-80B-A3B-Thinking"),
    tools=[],
)

async def run_agent(request: Request):
    data = await request.json()
    task = data.get("task", "")
    # Run the agent synchronously in a background thread
    result = await anyio.to_thread.run_sync(agent.run, task)
    return JSONResponse({"result": result})

app = Starlette(routes=[
    Route("/run-agent", run_agent, methods=["POST"]),
])
```

### 3. Run the App

```bash
uvicorn async_agent.main:app --reload
```

### 4. Test the Endpoint

```bash
curl -X POST http://localhost:8000/run-agent -H 'Content-Type: application/json' -d '{"task": "What is 2+2?"}'
```

**Expected Response:**

```json
{"result": "4"}
```

## Further Reading

- [Starlette Documentation](https://www.starlette.io/)
- [anyio Documentation](https://anyio.readthedocs.io/)

---

For the full code, see [`examples/async_agent`](https://github.com/huggingface/smolagents/tree/main/examples/async_agent).


================================================
FILE: docs/source/en/examples/multiagents.md
================================================
# Orchestrate a multi-agent system 🤖🤝🤖

[[open-in-colab]]

In this notebook we will make a **multi-agent web browser: an agentic system with several agents collaborating to solve problems using the web!**

It will be a simple hierarchy:

```
              +----------------+
              | Manager agent  |
              +----------------+
                       |
        _______________|______________
       |                              |
Code Interpreter            +------------------+
    tool                    | Web Search agent |
                            +------------------+
                               |            |
                        Web Search tool     |
                                   Visit webpage tool
```
Let's set up this system. 

Run the line below to install the required dependencies:

```py
!pip install 'smolagents[toolkit]' --upgrade -q
```

Let's login to HF in order to call Inference Providers:

```py
from huggingface_hub import login

login()
```

⚡️ Our agent will be powered by [Qwen/Qwen3-Next-80B-A3B-Thinking](https://huggingface.co/Qwen/Qwen3-Next-80B-A3B-Thinking) using `InferenceClientModel` class that uses HF's Inference API: the Inference API allows to quickly and easily run any OS model.

> [!TIP]
> Inference Providers give access to hundreds of models, powered by serverless inference partners. A list of supported providers can be found [here](https://huggingface.co/docs/inference-providers/index).

```py
model_id = "Qwen/Qwen3-Next-80B-A3B-Thinking"
```

## 🔍 Create a web search tool

For web browsing, we can already use our native [`WebSearchTool`] tool to provide a Google search equivalent.

But then we will also need to be able to peak into the page found by the `WebSearchTool`.
To do so, we could import the library's built-in `VisitWebpageTool`, but we will build it again to see how it's done.

So let's create our `VisitWebpageTool` tool from scratch using `markdownify`.

```py
import re
import requests
from markdownify import markdownify
from requests.exceptions import RequestException
from smolagents import tool


@tool
def visit_webpage(url: str) -> str:
    """Visits a webpage at the given URL and returns its content as a markdown string.

    Args:
        url: The URL of the webpage to visit.

    Returns:
        The content of the webpage converted to Markdown, or an error message if the request fails.
    """
    try:
        # Send a GET request to the URL
        response = requests.get(url)
        response.raise_for_status()  # Raise an exception for bad status codes

        # Convert the HTML content to Markdown
        markdown_content = markdownify(response.text).strip()

        # Remove multiple line breaks
        markdown_content = re.sub(r"\n{3,}", "\n\n", markdown_content)

        return markdown_content

    except RequestException as e:
        return f"Error fetching the webpage: {str(e)}"
    except Exception as e:
        return f"An unexpected error occurred: {str(e)}"
```

Ok, now let's initialize and test our tool!

```py
print(visit_webpage("https://en.wikipedia.org/wiki/Hugging_Face")[:500])
```

## Build our multi-agent system 🤖🤝🤖

Now that we have all the tools `search` and `visit_webpage`, we can use them to create the web agent.

Which configuration to choose for this agent?
- Web browsing is a single-timeline task that does not require parallel tool calls, so JSON tool calling works well for that. We thus choose a `ToolCallingAgent`.
- Also, since sometimes web search requires exploring many pages before finding the correct answer, we prefer to increase the number of `max_steps` to 10.

```py
from smolagents import (
    CodeAgent,
    ToolCallingAgent,
    InferenceClientModel,
    WebSearchTool,
)

model = InferenceClientModel(model_id=model_id)

web_agent = ToolCallingAgent(
    tools=[WebSearchTool(), visit_webpage],
    model=model,
    max_steps=10,
    name="web_search_agent",
    description="Runs web searches for you.",
)
```

Note that we gave this agent attributes `name` and `description`, mandatory attributes to make this agent callable by its manager agent.

Then we create a manager agent, and upon initialization we pass our managed agent to it in its `managed_agents` argument.

Since this agent is the one tasked with the planning and thinking, advanced reasoning will be beneficial, so a `CodeAgent` will work well.

Also, we want to ask a question that involves the current year and does additional data calculations: so let us add `additional_authorized_imports=["time", "numpy", "pandas"]`, just in case the agent needs these packages.

```py
manager_agent = CodeAgent(
    tools=[],
    model=model,
    managed_agents=[web_agent],
    additional_authorized_imports=["time", "numpy", "pandas"],
)
```

That's all! Now let's run our system! We select a question that requires both some calculation and research:

```py
answer = manager_agent.run("If LLM training continues to scale up at the current rhythm until 2030, what would be the electric power in GW required to power the biggest training runs by 2030? What would that correspond to, compared to some countries? Please provide a source for any numbers used.")
```

We get this report as the answer:
```
Based on current growth projections and energy consumption estimates, if LLM trainings continue to scale up at the 
current rhythm until 2030:

1. The electric power required to power the biggest training runs by 2030 would be approximately 303.74 GW, which 
translates to about 2,660,762 GWh/year.

2. Comparing this to countries' electricity consumption:
   - It would be equivalent to about 34% of China's total electricity consumption.
   - It would exceed the total electricity consumption of India (184%), Russia (267%), and Japan (291%).
   - It would be nearly 9 times the electricity consumption of countries like Italy or Mexico.

3. Source of numbers:
   - The initial estimate of 5 GW for future LLM training comes from AWS CEO Matt Garman.
   - The growth projection used a CAGR of 79.80% from market research by Springs.
   - Country electricity consumption data is from the U.S. Energy Information Administration, primarily for the year 
2021.
```

Seems like we'll need some sizeable powerplants if the [scaling hypothesis](https://gwern.net/scaling-hypothesis) continues to hold true.

Our agents managed to efficiently collaborate towards solving the task! ✅

💡 You can easily extend this orchestration to more agents: one does the code execution, one the web search, one handles file loadings...


================================================
FILE: docs/source/en/examples/plan_customization.md
================================================
# Human-in-the-Loop: Customize Agent Plan Interactively

This page demonstrates advanced usage of the smolagents library, with a special focus on **Human-in-the-Loop (HITL)** approaches for interactive plan creation, user-driven plan modification, and memory preservation in agentic workflows.
The example is based on the code in `examples/plan_customization/plan_customization.py`.

## Overview

This example teaches you how to implement Human-in-the-Loop strategies to:

- Interrupt agent execution after a plan is created (using step callbacks)
- Allow users to review and modify the agent's plan before execution (Human-in-the-Loop)
- Resume execution while preserving the agent's memory
- Dynamically update plans based on user feedback, keeping the human in control

## Key Concepts

### Step Callbacks for Plan Interruption

The agent is configured to pause after creating a plan. This is achieved by registering a step callback for the `PlanningStep`:

```python
agent = CodeAgent(
    model=InferenceClientModel(),
    tools=[DuckDuckGoSearchTool()],
    planning_interval=5,  # Plan every 5 steps
    step_callbacks={PlanningStep: interrupt_after_plan},
    max_steps=10,
    verbosity_level=1
)
```

### Human-in-the-Loop: Interactive Plan Review and Modification

When the agent creates a plan, the callback displays it and prompts the human user to:

1. Approve the plan
2. Modify the plan
3. Cancel execution

Example interaction:

```
============================================================
🤖 AGENT PLAN CREATED
============================================================
1. Search for recent AI developments
2. Analyze the top results
3. Summarize the 3 most significant breakthroughs
4. Include sources for each breakthrough
============================================================

Choose an option:
1. Approve plan
2. Modify plan
3. Cancel
Your choice (1-3):
```

This Human-in-the-Loop step enables a human to intervene and review or modify the plan before execution continues, and ensures that the agent's actions align with human intent.

If the user chooses to modify, they can edit the plan directly. The updated plan is then used for subsequent execution steps.

### Memory Preservation and Resuming Execution

By running the agent with `reset=False`, all previous steps and memory are preserved. This allows you to resume execution after an interruption or plan modification:

```python
# First run (may be interrupted)
agent.run(task, reset=True)

# Resume with preserved memory
agent.run(task, reset=False)
```

### Inspecting Agent Memory

You can inspect the agent's memory to see all steps taken so far:

```python
print(f"Current memory contains {len(agent.memory.steps)} steps:")
for i, step in enumerate(agent.memory.steps):
    step_type = type(step).__name__
    print(f"  {i+1}. {step_type}")
```

## Example Human-in-the-Loop Workflow

1. Agent starts with a complex task
2. Planning step is created and execution pauses for human review
3. Human reviews and optionally modifies the plan (Human-in-the-Loop)
4. Execution resumes with the approved/modified plan
5. All steps are preserved for future runs, maintaining transparency and control

## Error Handling

The example includes error handling for:
- User cancellation
- Plan modification errors
- Resume execution failures

## Requirements

- smolagents library
- DuckDuckGoSearchTool (included with smolagents)
- InferenceClientModel (requires HuggingFace API token)

## Educational Value

This example demonstrates:
- Step callback implementation for custom agent behavior
- Memory management in multi-step agents
- User interaction patterns in agentic systems
- Plan modification techniques for dynamic agent control
- Error handling in interactive agent systems

---

For the full code, see [`examples/plan_customization`](https://github.com/huggingface/smolagents/tree/main/examples/plan_customization).


================================================
FILE: docs/source/en/examples/rag.md
================================================
# Agentic RAG

[[open-in-colab]]

## Introduction to Retrieval-Augmented Generation (RAG)

Retrieval-Augmented Generation (RAG) combines the power of large language models with external knowledge retrieval to produce more accurate, factual, and contextually relevant responses. At its core, RAG is about "using an LLM to answer a user query, but basing the answer on information retrieved from a knowledge base."

### Why Use RAG?

RAG offers several significant advantages over using vanilla or fine-tuned LLMs:

1. **Factual Grounding**: Reduces hallucinations by anchoring responses in retrieved facts
2. **Domain Specialization**: Provides domain-specific knowledge without model retraining
3. **Knowledge Recency**: Allows access to information beyond the model's training cutoff
4. **Transparency**: Enables citation of sources for generated content
5. **Control**: Offers fine-grained control over what information the model can access

### Limitations of Traditional RAG

Despite its benefits, traditional RAG approaches face several challenges:

- **Single Retrieval Step**: If the initial retrieval results are poor, the final generation will suffer
- **Query-Document Mismatch**: User queries (often questions) may not match well with documents containing answers (often statements)
- **Limited Reasoning**: Simple RAG pipelines don't allow for multi-step reasoning or query refinement
- **Context Window Constraints**: Retrieved documents must fit within the model's context window

## Agentic RAG: A More Powerful Approach

We can overcome these limitations by implementing an **Agentic RAG** system - essentially an agent equipped with retrieval capabilities. This approach transforms RAG from a rigid pipeline into an interactive, reasoning-driven process.

### Key Benefits of Agentic RAG

An agent with retrieval tools can:

1. ✅ **Formulate optimized queries**: The agent can transform user questions into retrieval-friendly queries
2. ✅ **Perform multiple retrievals**: The agent can retrieve information iteratively as needed
3. ✅ **Reason over retrieved content**: The agent can analyze, synthesize, and draw conclusions from multiple sources
4. ✅ **Self-critique and refine**: The agent can evaluate retrieval results and adjust its approach

This approach naturally implements advanced RAG techniques:
- **Hypothetical Document Embedding (HyDE)**: Instead of using the user query directly, the agent formulates retrieval-optimized queries ([paper reference](https://huggingface.co/papers/2212.10496))
- **Self-Query Refinement**: The agent can analyze initial results and perform follow-up retrievals with refined queries ([technique reference](https://docs.llamaindex.ai/en/stable/examples/evaluation/RetryQuery/))

## Building an Agentic RAG System

Let's build a complete Agentic RAG system step by step. We'll create an agent that can answer questions about the Hugging Face Transformers library by retrieving information from its documentation.

You can follow along with the code snippets below, or check out the full example in the smolagents GitHub repository: [examples/rag.py](https://github.com/huggingface/smolagents/blob/main/examples/rag.py).

### Step 1: Install Required Dependencies

First, we need to install the necessary packages:

```bash
pip install smolagents pandas langchain langchain-community sentence-transformers datasets python-dotenv rank_bm25 --upgrade
```

If you plan to use Hugging Face's Inference API, you'll need to set up your API token:

```python
# Load environment variables (including HF_TOKEN)
from dotenv import load_dotenv
load_dotenv()
```

### Step 2: Prepare the Knowledge Base

We'll use a dataset containing Hugging Face documentation and prepare it for retrieval:

```python
import datasets
from langchain.docstore.document import Document
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.retrievers import BM25Retriever

# Load the Hugging Face documentation dataset
knowledge_base = datasets.load_dataset("m-ric/huggingface_doc", split="train")

# Filter to include only Transformers documentation
knowledge_base = knowledge_base.filter(lambda row: row["source"].startswith("huggingface/transformers"))

# Convert dataset entries to Document objects with metadata
source_docs = [
    Document(page_content=doc["text"], metadata={"source": doc["source"].split("/")[1]})
    for doc in knowledge_base
]

# Split documents into smaller chunks for better retrieval
text_splitter = RecursiveCharacterTextSplitter(
    chunk_size=500,  # Characters per chunk
    chunk_overlap=50,  # Overlap between chunks to maintain context
    add_start_index=True,
    strip_whitespace=True,
    separators=["\n\n", "\n", ".", " ", ""],  # Priority order for splitting
)
docs_processed = text_splitter.split_documents(source_docs)

print(f"Knowledge base prepared with {len(docs_processed)} document chunks")
```

### Step 3: Create a Retriever Tool

Now we'll create a custom tool that our agent can use to retrieve information from the knowledge base:

```python
from smolagents import Tool

class RetrieverTool(Tool):
    name = "retriever"
    description = "Uses semantic search to retrieve the parts of transformers documentation that could be most relevant to answer your query."
    inputs = {
        "query": {
            "type": "string",
            "description": "The query to perform. This should be semantically close to your target documents. Use the affirmative form rather than a question.",
        }
    }
    output_type = "string"

    def __init__(self, docs, **kwargs):
        super().__init__(**kwargs)
        # Initialize the retriever with our processed documents
        self.retriever = BM25Retriever.from_documents(
            docs, k=10  # Return top 10 most relevant documents
        )

    def forward(self, query: str) -> str:
        """Execute the retrieval based on the provided query."""
        assert isinstance(query, str), "Your search query must be a string"

        # Retrieve relevant documents
        docs = self.retriever.invoke(query)

        # Format the retrieved documents for readability
        return "\nRetrieved documents:\n" + "".join(
            [
                f"\n\n===== Document {str(i)} =====\n" + doc.page_content
                for i, doc in enumerate(docs)
            ]
        )

# Initialize our retriever tool with the processed documents
retriever_tool = RetrieverTool(docs_processed)
```

> [!TIP]
> We're using BM25, a lexical retrieval method, for simplicity and speed. For production systems, you might want to use semantic search with embeddings for better retrieval quality. Check the [MTEB Leaderboard](https://huggingface.co/spaces/mteb/leaderboard) for high-quality embedding models.

### Step 4: Create an Advanced Retrieval Agent

Now we'll create an agent that can use our retriever tool to answer questions:

```python
from smolagents import InferenceClientModel, CodeAgent

# Initialize the agent with our retriever tool
agent = CodeAgent(
    tools=[retriever_tool],  # List of tools available to the agent
    model=InferenceClientModel(),  # Default model "Qwen/Qwen3-Next-80B-A3B-Thinking"
    max_steps=4,  # Limit the number of reasoning steps
    verbosity_level=2,  # Show detailed agent reasoning
)

# To use a specific model, you can specify it like this:
# model=InferenceClientModel(model_id="meta-llama/Llama-3.3-70B-Instruct")
```

> [!TIP]
> Inference Providers give access to hundreds of models, powered by serverless inference partners. A list of supported providers can be found [here](https://huggingface.co/docs/inference-providers/index).

### Step 5: Run the Agent to Answer Questions

Let's use our agent to answer a question about Transformers:

```python
# Ask a question that requires retrieving information
question = "For a transformers model training, which is slower, the forward or the backward pass?"

# Run the agent to get an answer
agent_output = agent.run(question)

# Display the final answer
print("\nFinal answer:")
print(agent_output)
```

## Practical Applications of Agentic RAG

Agentic RAG systems can be applied to various use cases:

1. **Technical Documentation Assistance**: Help users navigate complex technical documentation
2. **Research Paper Analysis**: Extract and synthesize information from scientific papers
3. **Legal Document Review**: Find relevant precedents and clauses in legal documents
4. **Customer Support**: Answer questions based on product documentation and knowledge bases
5. **Educational Tutoring**: Provide explanations based on textbooks and learning materials

## Conclusion

Agentic RAG represents a significant advancement over traditional RAG pipelines. By combining the reasoning capabilities of LLM agents with the factual grounding of retrieval systems, we can build more powerful, flexible, and accurate information systems.

The approach we've demonstrated:
- Overcomes the limitations of single-step retrieval
- Enables more natural interactions with knowledge bases
- Provides a framework for continuous improvement through self-critique and query refinement

As you build your own Agentic RAG systems, consider experimenting with different retrieval methods, agent architectures, and knowledge sources to find the optimal configuration for your specific use case.


================================================
FILE: docs/source/en/examples/text_to_sql.md
================================================
# Text-to-SQL

[[open-in-colab]]

In this tutorial, we’ll see how to implement an agent that leverages SQL using `smolagents`.

> Let's start with the golden question: why not keep it simple and use a standard text-to-SQL pipeline?

A standard text-to-sql pipeline is brittle, since the generated SQL query can be incorrect. Even worse, the query could be incorrect, but not raise an error, instead giving some incorrect/useless outputs without raising an alarm.

👉 Instead, an agent system is able to critically inspect outputs and decide if the query needs to be changed or not, thus giving it a huge performance boost.

Let’s build this agent! 💪

Run the line below to install required dependencies:
```bash
!pip install smolagents python-dotenv sqlalchemy --upgrade -q
```
To call Inference Providers, you will need a valid token as your environment variable `HF_TOKEN`.
We use python-dotenv to load it.
```py
from dotenv import load_dotenv
load_dotenv()
```

Then, we setup the SQL environment:
```py
from sqlalchemy import (
    create_engine,
    MetaData,
    Table,
    Column,
    String,
    Integer,
    Float,
    insert,
    inspect,
    text,
)

engine = create_engine("sqlite:///:memory:")
metadata_obj = MetaData()

def insert_rows_into_table(rows, table, engine=engine):
    for row in rows:
        stmt = insert(table).values(**row)
        with engine.begin() as connection:
            connection.execute(stmt)

table_name = "receipts"
receipts = Table(
    table_name,
    metadata_obj,
    Column("receipt_id", Integer, primary_key=True),
    Column("customer_name", String(16), primary_key=True),
    Column("price", Float),
    Column("tip", Float),
)
metadata_obj.create_all(engine)

rows = [
    {"receipt_id": 1, "customer_name": "Alan Payne", "price": 12.06, "tip": 1.20},
    {"receipt_id": 2, "customer_name": "Alex Mason", "price": 23.86, "tip": 0.24},
    {"receipt_id": 3, "customer_name": "Woodrow Wilson", "price": 53.43, "tip": 5.43},
    {"receipt_id": 4, "customer_name": "Margaret James", "price": 21.11, "tip": 1.00},
]
insert_rows_into_table(rows, receipts)
```

### Build our agent

Now let’s make our SQL table retrievable by a tool.

The tool’s description attribute will be embedded in the LLM’s prompt by the agent system: it gives the LLM information about how to use the tool. This is where we want to describe the SQL table.

```py
inspector = inspect(engine)
columns_info = [(col["name"], col["type"]) for col in inspector.get_columns("receipts")]

table_description = "Columns:\n" + "\n".join([f"  - {name}: {col_type}" for name, col_type in columns_info])
print(table_description)
```

```text
Columns:
  - receipt_id: INTEGER
  - customer_name: VARCHAR(16)
  - price: FLOAT
  - tip: FLOAT
```

Now let’s build our tool. It needs the following: (read [the tool doc](../tutorials/tools) for more detail)
- A docstring with an `Args:` part listing arguments.
- Type hints on both inputs and output.

```py
from smolagents import tool

@tool
def sql_engine(query: str) -> str:
    """
    Allows you to perform SQL queries on the table. Returns a string representation of the result.
    The table is named 'receipts'. Its description is as follows:
        Columns:
        - receipt_id: INTEGER
        - customer_name: VARCHAR(16)
        - price: FLOAT
        - tip: FLOAT

    Args:
        query: The query to perform. This should be correct SQL.
    """
    output = ""
    with engine.connect() as con:
        rows = con.execute(text(query))
        for row in rows:
            output += "\n" + str(row)
    return output
```

Now let us create an agent that leverages this tool.

We use the `CodeAgent`, which is smolagents’ main agent class: an agent that writes actions in code and can iterate on previous output according to the ReAct framework.

The model is the LLM that powers the agent system. `InferenceClientModel` allows you to call LLMs using HF’s Inference API, either via Serverless or Dedicated endpoint, but you could also use any proprietary API.

```py
from smolagents import CodeAgent, InferenceClientModel

agent = CodeAgent(
    tools=[sql_engine],
    model=InferenceClientModel(model_id="meta-llama/Llama-3.1-8B-Instruct"),
)
agent.run("Can you give me the name of the client who got the most expensive receipt?")
```

### Level 2: Table joins

Now let’s make it more challenging! We want our agent to handle joins across multiple tables.

So let’s make a second table recording the names of waiters for each receipt_id!

```py
table_name = "waiters"
waiters = Table(
    table_name,
    metadata_obj,
    Column("receipt_id", Integer, primary_key=True),
    Column("waiter_name", String(16), primary_key=True),
)
metadata_obj.create_all(engine)

rows = [
    {"receipt_id": 1, "waiter_name": "Corey Johnson"},
    {"receipt_id": 2, "waiter_name": "Michael Watts"},
    {"receipt_id": 3, "waiter_name": "Michael Watts"},
    {"receipt_id": 4, "waiter_name": "Margaret James"},
]
insert_rows_into_table(rows, waiters)
```
Since we changed the table, we update the `SQLExecutorTool` with this table’s description to let the LLM properly leverage information from this table.

```py
updated_description = """Allows you to perform SQL queries on the table. Beware that this tool's output is a string representation of the execution output.
It can use the following tables:"""

inspector = inspect(engine)
for table in ["receipts", "waiters"]:
    columns_info = [(col["name"], col["type"]) for col in inspector.get_columns(table)]

    table_description = f"Table '{table}':\n"

    table_description += "Columns:\n" + "\n".join([f"  - {name}: {col_type}" for name, col_type in columns_info])
    updated_description += "\n\n" + table_description

print(updated_description)
```
Since this request is a bit harder than the previous one, we’ll switch the LLM engine to use the more powerful [Qwen/Qwen3-Next-80B-A3B-Thinking](https://huggingface.co/Qwen/Qwen3-Next-80B-A3B-Thinking)!

```py
sql_engine.description = updated_description

agent = CodeAgent(
    tools=[sql_engine],
    model=InferenceClientModel(model_id="Qwen/Qwen3-Next-80B-A3B-Thinking"),
)

agent.run("Which waiter got more total money from tips?")
```
It directly works! The setup was surprisingly simple, wasn’t it?

This example is done! We've touched upon these concepts:
- Building new tools.
- Updating a tool's description.
- Switching to a stronger LLM helps agent reasoning.

✅ Now you can go build this text-to-SQL system you’ve always dreamt of! ✨


================================================
FILE: docs/source/en/examples/using_different_models.md
================================================
# Using different models

[[open-in-colab]]

`smolagents` provides a flexible framework that allows you to use various language models from different providers.
This guide will show you how to use different model types with your agents.

## Available model types

`smolagents` supports several model types out of the box:
1. [`InferenceClientModel`]: Uses Hugging Face's Inference API to access models
2. [`TransformersModel`]: Runs models locally using the Transformers library
3. [`VLLMModel`]: Uses vLLM for fast inference with optimized serving
4. [`MLXModel`]: Optimized for Apple Silicon devices using MLX
5. [`LiteLLMModel`]: Provides access to hundreds of LLMs through LiteLLM
6. [`LiteLLMRouterModel`]: Distributes requests among multiple models
7. [`OpenAIModel`]: Provides access to any provider that implements an OpenAI-compatible API
8. [`AzureOpenAIModel`]: Uses Azure's OpenAI service
9. [`AmazonBedrockModel`]: Connects to AWS Bedrock's API

All model classes support passing additional keyword arguments (like `temperature`, `max_tokens`, `top_p`, etc.) directly at instantiation time.
These parameters are automatically forwarded to the underlying model's completion calls, allowing you to configure model behavior such as creativity, response length, and sampling strategies.

## Using Google Gemini Models

As explained in the Google Gemini API documentation (https://ai.google.dev/gemini-api/docs/openai),
Google provides an OpenAI-compatible API for Gemini models, allowing you to use the [`OpenAIModel`]
with Gemini models by setting the appropriate base URL.

First, install the required dependencies:
```bash
pip install 'smolagents[openai]'
```

Then, [get a Gemini API key](https://ai.google.dev/gemini-api/docs/api-key) and set it in your code:
```python
GEMINI_API_KEY = <YOUR-GEMINI-API-KEY>
```

Now, you can initialize the Gemini model using the `OpenAIModel` class
and setting the `api_base` parameter to the Gemini API base URL:
```python
from smolagents import OpenAIModel

model = OpenAIModel(
    model_id="gemini-2.0-flash",
    # Google Gemini OpenAI-compatible API base URL
    api_base="https://generativelanguage.googleapis.com/v1beta/openai/",
    api_key=GEMINI_API_KEY,
)
```

## Using OpenRouter Models

OpenRouter provides access to a wide variety of language models through a unified OpenAI-compatible API.
You can use the [`OpenAIModel`] to connect to OpenRouter by setting the appropriate base URL.

First, install the required dependencies:
```bash
pip install 'smolagents[openai]'
```

Then, [get an OpenRouter API key](https://openrouter.ai/keys) and set it in your code:
```python
OPENROUTER_API_KEY = <YOUR-OPENROUTER-API-KEY>
```

Now, you can initialize any model available on OpenRouter using the `OpenAIModel` class:
```python
from smolagents import OpenAIModel

model = OpenAIModel(
    # You can use any model ID available on OpenRouter
    model_id="openai/gpt-4o",
    # OpenRouter API base URL
    api_base="https://openrouter.ai/api/v1",
    api_key=OPENROUTER_API_KEY,
)
```

## Using xAI's Grok Models

xAI's Grok models can be accessed through [`LiteLLMModel`].

Some models (such as "grok-4" and "grok-3-mini") don't support the `stop` parameter, so you'll need to use
`REMOVE_PARAMETER` to exclude it from API calls.

First, install the required dependencies:
```bash
pip install smolagents[litellm]
```

Then, [get an xAI API key](https://console.x.ai/) and set it in your code:
```python
XAI_API_KEY = <YOUR-XAI-API-KEY>
```

Now, you can initialize Grok models using the `LiteLLMModel` class and remove the `stop` parameter if applicable:
```python
from smolagents import LiteLLMModel, REMOVE_PARAMETER

# Using Grok-4
model = LiteLLMModel(
    model_id="xai/grok-4",
    api_key=XAI_API_KEY,
    stop=REMOVE_PARAMETER,  # Remove stop parameter as grok-4 model doesn't support it
    temperature=0.7
)

# Or using Grok-3-mini
model_mini = LiteLLMModel(
    model_id="xai/grok-3-mini",
    api_key=XAI_API_KEY,
    stop=REMOVE_PARAMETER,  # Remove stop parameter as grok-3-mini model doesn't support it
    max_tokens=1000
)
```


================================================
FILE: docs/source/en/examples/web_browser.md
================================================
# Web Browser Automation with Agents 🤖🌐

[[open-in-colab]]

In this notebook, we'll create an **agent-powered web browser automation system**! This system can navigate websites, interact with elements, and extract information automatically.

The agent will be able to:

- [x] Navigate to web pages
- [x] Click on elements
- [x] Search within pages
- [x] Handle popups and modals
- [x] Extract information

Let's set up this system step by step!

First, run these lines to install the required dependencies:

```bash
pip install smolagents selenium helium pillow -q
```

Let's import our required libraries and set up environment variables:

```python
from io import BytesIO
from time import sleep

import helium
from dotenv import load_dotenv
from PIL import Image
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

from smolagents import CodeAgent, tool
from smolagents.agents import ActionStep

# Load environment variables
load_dotenv()
```

Now let's create our core browser interaction tools that will allow our agent to navigate and interact with web pages:

```python
@tool
def search_item_ctrl_f(text: str, nth_result: int = 1) -> str:
    """
    Searches for text on the current page via Ctrl + F and jumps to the nth occurrence.
    Args:
        text: The text to search for
        nth_result: Which occurrence to jump to (default: 1)
    """
    elements = driver.find_elements(By.XPATH, f"//*[contains(text(), '{text}')]")
    if nth_result > len(elements):
        raise Exception(f"Match n°{nth_result} not found (only {len(elements)} matches found)")
    result = f"Found {len(elements)} matches for '{text}'."
    elem = elements[nth_result - 1]
    driver.execute_script("arguments[0].scrollIntoView(true);", elem)
    result += f"Focused on element {nth_result} of {len(elements)}"
    return result

@tool
def go_back() -> None:
    """Goes back to previous page."""
    driver.back()

@tool
def close_popups() -> str:
    """
    Closes any visible modal or pop-up on the page. Use this to dismiss pop-up windows!
    This does not work on cookie consent banners.
    """
    webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform()
```

Let's set up our browser with Chrome and configure screenshot capabilities:

```python
# Configure Chrome options
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--force-device-scale-factor=1")
chrome_options.add_argument("--window-size=1000,1350")
chrome_options.add_argument("--disable-pdf-viewer")
chrome_options.add_argument("--window-position=0,0")

# Initialize the browser
driver = helium.start_chrome(headless=False, options=chrome_options)

# Set up screenshot callback
def save_screenshot(memory_step: ActionStep, agent: CodeAgent) -> None:
    sleep(1.0)  # Let JavaScript animations happen before taking the screenshot
    driver = helium.get_driver()
    current_step = memory_step.step_number
    if driver is not None:
        for previous_memory_step in agent.memory.steps:  # Remove previous screenshots for lean processing
            if isinstance(previous_memory_step, ActionStep) and previous_memory_step.step_number <= current_step - 2:
                previous_memory_step.observations_images = None
        png_bytes = driver.get_screenshot_as_png()
        image = Image.open(BytesIO(png_bytes))
        print(f"Captured a browser screenshot: {image.size} pixels")
        memory_step.observations_images = [image.copy()]  # Create a copy to ensure it persists

    # Update observations with current URL
    url_info = f"Current url: {driver.current_url}"
    memory_step.observations = (
        url_info if memory_step.observations is None else memory_step.observations + "\n" + url_info
    )
```

Now let's create our web automation agent:

```python
from smolagents import InferenceClientModel

# Initialize the model
model_id = "Qwen/Qwen2-VL-72B-Instruct"  # You can change this to your preferred VLM model
model = InferenceClientModel(model_id=model_id)

# Create the agent
agent = CodeAgent(
    tools=[go_back, close_popups, search_item_ctrl_f],
    model=model,
    additional_authorized_imports=["helium"],
    step_callbacks=[save_screenshot],
    max_steps=20,
    verbosity_level=2,
)

# Import helium for the agent
agent.python_executor("from helium import *", agent.state)
```

The agent needs instructions on how to use Helium for web automation. Here are the instructions we'll provide:

```python
helium_instructions = """
You can use helium to access websites. Don't bother about the helium driver, it's already managed.
We've already ran "from helium import *"
Then you can go to pages!
Code:
```py
go_to('github.com/trending')
```<end_code>

You can directly click clickable elements by inputting the text that appears on them.
Code:
```py
click("Top products")
```<end_code>

If it's a link:
Code:
```py
click(Link("Top products"))
```<end_code>

If you try to interact with an element and it's not found, you'll get a LookupError.
In general stop your action after each button click to see what happens on your screenshot.
Never try to login in a page.

To scroll up or down, use scroll_down or scroll_up with as an argument the number of pixels to scroll from.
Code:
```py
scroll_down(num_pixels=1200) # This will scroll one viewport down
```<end_code>

When you have pop-ups with a cross icon to close, don't try to click the close icon by finding its element or targeting an 'X' element (this most often fails).
Just use your built-in tool `close_popups` to close them:
Code:
```py
close_popups()
```<end_code>

You can use .exists() to check for the existence of an element. For example:
Code:
```py
if Text('Accept cookies?').exists():
    click('I accept')
```<end_code>
"""
```

Now we can run our agent with a task! Let's try finding information on Wikipedia:

```python
search_request = """
Please navigate to https://en.wikipedia.org/wiki/Chicago and give me a sentence containing the word "1992" that mentions a construction accident.
"""

agent_output = agent.run(search_request + helium_instructions)
print("Final output:")
print(agent_output)
```

You can run different tasks by modifying the request. For example, here's for me to know if I should work harder:

```python
github_request = """
I'm trying to find how hard I have to work to get a repo in github.com/trending.
Can you navigate to the profile for the top author of the top trending repo, and give me their total number of commits over the last year?
"""

agent_output = agent.run(github_request + helium_instructions)
print("Final output:")
print(agent_output)
```

The system is particularly effective for tasks like:
- Data extraction from websites
- Web research automation
- UI testing and verification
- Content monitoring

================================================
FILE: docs/source/en/guided_tour.md
================================================
# Agents - Guided tour

[[open-in-colab]]

In this guided visit, you will learn how to build an agent, how to run it, and how to customize it to make it work better for your use-case.

## Choosing an agent type: CodeAgent or ToolCallingAgent

`smolagents` comes with two agent classes: [`CodeAgent`] and [`ToolCallingAgent`], which represent two different paradigms for how agents interact with tools.
The key difference lies in how actions are specified and executed: code generation vs structured tool calling.

- [`CodeAgent`] generates tool calls as Python code snippets.
  - The code is executed either locally (potentially unsecure) or in a secure sandbox.
  - Tools are exposed as Python functions (via bindings).
  - Example of tool call:
    ```py
    result = search_docs("What is the capital of France?")
    print(result)
    ```
  - Strengths:
    - Highly expressive: Allows for complex logic and control flow and can combine tools, loop, transform, reason.
    - Flexible: No need to predefine every possible action, can dynamically generate new actions/tools.
    - Emergent reasoning: Ideal for multi-step problems or dynamic logic.
  - Limitations
    - Risk of errors: Must handle syntax errors, exceptions.
    - Less predictable: More prone to unexpected or unsafe outputs.
    - Requires secure execution environment.

- [`ToolCallingAgent`] writes tool calls as structured JSON.
  - This is the common format used in many frameworks (OpenAI API), allowing for structured tool interactions without code execution.
  - Tools are defined with a JSON schema: name, description, parameter types, etc.
  - Example of tool call:
    ```json
    {
      "tool_call": {
        "name": "search_docs",
        "arguments": {
          "query": "What is the capital of France?"
        }
      }
    }
    ```
  - Strengths:
    - Reliable: Less prone to hallucination, outputs are structured and validated.
    - Safe: Arguments are strictly validated, no risk of arbitrary code running.
    - Interoperable: Easy to map to external APIs or services.
  - Limitations:
    - Low expressivity: Can't easily combine or transform results dynamically, or perform complex logic or control flow.
    - Inflexible: Must define all possible actions in advance, limited to predefined tools.
    - No code synthesis: Limited to tool capabilities.

When to use which agent type:
- Use [`CodeAgent`] when:
  - You need reasoning, chaining, or dynamic composition.
  - Tools are functions that can be combined (e.g., parsing + math + querying).
  - Your agent is a problem solver or programmer.

- Use [`ToolCallingAgent`] when:
  - You have simple, atomic tools (e.g., call an API, fetch a document).
  - You want high reliability and clear validation.
  - Your agent is like a dispatcher or controller.

## CodeAgent

[`CodeAgent`] generates Python code snippets to perform actions and solve tasks.

By default, the Python code execution is done in your local environment.
This should be safe because the only functions that can be called are the tools you provided (especially if it's only tools by Hugging Face) and a set of predefined safe functions like `print` or functions from the `math` module, so you're already limited in what can be executed.

The Python interpreter also doesn't allow imports by default outside of a safe list, so all the most obvious attacks shouldn't be an issue.
You can authorize additional imports by passing the authorized modules as a list of strings in argument `additional_authorized_imports` upon initialization of your [`CodeAgent`]:

```py
model = InferenceClientModel()
agent = CodeAgent(tools=[], model=model, additional_authorized_imports=['requests', 'bs4'])
agent.run("Could you get me the title of the page at url 'https://huggingface.co/blog'?")
```

Additionally, as an extra security layer, access to submodule is forbidden by default, unless explicitly authorized within the import list.
For instance, to access the `numpy.random` submodule, you need to add `'numpy.random'` to the `additional_authorized_imports` list.
This could also be authorized by using `numpy.*`, which will allow `numpy` as well as any subpackage like `numpy.random` and its own subpackages.

> [!WARNING]
> The LLM can generate arbitrary code that will then be executed: do not add any unsafe imports!

The execution will stop at any code trying to perform an illegal operation or if there is a regular Python error with the code generated by the agent.

You can also use [Blaxel](https://blaxel.ai), [E2B](https://e2b.dev/docs#what-is-e2-b), or Docker instead of a local Python interpreter. For Blaxel, first [set the `BL_API_KEY` and `BL_WORKSPACE` environment variables](https://app.blaxel.ai/profile/security) and then pass `executor_type="blaxel"` upon agent initialization. For E2B, first [set the `E2B_API_KEY` environment variable](https://e2b.dev/dashboard?tab=keys) and then pass `executor_type="e2b"`. For Docker, pass `executor_type="docker"`.


> [!TIP]
> Learn more about code execution [in this tutorial](tutorials/secure_code_execution).

### ToolCallingAgent

[`ToolCallingAgent`] outputs JSON tool calls, which is the common format used in many frameworks (OpenAI API), allowing for structured tool interactions without code execution. We utilize the built-in WebSearchTool (from the smolagents toolkit extra, which will be described in more detail later) to enable our agent to perform web searches.   

It works much in the same way like [`CodeAgent`], of course without `additional_authorized_imports` since it doesn't execute code:

```py
from smolagents import ToolCallingAgent, WebSearchTool

agent = ToolCallingAgent(tools=[WebSearchTool()], model=model)
agent.run("Could you get me the title of the page at url 'https://huggingface.co/blog'?")
```

## Using the CLI

You can quickly get started with smolagents using the command line interface:

```bash
# Run with direct prompt and options
smolagent "Plan a trip to Tokyo, Kyoto and Osaka between Mar 28 and Apr 7."  --model-type "InferenceClientModel" --model-id "Qwen/Qwen2.5-Coder-32B-Instruct" --imports "pandas numpy" --tools "web_search"

# Run in interactive mode: launches when no prompt is provided, will guide you through argument selection
smolagent
```

## Building your agent

To initialize a minimal agent, you need at least these two arguments:

- `model`, a text-generation model to power your agent - because the agent is different from a simple LLM, it is a system that uses a LLM as its engine. You can use any of these options:
    - [`TransformersModel`] takes a pre-initialized `transformers` pipeline to run inference on your local machine using `transformers`.
    - [`InferenceClientModel`] leverages a `huggingface_hub.InferenceClient` under the hood and supports all Inference Providers on the Hub: Cerebras, Cohere, Fal, Fireworks, HF-Inference, Hyperbolic, Nebius, Novita, Replicate, SambaNova, Together, and more.
    - [`LiteLLMModel`] similarly lets you call 100+ different models and providers through [LiteLLM](https://docs.litellm.ai/)!
    - [`AzureOpenAIModel`] allows you to use OpenAI models deployed in [Azure](https://azure.microsoft.com/en-us/products/ai-services/openai-service).
    - [`AmazonBedrockModel`] allows you to use Amazon Bedrock in [AWS](https://aws.amazon.com/bedrock/?nc1=h_ls).
    - [`MLXModel`] creates a [mlx-lm](https://pypi.org/project/mlx-lm/) pipeline to run inference on your local machine.

- `tools`, a list of `Tools` that the agent can use to solve the task. It can be an empty list. You can also add the default toolbox on top of your `tools` list by defining the optional argument `add_base_tools=True`.

Once you have these two arguments, `tools` and `model`,  you can create an agent and run it. You can use any LLM you'd like, either through [Inference Providers](https://huggingface.co/blog/inference-providers), [transformers](https://github.com/huggingface/transformers/), [ollama](https://ollama.com/), [LiteLLM](https://www.litellm.ai/), [Azure OpenAI](https://azure.microsoft.com/en-us/products/ai-services/openai-service), [Amazon Bedrock](https://aws.amazon.com/bedrock/?nc1=h_ls), or [mlx-lm](https://pypi.org/project/mlx-lm/).

All model classes support passing additional keyword arguments (like `temperature`, `max_tokens`, `top_p`, etc.) directly at instantiation time.
These parameters are automatically forwarded to the underlying model's completion calls, allowing you to configure model behavior such as creativity, response length, and sampling strategies.

<hfoptions id="Pick a LLM">
<hfoption id="Inference Providers">

Inference Providers need a `HF_TOKEN` to authenticate, but a free HF account already comes with included credits. Upgrade to PRO to raise your included credits.

To access gated models or rise your rate limits with a PRO account, you need to set the environment variable `HF_TOKEN` or pass `token` variable upon initialization of `InferenceClientModel`. You can get your token from your [settings page](https://huggingface.co/settings/tokens)

```python
from smolagents import CodeAgent, InferenceClientModel

model_id = "meta-llama/Llama-3.3-70B-Instruct"

model = InferenceClientModel(model_id=model_id, token="<YOUR_HUGGINGFACEHUB_API_TOKEN>") # You can choose to not pass any model_id to InferenceClientModel to use a default model
# you can also specify a particular provider e.g. provider="together" or provider="sambanova"
agent = CodeAgent(tools=[], model=model, add_base_tools=True)

agent.run(
    "Could you give me the 118th number in the Fibonacci sequence?",
)
```
</hfoption>
<hfoption id="Local Transformers Model">

```python
# !pip install 'smolagents[transformers]'
from smolagents import CodeAgent, TransformersModel

model_id = "meta-llama/Llama-3.2-3B-Instruct"

model = TransformersModel(model_id=model_id)
agent = CodeAgent(tools=[], model=model, add_base_tools=True)

agent.run(
    "Could you give me the 118th number in the Fibonacci sequence?",
)
```
</hfoption>
<hfoption id="OpenAI or Anthropic API">

To use `LiteLLMModel`, you need to set the environment variable `ANTHROPIC_API_KEY` or `OPENAI_API_KEY`, or pass `api_key` variable upon initialization.

```python
# !pip install 'smolagents[litellm]'
from smolagents import CodeAgent, LiteLLMModel

model = LiteLLMModel(model_id="anthropic/claude-3-5-sonnet-latest", api_key="YOUR_ANTHROPIC_API_KEY") # Could use 'gpt-4o'
agent = CodeAgent(tools=[], model=model, add_base_tools=True)

agent.run(
    "Could you give me the 118th number in the Fibonacci sequence?",
)
```
</hfoption>
<hfoption id="Ollama">

```python
# !pip install 'smolagents[litellm]'
from smolagents import CodeAgent, LiteLLMModel

model = LiteLLMModel(
    model_id="ollama_chat/llama3.2", # This model is a bit weak for agentic behaviours though
    api_base="http://localhost:11434", # replace with 127.0.0.1:11434 or remote open-ai compatible server if necessary
    api_key="YOUR_API_KEY", # replace with API key if necessary
    num_ctx=8192, # ollama default is 2048 which will fail horribly. 8192 works for easy tasks, more is better. Check https://huggingface.co/spaces/NyxKrage/LLM-Model-VRAM-Calculator to calculate how much VRAM this will need for the selected model.
)

agent = CodeAgent(tools=[], model=model, add_base_tools=True)

agent.run(
    "Could you give me the 118th number in the Fibonacci sequence?",
)
```
</hfoption>
<hfoption id="Azure OpenAI">

To connect to Azure OpenAI, you can either use `AzureOpenAIModel` directly, or use `LiteLLMModel` and configure it accordingly.

To initialize an instance of `AzureOpenAIModel`, you need to pass your model deployment name and then either pass the `azure_endpoint`, `api_key`, and `api_version` arguments, or set the environment variables `AZURE_OPENAI_ENDPOINT`, `AZURE_OPENAI_API_KEY`, and `OPENAI_API_VERSION`.

```python
# !pip install 'smolagents[openai]'
from smolagents import CodeAgent, AzureOpenAIModel

model = AzureOpenAIModel(model_id="gpt-4o-mini")
agent = CodeAgent(tools=[], model=model, add_base_tools=True)

agent.run(
    "Could you give me the 118th number in the Fibonacci sequence?",
)
```

Similarly, you can configure `LiteLLMModel` to connect to Azure OpenAI as follows:

- pass your model deployment name as `model_id`, and make sure to prefix it with `azure/`
- make sure to set the environment variable `AZURE_API_VERSION`
- either pass the `api_base` and `api_key` arguments, or set the environment variables `AZURE_API_KEY`, and `AZURE_API_BASE`

```python
import os
from smolagents import CodeAgent, LiteLLMModel

AZURE_OPENAI_CHAT_DEPLOYMENT_NAME="gpt-35-turbo-16k-deployment" # example of deployment name

os.environ["AZURE_API_KEY"] = "" # api_key
os.environ["AZURE_API_BASE"] = "" # "https://example-endpoint.openai.azure.com"
os.environ["AZURE_API_VERSION"] = "" # "2024-10-01-preview"

model = LiteLLMModel(model_id="azure/" + AZURE_OPENAI_CHAT_DEPLOYMENT_NAME)
agent = CodeAgent(tools=[], model=model, add_base_tools=True)

agent.run(
   "Could you give me the 118th number in the Fibonacci sequence?",
)
```

</hfoption>
<hfoption id="Amazon Bedrock">

The `AmazonBedrockModel` class provides native integration with Amazon Bedrock, allowing for direct API calls and comprehensive configuration.

Basic Usage:

```python
# !pip install 'smolagents[bedrock]'
from smolagents import CodeAgent, AmazonBedrockModel

model = AmazonBedrockModel(model_id="anthropic.claude-3-sonnet-20240229-v1:0")
agent = CodeAgent(tools=[], model=model, add_base_tools=True)

agent.run(
    "Could you give me the 118th number in the Fibonacci sequence?",
)
```

Advanced Configuration:

```python
import boto3
from smolagents import AmazonBedrockModel

# Create a custom Bedrock client
bedrock_client = boto3.client(
    'bedrock-runtime',
    region_name='us-east-1',
    aws_access_key_id='YOUR_ACCESS_KEY',
    aws_secret_access_key='YOUR_SECRET_KEY'
)

additional_api_config = {
    "inferenceConfig": {
        "maxTokens": 3000
    },
    "guardrailConfig": {
        "guardrailIdentifier": "identify1",
        "guardrailVersion": 'v1'
    },
}

# Initialize with comprehensive configuration
model = AmazonBedrockModel(
    model_id="us.amazon.nova-pro-v1:0",
    client=bedrock_client,  # Use custom client
    **additional_api_config
)

agent = CodeAgent(tools=[], model=model, add_base_tools=True)

agent.run(
    "Could you give me the 118th number in the Fibonacci sequence?",
)
```

Using LiteLLMModel:

Alternatively, you can use `LiteLLMModel` with Bedrock models:

```python
from smolagents import LiteLLMModel, CodeAgent

model = LiteLLMModel(model_name="bedrock/anthropic.claude-3-sonnet-20240229-v1:0")
agent = CodeAgent(tools=[], model=model)

agent.run("Explain the concept of quantum computing")
```

</hfoption>
<hfoption id="mlx-lm">

```python
# !pip install 'smolagents[mlx-lm]'
from smolagents import CodeAgent, MLXModel

mlx_model = MLXModel("mlx-community/Qwen2.5-Coder-32B-Instruct-4bit")
agent = CodeAgent(model=mlx_model, tools=[], add_base_tools=True)

agent.run("Could you give me the 118th number in the Fibonacci sequence?")
```

</hfoption>
</hfoptions>

### Model parameter management

When initializing models, you can pass keyword arguments that will be forwarded as completion parameters to the
underlying model API during inference.

For fine-grained control over parameter handling, the `REMOVE_PARAMETER` sentinel value allows you to explicitly exclude
parameters that might otherwise be set by default or passed through elsewhere:

```python
from smolagents import OpenAIModel, REMOVE_PARAMETER

# Remove "stop" parameter
model = OpenAIModel(
    model_id="gpt-5",
    stop=REMOVE_PARAMETER,  # Ensures "stop" is not included in API calls
    temperature=0.7
)

agent = CodeAgent(tools=[], model=model, add_base_tools=True)
```

This is particularly useful when:
- You want to override default parameters that might be applied automatically
- You need to ensure certain parameters are completely excluded from API calls
- You want to let the model provider use their own defaults for specific parameters

## Advanced agent configuration

### Customizing agent termination conditions

By default, an agent continues running until it calls the `final_answer` function or reaches the maximum number of steps.
The `final_answer_checks` parameter gives you more control over when and how an agent terminates its execution:

```python
from smolagents import CodeAgent, InferenceClientModel

# Define a custom final answer check function
def is_integer(final_answer: str, agent_memory=None) -> bool:
    """Return True if final_answer is an integer."""
    try:
        int(final_answer)
        return True
    except ValueError:
        return False

# Initialize agent with custom final answer check
agent = CodeAgent(
    tools=[],
    model=InferenceClientModel(),
    final_answer_checks=[is_integer]
)

agent.run("Calculate the least common multiple of 3 and 7")
```

The `final_answer_checks` parameter accepts a list of functions that each:
- Take the agent's final_answer and the agent itself as parameters
- Return a boolean indicating whether the final_answer is valid (True) or not (False)

If any function returns `False`, the agent will log the error message and continue the run.
This validation mechanism enables:
- Enforcing output format requirements (e.g., ensuring numeric answers for math problems)
- Implementing domain-specific validation rules
- Creating more robust agents that validate their own outputs

## Inspecting an agent run

Here are a few useful attributes to inspect what happened after a run:
- `agent.logs` stores the fine-grained logs of the agent. At every step of the agent's run, everything gets stored in a dictionary that then is appended to `agent.logs`.
- Running `agent.write_memory_to_messages()` writes the agent's memory as list of chat messages for the Model to view. This method goes over each step of the log and only stores what it's interested in as a message: for instance, it will save the system prompt and task in separate messages, then for each step it will store the LLM output as a message, and the tool call output as another message. Use this if you want a higher-level view of what has happened - but not every log will be transcripted by this method.

## Tools

A tool is an atomic function to be used by an agent. To be used by an LLM, it also needs a few attributes that constitute its API and will be used to describe to the LLM how to call this tool:
- A name
- A description
- Input types and descriptions
- An output type

You can for instance check the [`PythonInterpreterTool`]: it has a name, a description, input descriptions, an output type, and a `forward` method to perform the action.

When the agent is initialized, the tool attributes are used to generate a tool description which is baked into the agent's system prompt. This lets the agent know which tools it can use and why.

**Schema Information**: For tools that have an `output_schema` defined (such as MCP tools with structured output), the `CodeAgent` system prompt automatically includes the JSON schema information. This helps the agent understand the expected structure of tool outputs and access the data appropriately.

### Default toolbox

If you install `smolagents` with the "toolkit" extra, it comes with a default toolbox for empowering agents, that you can add to your agent upon initialization with argument `add_base_tools=True`:

- **DuckDuckGo web search***: performs a web search using DuckDuckGo browser.
- **Python code interpreter**: runs your LLM generated Python code in a secure environment. This tool will only be added to [`ToolCallingAgent`] if you initialize it with `add_base_tools=True`, since code-based agent can already natively execute Python code
- **Transcriber**: a speech-to-text pipeline built on Whisper-Turbo that transcribes an audio to text.

You can manually use a tool by calling it with its arguments.

```python
# !pip install 'smolagents[toolkit]'
from smolagents import WebSearchTool

search_tool = WebSearchTool()
print(search_tool("Who's the current president of Russia?"))
```

### Create a new tool

You can create your own tool for use cases not covered by the default tools from Hugging Face.
For example, let's create a tool that returns the most downloaded model for a given task from the Hub.

You'll start with the code below.

```python
from huggingface_hub import list_models

task = "text-classification"

most_downloaded_model = next(iter(list_models(filter=task, sort="downloads", direction=-1)))
print(most_downloaded_model.id)
```

This code can quickly be converted into a tool, just by wrapping it in a function and adding the `tool` decorator:
This is not the only way to build the tool: you can directly define it as a subclass of [`Tool`], which gives you more flexibility, for instance the possibility to initialize heavy class attributes.

Let's see how it works for both options:

<hfoptions id="build-a-tool">
<hfoption id="Decorate a function with @tool">

```py
from smolagents import tool

@tool
def model_download_tool(task: str) -> str:
    """
    This is a tool that returns the most downloaded model of a given task on the Hugging Face Hub.
    It returns the name of the checkpoint.

    Args:
        task: The task for which to get the download count.
    """
    most_downloaded_model = next(iter(list_models(filter=task, sort="downloads", direction=-1)))
    return most_downloaded_model.id
```

The function needs:
- A clear name. The name should be descriptive enough of what this tool does to help the LLM brain powering the agent. Since this tool returns the model with the most downloads for a task, let's name it `model_download_tool`.
- Type hints on both inputs and output
- A description, that includes an 'Args:' part where each argument is described (without a type indication this time, it will be pulled from the type hint). Same as for the tool name, this description is an instruction manual for the LLM powering your agent, so do not neglect it.

All these elements will be automatically baked into the agent's system prompt upon initialization: so strive to make them as clear as possible!

> [!TIP]
> This definition format is the same as tool schemas used in `apply_chat_template`, the only difference is the added `tool` decorator: read more on our tool use API [here](https://huggingface.co/blog/unified-tool-use#passing-tools-to-a-chat-template).


Then you can directly initialize your agent:
```py
from smolagents import CodeAgent, InferenceClientModel
agent = CodeAgent(tools=[model_download_tool], model=InferenceClientModel())
agent.run(
    "Can you give me the name of the model that has the most downloads in the 'text-to-video' task on the Hugging Face Hub?"
)
```
</hfoption>
<hfoption id="Subclass Tool">

```py
from smolagents import Tool

class ModelDownloadTool(Tool):
    name = "model_download_tool"
    description = "This is a tool that returns the most downloaded model of a given task on the Hugging Face Hub. It returns the name of the checkpoint."
    inputs = {"task": {"type": "string", "description": "The task for which to get the download count."}}
    output_type = "string"

    def forward(self, task: str) -> str:
        most_downloaded_model = next(iter(list_models(filter=task, sort="downloads", direction=-1)))
        return most_downloaded_model.id
```

The subclass needs the following attributes:
- A clear `name`. The name should be descriptive enough of what this tool does to help the LLM brain powering the agent. Since this tool returns the model with the most downloads for a task, let's name it `model_download_tool`.
- A `description`. Same as for the `name`, this description is an instruction manual for the LLM powering your agent, so do not neglect it.
- Input types and descriptions
- Output type
All these attributes will be automatically baked into the agent's system prompt upon initialization: so strive to make them as clear as possible!


Then you can directly initialize your agent:
```py
from smolagents import CodeAgent, InferenceClientModel
agent = CodeAgent(tools=[ModelDownloadTool()], model=InferenceClientModel())
agent.run(
    "Can you give me the name of the model that has the most downloads in the 'text-to-video' task on the Hugging Face Hub?"
)
```
</hfoption>
</hfoptions>

You get the following logs:
```text
╭──────────────────────────────────────── New run ─────────────────────────────────────────╮
│                                                                                          │
│ Can you give me the name of the model that has the most downloads in the 'text-to-video' │
│ task on the Hugging Face Hub?                                                            │
│                                                                                          │
╰─ InferenceClientModel - Qwen/Qwen2.5-Coder-32B-Instruct ───────────────────────────────────────────╯
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Step 0 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
╭─ Executing this code: ───────────────────────────────────────────────────────────────────╮
│   1 model_name = model_download_tool(task="text-to-video")                               │
│   2 print(model_name)                                                                    │
╰──────────────────────────────────────────────────────────────────────────────────────────╯
Execution logs:
ByteDance/AnimateDiff-Lightning

Out: None
[Step 0: Duration 0.27 seconds| Input tokens: 2,069 | Output tokens: 60]
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Step 1 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
╭─ Executing this code: ───────────────────────────────────────────────────────────────────╮
│   1 final_answer("ByteDance/AnimateDiff-Lightning")                                      │
╰──────────────────────────────────────────────────────────────────────────────────────────╯
Out - Final answer: ByteDance/AnimateDiff-Lightning
[Step 1: Duration 0.10 seconds| Input tokens: 4,288 | Output tokens: 148]
Out[20]: 'ByteDance/AnimateDiff-Lightning'
```

> [!TIP]
> Read more on tools in the [dedicated tutorial](./tutorials/tools#what-is-a-tool-and-how-to-build-one).

## Multi-agents

Multi-agent systems have been introduced with Microsoft's framework [Autogen](https://huggingface.co/papers/2308.08155).

In this type of framework, you have several agents working together to solve your task instead of only one.
It empirically yields better performance on most benchmarks. The reason for this better performance is conceptually simple: for many tasks, rather than using a do-it-all system, you would prefer to specialize units on sub-tasks. Here, having agents with separate tool sets and memories allows to achieve efficient specialization. For instance, why fill the memory of the code generating agent with all the content of webpages visited by the web search agent? It's better to keep them separate.

You can easily build hierarchical multi-agent systems with `smolagents`.

To do so, just ensure your agent has `name` and`description` attributes, which will then be embedded in the manager agent's system prompt to let it know how to call this managed agent, as we also do for tools.
Then you can pass this managed agent in the parameter managed_agents upon initialization of the manager agent.

Here's an example of making an agent that managed a specific web search agent using our native [`WebSearchTool`]:

```py
from smolagents import CodeAgent, InferenceClientModel, WebSearchTool

model = InferenceClientModel()

web_agent = CodeAgent(
    tools=[WebSearchTool()],
    model=model,
    name="web_search_agent",
    description="Runs web searches for you. Give it your query as an argument."
)

manager_agent = CodeAgent(
    tools=[], model=model, managed_agents=[web_agent]
)

manager_agent.run("Who is the CEO of Hugging Face?")
```

> [!TIP]
> For an in-depth example of an efficient multi-agent implementation, see [how we pushed our multi-agent system to the top of the GAIA leaderboard](https://huggingface.co/blog/beating-gaia).


## Talk with your agent and visualize its thoughts in a cool Gradio interface

You can use `GradioUI` to interactively submit tasks to your agent and observe its thought and execution process, here is an example:

```py
from smolagents import (
    load_tool,
    CodeAgent,
    InferenceClientModel,
    GradioUI
)

# Import tool from Hub
image_generation_tool = load_tool("m-ric/text-to-image", trust_remote_code=True)

model = InferenceClientModel(model_id=model_id)

# Initialize the agent with the image generation tool
agent = CodeAgent(tools=[image_generation_tool], model=model)

GradioUI(agent).launch()
```

Under the hood, when the user types a new answer, the agent is launched with `agent.run(user_request, reset=False)`.
The `reset=False` flag means the agent's memory is not flushed before launching this new task, which lets the conversation go on.

You can also use this `reset=False` argument to keep the conversation going in any other agentic application.

In gradio UIs, if you want to allow users to interrupt a running agent, you could do this with a button that triggers method `agent.interrupt()`.
This will stop the agent at the end of its current step, then raise an error.

## Next steps

Finally, when you've configured your agent to your needs, you can share it to the Hub!

```py
agent.push_to_hub("m-ric/my_agent")
```

Similarly, to load an agent that has been pushed to hub, if you trust the code from its tools, use:
```py
agent.from_hub("m-ric/my_agent", trust_remote_code=True)
```

For more in-depth usage, you will then want to check out our tutorials:
- [the explanation of how our code agents work](./tutorials/secure_code_execution)
- [this guide on how to build good agents](./tutorials/building_good_agents).
- [the in-depth guide for tool usage](./tutorials/building_good_agents).


================================================
FILE: docs/source/en/index.md
================================================
# `smolagents`

<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/smolagents/license_to_call.png" style="max-width:700px"/>
</div>

## What is smolagents?

`smolagents` is an open-source Python library designed to make it extremely easy to build and run agents using just a few lines of code.

Key features of `smolagents` include:

✨ **Simplicity**: The logic for agents fits in ~thousand lines of code. We kept abstractions to their minimal shape above raw code!

🧑‍💻 **First-class support for Code Agents**: [`CodeAgent`](reference/agents#smolagents.CodeAgent) writes its actions in code (as opposed to "agents being used to write code") to invoke tools or perform computations, enabling natural composability (function nesting, loops, conditionals). To make it secure, we support [executing in sandboxed environment](tutorials/secure_code_execution) via [Modal](https://modal.com/), [Blaxel](https://blaxel.ai), [E2B](https://e2b.dev/), or Docker.

📡 **Common Tool-Calling Agent Support**: In addition to CodeAgents, [`ToolCallingAgent`](reference/agents#smolagents.ToolCallingAgent) supports usual JSON/text-based tool-calling for scenarios where that paradigm is preferred.

🤗 **Hub integrations**: Seamlessly share and load agents and tools to/from the Hub as Gradio Spaces.

🌐 **Model-agnostic**: Easily integrate any large language model (LLM), whether it's hosted on the Hub via [Inference providers](https://huggingface.co/docs/inference-providers/index), accessed via APIs such as OpenAI, Anthropic, or many others via LiteLLM integration, or run locally using Transformers or Ollama. Powering an agent with your preferred LLM is straightforward and flexible.

👁️ **Modality-agnostic**: Beyond text, agents can handle vision, video, and audio inputs, broadening the range of possible applications. Check out [this tutorial](examples/web_browser) for vision.

🛠️ **Tool-agnostic**: You can use tools from any [MCP server](reference/tools#smolagents.ToolCollection.from_mcp), from [LangChain](reference/tools#smolagents.Tool.from_langchain), you can even use a [Hub Space](reference/tools#smolagents.Tool.from_space) as a tool.

💻 **CLI Tools**: Comes with command-line utilities (smolagent, webagent) for quickly running agents without writing boilerplate code.

## Quickstart

[[open-in-colab]]

Get started with smolagents in just a few minutes! This guide will show you how to create and run your first agent.

### Installation

Install smolagents with pip:

```bash
pip install 'smolagents[toolkit]'  # Includes default tools like web search
```

### Create Your First Agent

Here's a minimal example to create and run an agent:

```python
from smolagents import CodeAgent, InferenceClientModel

# Initialize a model (using Hugging Face Inference API)
model = InferenceClientModel()  # Uses a default model

# Create an agent with no tools
agent = CodeAgent(tools=[], model=model)

# Run the agent with a task
result = agent.run("Calculate the sum of numbers from 1 to 10")
print(result)
```

That's it! Your agent will use Python code to solve the task and return the result.

### Adding Tools

Let's make our agent more capable by adding some tools:

```python
from smolagents import CodeAgent, InferenceClientModel, DuckDuckGoSearchTool

model = InferenceClientModel()
agent = CodeAgent(
    tools=[DuckDuckGoSearchTool()],
    model=model,
)

# Now the agent can search the web!
result = agent.run("What is the current weather in Paris?")
print(result)
```

### Using Different Models

You can use various models with your agent:

```python
# Using a specific model from Hugging Face
model = InferenceClientModel(model_id="meta-llama/Llama-2-70b-chat-hf")

# Using OpenAI/Anthropic (requires 'smolagents[litellm]')
from smolagents import LiteLLMModel
model = LiteLLMModel(model_id="gpt-4")

# Using local models (requires 'smolagents[transformers]')
from smolagents import TransformersModel
model = TransformersModel(model_id="meta-llama/Llama-2-7b-chat-hf")
```

## Next Steps

- Learn how to set up smolagents with various models and tools in the [Installation Guide](installation)
- Check out the [Guided Tour](guided_tour) for more advanced features
- Learn about [building custom tools](tutorials/tools)
- Explore [secure code execution](tutorials/secure_code_execution)
- See how to create [multi-agent systems](tutorials/building_good_agents)

<div class="mt-10">
  <div class="w-full flex flex-col space-y-4 md:space-y-0 md:grid md:grid-cols-2 md:gap-y-4 md:gap-x-5">
    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./guided_tour"
      ><div class="w-full text-center bg-gradient-to-br from-blue-400 to-blue-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Guided tour</div>
      <p class="text-gray-700">Learn the basics and become familiar with using Agents. Start here if you are using Agents for the first time!</p>
    </a>
    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./examples/text_to_sql"
      ><div class="w-full text-center bg-gradient-to-br from-indigo-400 to-indigo-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">How-to guides</div>
      <p class="text-gray-700">Practical guides to help you achieve a specific goal: create an agent to generate and test SQL queries!</p>
    </a>
    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./conceptual_guides/intro_agents"
      ><div class="w-full text-center bg-gradient-to-br from-pink-400 to-pink-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Conceptual guides</div>
      <p class="text-gray-700">High-level explanations for building a better understanding of important topics.</p>
   </a>
    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./tutorials/building_good_agents"
      ><div class="w-full text-center bg-gradient-to-br from-purple-400 to-purple-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Tutorials</div>
      <p class="text-gray-700">Horizontal tutorials that cover important aspects of building agents.</p>
    </a>
  </div>
</div>


================================================
FILE: docs/source/en/installation.md
================================================
# Installation Options

The `smolagents` library can be installed using pip. Here are the different installation methods and options available.

## Prerequisites
- Python 3.10 or newer
- Python package manager: [`pip`](https://pip.pypa.io/en/stable/) or [`uv`](https://docs.astral.sh/uv/)

## Virtual Environment

It's strongly recommended to install `smolagents` within a Python virtual environment.
Virtual environments isolate your project dependencies from other Python projects and your system Python installation,
preventing version conflicts and making package management more reliable.

<hfoptions id="virtual-environment">
<hfoption id="venv">

Using [`venv`](https://docs.python.org/3/library/venv.html):

```bash
python -m venv .venv
source .venv/bin/activate
```

</hfoption>
<hfoption id="uv">

Using [`uv`](https://docs.astral.sh/uv/):

```bash
uv venv .venv
source .venv/bin/activate
```

</hfoption>
</hfoptions>

## Basic Installation

Install `smolagents` core library with:

<hfoptions id="installation">
<hfoption id="pip">
```bash
pip install smolagents
```
</hfoption>
<hfoption id="uv">
```bash
uv pip install smolagents
```
</hfoption>
</hfoptions>

## Installation with Extras

`smolagents` provides several optional dependencies (extras) that can be installed based on your needs.
You can install these extras using the following syntax:
<hfoptions id="installation">
<hfoption id="pip">
```bash
pip install "smolagents[extra1,extra2]"
```
</hfoption>
<hfoption id="uv">
```bash
uv pip install "smolagents[extra1,extra2]"
```
</hfoption>
</hfoptions>

### Tools
These extras include various tools and integrations:
<hfoptions id="installation">
<hfoption id="pip">
- **toolkit**: Install a default set of tools for common tasks.
  ```bash
  pip install "smolagents[toolkit]"
  ```
- **mcp**: Add support for the Model Context Protocol (MCP) to integrate with external tools and services.
  ```bash
  pip install "smolagents[mcp]"
  ```
</hfoption>
<hfoption id="uv">
- **toolkit**: Install a default set of tools for common tasks.
  ```bash
  uv pip install "smolagents[toolkit]"
  ```
- **mcp**: Add support for the Model Context Protocol (MCP) to integrate with external tools and services.
  ```bash
  uv pip install "smolagents[mcp]"
  ```
</hfoption>
</hfoptions>

### Model Integration
These extras enable integration with various AI models and frameworks:
<hfoptions id="installation">
<hfoption id="pip">
- **openai**: Add support for OpenAI API models.
  ```bash
  pip install "smolagents[openai]"
  ```
- **transformers**: Enable Hugging Face Transformers models.
  ```bash
  pip install "smolagents[transformers]"
  ```
- **vllm**: Add VLLM support for efficient model inference.
  ```bash
  pip install "smolagents[vllm]"
  ```
- **mlx-lm**: Enable support for MLX-LM models.
  ```bash
  pip install "smolagents[mlx-lm]"
  ```
- **litellm**: Add LiteLLM support for lightweight model inference.
  ```bash
  pip install "smolagents[litellm]"
  ```
- **bedrock**: Enable support for AWS Bedrock models.
  ```bash
  pip install "smolagents[bedrock]"
  ```
</hfoption>
<hfoption id="uv">
- **openai**: Add support for OpenAI API models.
  ```bash
  uv pip install "smolagents[openai]"
  ```
- **transformers**: Enable Hugging Face Transformers models.
  ```bash
  uv pip install "smolagents[transformers]"
  ```
- **vllm**: Add VLLM support for efficient model inference.
  ```bash
  uv pip install "smolagents[vllm]"
  ```
- **mlx-lm**: Enable support for MLX-LM models.
  ```bash
  uv pip install "smolagents[mlx-lm]"
  ```
- **litellm**: Add LiteLLM support for lightweight model inference.
  ```bash
  uv pip install "smolagents[litellm]"
  ```
- **bedrock**: Enable support for AWS Bedrock models.
  ```bash
  uv pip install "smolagents[bedrock]"
  ```
</hfoption>
</hfoptions>

### Multimodal Capabilities
Extras for handling different types of media and input:
<hfoptions id="installation">
<hfoption id="pip">
- **vision**: Add support for image processing and computer vision tasks.
  ```bash
  pip install "smolagents[vision]"
  ```
- **audio**: Enable audio processing capabilities.
  ```bash
  pip install "smolagents[audio]"
  ```
</hfoption>
<hfoption id="uv">
- **vision**: Add support for image processing and computer vision tasks.
  ```bash
  uv pip install "smolagents[vision]"
  ```
- **audio**: Enable audio processing capabilities.
  ```bash
  uv pip install "smolagents[audio]"
  ```
</hfoption>
</hfoptions>

### Remote Execution
Extras for executing code remotely:
<hfoptions id="installation">
<hfoption id="pip">
- **blaxel**: Add support for Blaxel sandboxes - fast-launching VMs with hibernation (recommended).
  ```bash
  pip install "smolagents[blaxel]"
  ```
- **e2b**: Enable E2B support for remote execution.
  ```bash
  pip install "smolagents[e2b]"
  ```
- **docker**: Add support for executing code in Docker containers.
  ```bash
  pip install "smolagents[docker]"
  ```
</hfoption>
<hfoption id="uv">
- **blaxel**: Add support for Blaxel sandboxes - fast-launching VMs with hibernation (recommended).
  ```bash
  uv pip install "smolagents[blaxel]"
  ```
- **e2b**: Enable E2B support for remote execution.
  ```bash
  uv pip install "smolagents[e2b]"
  ```
- **docker**: Add support for executing code in Docker containers.
  ```bash
  uv pip install "smolagents[docker]"
  ```
</hfoption>
</hfoptions>

### Telemetry and User Interface
Extras for telemetry, monitoring and user interface components:
<hfoptions id="installation">
<hfoption id="pip">
- **telemetry**: Add support for monitoring and tracing.
  ```bash
  pip install "smolagents[telemetry]"
  ```
- **gradio**: Add support for interactive Gradio UI components.
  ```bash
  pip install "smolagents[gradio]"
  ```
</hfoption>
<hfoption id="uv">
- **telemetry**: Add support for monitoring and tracing.
  ```bash
  uv pip install "smolagents[telemetry]"
  ```
- **gradio**: Add support for interactive Gradio UI components.
  ```bash
  uv pip install "smolagents[gradio]"
  ```
</hfoption>
</hfoptions>

### Complete Installation
To install all available extras, you can use:
<hfoptions id="installation">
<hfoption id="pip">
```bash
pip install "smolagents[all]"
```
</hfoption>
<hfoption id="uv">
```bash
uv pip install "smolagents[all]"
```
</hfoption>
</hfoptions>

## Verifying Installation
After installation, you can verify that `smolagents` is installed correctly by running:
```python
import smolagents
print(smolagents.__version__)
```

## Next Steps
Once you have successfully installed `smolagents`, you can:
- Follow the [guided tour](./guided_tour) to learn the basics.
- Explore the [how-to guides](./examples/text_to_sql) for practical examples.
- Read the [conceptual guides](./conceptual_guides/intro_agents) for high-level explanations.
- Check out the [tutorials](./tutorials/building_good_agents) for in-depth tutorials on building agents.
- Explore the [API reference](./reference/index) for detailed information on classes and functions.


================================================
FILE: docs/source/en/reference/agents.md
================================================
# Agents

<Tip warning={true}>

Smolagents is an experimental API which is subject to change at any time. Results returned by the agents
can vary as the APIs or underlying models are prone to change.

</Tip>

To learn more about agents and tools make sure to read the [introductory guide](../index). This page
contains the API docs for the underlying classes.

## Agents

Our agents inherit from [`MultiStepAgent`], which means they can act in multiple steps, each step consisting of one thought, then one tool call and execution. Read more in [this conceptual guide](../conceptual_guides/react).

We provide two types of agents, based on the main [`Agent`] class.
  - [`CodeAgent`] writes its tool calls in Python code (this is the default).
  - [`ToolCallingAgent`] writes its tool calls in JSON.

Both require arguments `model` and list of tools `tools` at initialization.

### Classes of agents

[[autodoc]] MultiStepAgent

[[autodoc]] CodeAgent

[[autodoc]] ToolCallingAgent

### stream_to_gradio

[[autodoc]] stream_to_gradio

### GradioUI

> [!TIP]
> You must have `gradio` installed to use the UI. Please run `pip install 'smolagents[gradio]'` if it's not the case.

[[autodoc]] GradioUI

## Prompts

[[autodoc]] smolagents.agents.PromptTemplates

[[autodoc]] smolagents.agents.PlanningPromptTemplate

[[autodoc]] smolagents.agents.ManagedAgentPromptTemplate

[[autodoc]] smolagents.agents.FinalAnswerPromptTemplate

## Memory

Smolagents use memory to store information across multiple steps.

[[autodoc]] smolagents.memory.AgentMemory


================================================
FILE: docs/source/en/reference/default_tools.md
================================================
# Built-in Tools

Ready-to-use tool implementations provided by the `smolagents` library.

These built-in tools are concrete implementations of the [`Tool`] base class, each designed for specific tasks such as web searching, Python code execution, webpage retrieval, and user interaction.
You can use these tools directly in your agents without having to implement the underlying functionality yourself.
Each tool handles a particular capability and follows a consistent interface, making it easy to compose them into powerful agent workflows.

The built-in tools can be categorized by their primary functions:
- **Information Retrieval**: Search and retrieve information from the web and specific knowledge sources.
  - [`ApiWebSearchTool`]
  - [`DuckDuckGoSearchTool`]
  - [`GoogleSearchTool`]
  - [`WebSearchTool`]
  - [`WikipediaSearchTool`]
- **Web Interaction**: Fetch and process content from specific web pages.
  - [`VisitWebpageTool`]
- **Code Execution**: Dynamic execution of Python code for computational tasks.
  - [`PythonInterpreterTool`]
- **User Interaction**: Enable Human-in-the-Loop collaboration between agents and users.
  - [`UserInputTool`]: Collect input from users.
- **Speech Processing**: Convert audio to textual data.
  - [`SpeechToTextTool`]
- **Workflow Control**: Manage and direct the flow of agent operations.
  - [`FinalAnswerTool`]: Conclude agent workflow with final response.

## ApiWebSearchTool

[[autodoc]] smolagents.default_tools.ApiWebSearchTool

## DuckDuckGoSearchTool

[[autodoc]] smolagents.default_tools.DuckDuckGoSearchTool

## FinalAnswerTool

[[autodoc]] smolagents.default_tools.FinalAnswerTool

## GoogleSearchTool

[[autodoc]] smolagents.default_tools.GoogleSearchTool

## PythonInterpreterTool

[[autodoc]] smolagents.default_tools.PythonInterpreterTool

## SpeechToTextTool

[[autodoc]] smolagents.default_tools.SpeechToTextTool

## UserInputTool

[[autodoc]] smolagents.default_tools.UserInputTool

## VisitWebpageTool

[[autodoc]] smolagents.default_tools.VisitWebpageTool

## WebSearchTool

[[autodoc]] smolagents.default_tools.WebSearchTool

## WikipediaSearchTool

[[autodoc]] smolagents.default_tools.WikipediaSearchTool


================================================
FILE: docs/source/en/reference/models.md
================================================
# Models

<Tip warning={true}>

Smolagents is an experimental API which is subject to change at any time. Results returned by the agents
can vary as the APIs or underlying models are prone to change.

</Tip>

To learn more about agents and tools make sure to read the [introductory guide](../index). This page
contains the API docs for the underlying classes.

## Models

All model classes in smolagents support passing additional keyword arguments (like `temperature`, `max_tokens`, `top_p`, etc.) directly at instantiation time.
These parameters are automatically forwarded to the underlying model's completion calls, allowing you to configure model behavior such as creativity, response length, and sampling strategies.

### Base Model

The `Model` class serves as the foundation for all model implementations, providing the core interface that custom models must implement to work with agents.

[[autodoc]] Model

### API Model

The `ApiModel` class serves as the foundation for all API-based model implementations, providing common functionality for external API interactions, rate limiting, and client management that API-specific models inherit.

[[autodoc]] ApiModel

### TransformersModel

For convenience, we have added a `TransformersModel` that implements the points above by building a local `transformers` pipeline for the model_id given at initialization.

```python
from smolagents import TransformersModel

model = TransformersModel(model_id="HuggingFaceTB/SmolLM-135M-Instruct")

print(model([{"role": "user", "content": [{"type": "text", "text": "Ok!"}]}], stop_sequences=["great"]))
```
```text
>>> What a
```

You can pass any keyword arguments supported by the underlying model (such as `temperature`, `max_new_tokens`, `top_p`, etc.) directly at instantiation time. These are forwarded to the model completion call:

```python
model = TransformersModel(
    model_id="HuggingFaceTB/SmolLM-135M-Instruct",
    temperature=0.7,
    max_new_tokens=1000
)
```

> [!TIP]
> You must have `transformers` and `torch` installed on your machine. Please run `pip install 'smolagents[transformers]'` if it's not the case.

[[autodoc]] TransformersModel

### InferenceClientModel

The `InferenceClientModel` wraps huggingface_hub's [InferenceClient](https://huggingface.co/docs/huggingface_hub/main/en/guides/inference) for the execution of the LLM. It supports all [Inference Providers](https://huggingface.co/docs/inference-providers/index) available on the Hub: Cerebras, Cohere, Fal, Fireworks, HF-Inference, Hyperbolic, Nebius, Novita, Replicate, SambaNova, Together, and more.

You can also set a rate limit in requests per minute by using the `requests_per_minute` argument:

```python
from smolagents import InferenceClientModel

messages = [
  {"role": "user", "content": [{"type": "text", "text": "Hello, how are you?"}]}
]

model = InferenceClientModel(provider="novita", requests_per_minute=60)
print(model(messages))
```
```text
>>> Of course! If you change your mind, feel free to reach out. Take care!
```

You can pass any keyword arguments supported by the underlying model (such as `temperature`, `max_tokens`, `top_p`, etc.) directly at instantiation time. These are forwarded to the model completion call:

```python
model = InferenceClientModel(
    provider="novita",
    requests_per_minute=60,
    temperature=0.8,
    max_tokens=500
)
```

[[autodoc]] InferenceClientModel

### LiteLLMModel

The `LiteLLMModel` leverages [LiteLLM](https://www.litellm.ai/) to support 100+ LLMs from various providers.
You can pass kwargs upon model initialization that will then be used whenever using the model, for instance below we pass `temperature`. You can also set a rate limit in requests per minute by using the `requests_per_minute` argument.

```python
from smolagents import LiteLLMModel

messages = [
  {"role": "user", "content": [{"type": "text", "text": "Hello, how are you?"}]}
]

model = LiteLLMModel(model_id="anthropic/claude-3-5-sonnet-latest", temperature=0.2, max_tokens=10, requests_per_minute=60)
print(model(messages))
```

[[autodoc]] LiteLLMModel

### LiteLLMRouterModel

The `LiteLLMRouterModel` is a wrapper around the [LiteLLM Router](https://docs.litellm.ai/docs/routing) that leverages
advanced routing strategies: load-balancing across multiple deployments, prioritizing critical requests via queueing,
and implementing basic reliability measures such as cooldowns, fallbacks, and exponential backoff retries.

```python
from smolagents import LiteLLMRouterModel

messages = [
  {"role": "user", "content": [{"type": "text", "text": "Hello, how are you?"}]}
]

model = LiteLLMRouterModel(
    model_id="llama-3.3-70b",
    model_list=[
        {
            "model_name": "llama-3.3-70b",
            "litellm_params": {"model": "groq/llama-3.3-70b", "api_key": os.getenv("GROQ_API_KEY")},
        },
        {
            "model_name": "llama-3.3-70b",
            "litellm_params": {"model": "cerebras/llama-3.3-70b", "api_key": os.getenv("CEREBRAS_API_KEY")},
        },
    ],
    client_kwargs={
        "routing_strategy": "simple-shuffle",
    },
)
print(model(messages))
```

[[autodoc]] LiteLLMRouterModel

### OpenAIModel

This class lets you call any OpenAIServer compatible model.
Here's how you can set it (you can customise the `api_base` url to point to another server):
```py
import os
from smolagents import OpenAIModel

model = OpenAIModel(
    model_id="gpt-4o",
    api_base="https://api.openai.com/v1",
    api_key=os.environ["OPENAI_API_KEY"],
)
```

You can pass any keyword arguments supported by the underlying model (such as `temperature`, `max_tokens`, `top_p`, etc.) directly at instantiation time. These are forwarded to the model completion call:

```py
model = OpenAIModel(
    model_id="gpt-4o",
    api_base="https://api.openai.com/v1",
    api_key=os.environ["OPENAI_API_KEY"],
    temperature=0.7,
    max_tokens=1000,
    top_p=0.9,
)
```

[[autodoc]] OpenAIModel

### AzureOpenAIModel

`AzureOpenAIModel` allows you to connect to any Azure OpenAI deployment. 

Below you can find an example of how to set it up, note that you can omit the `azure_endpoint`, `api_key`, and `api_version` arguments, provided you've set the corresponding environment variables -- `AZURE_OPENAI_ENDPOINT`, `AZURE_OPENAI_API_KEY`, and `OPENAI_API_VERSION`.

Pay attention to the lack of an `AZURE_` prefix for `OPENAI_API_VERSION`, this is due to the way the underlying [openai](https://github.com/openai/openai-python) package is designed. 

```py
import os

from smolagents import AzureOpenAIModel

model = AzureOpenAIModel(
    model_id = os.environ.get("AZURE_OPENAI_MODEL"),
    azure_endpoint=os.environ.get("AZURE_OPENAI_ENDPOINT"),
    api_key=os.environ.get("AZURE_OPENAI_API_KEY"),
    api_version=os.environ.get("OPENAI_API_VERSION")    
)
```

[[autodoc]] AzureOpenAIModel

### AmazonBedrockModel

`AmazonBedrockModel` helps you connect to Amazon Bedrock and run your agent with any available models.

Below is an example setup. This class also offers additional options for customization.

```py
import os

from smolagents import AmazonBedrockModel

model = AmazonBedrockModel(
    model_id = os.environ.get("AMAZON_BEDROCK_MODEL_ID"),
)
```

[[autodoc]] AmazonBedrockModel

### MLXModel


```python
from smolagents import MLXModel

model = MLXModel(model_id="HuggingFaceTB/SmolLM-135M-Instruct")

print(model([{"role": "user", "content": "Ok!"}], stop_sequences=["great"]))
```
```text
>>> What a
```

> [!TIP]
> You must have `mlx-lm` installed on your machine. Please run `pip install 'smolagents[mlx-lm]'` if it's not the case.

[[autodoc]] MLXModel

### VLLMModel

Model to use [vLLM](https://docs.vllm.ai/) for fast LLM inference and serving.

```python
from smolagents import VLLMModel

model = VLLMModel(model_id="HuggingFaceTB/SmolLM-135M-Instruct")

print(model([{"role": "user", "content": "Ok!"}], stop_sequences=["great"]))
```

> [!TIP]
> You must have `vllm` installed on your machine. Please run `pip install 'smolagents[vllm]'` if it's not the case.

[[autodoc]] VLLMModel

### Custom Model

You're free to create and use your own models to power your agent.

You could subclass the base `Model` class to create a model for your agent.
The main criteria is to subclass the `generate` method, with these two criteria:
1. It follows the [messages format](./chat_templating) (`List[Dict[str, str]]`) for its input `messages`, and it returns an object with a `.content` attribute.
2. It stops generating outputs at the sequences passed in the argument `stop_sequences`.

For defining your LLM, you can make a `CustomModel` class that inherits from the base `Model` class.
It should have a generate method that takes a list of [messages](./chat_templating) and returns an object with a .content attribute containing the text. The `generate` method also needs to accept a `stop_sequences` argument that indicates when to stop generating.

```python
from huggingface_hub import login, InferenceClient

from smolagents import Model

login("<YOUR_HUGGINGFACEHUB_API_TOKEN>")

model_id = "meta-llama/Llama-3.3-70B-Instruct"

client = InferenceClient(model=model_id)

class CustomModel(Model):
    def generate(messages, stop_sequences=["Task"]):
        response = client.chat_completion(messages, stop=stop_sequences, max_tokens=1024)
        answer = response.choices[0].message
        return answer

custom_model = CustomModel()
```

Additionally, `generate` can also take a `grammar` argument to allow [constrained generation](https://huggingface.co/docs/text-generation-inference/conceptual/guidance) in order to force properly-formatted agent outputs.


================================================
FILE: docs/source/en/reference/python_executors.md
================================================
# Python code executors

Python executors are responsible for running the code generated by code agents in a controlled environment.
Since agents dynamically generate and execute Python code to accomplish tasks, choosing the right executor is critical
for both functionality and security.

To learn more about code execution and its risks, make sure to read the [Secure code execution](../tutorials/secure_code_execution)
tutorial. This reference contains the API docs for the underlying classes: the base `PythonExecutor` interface and all 
available executor implementations.

## Python executor

[[autodoc]] smolagents.local_python_executor.PythonExecutor

## Local Python executor

[[autodoc]] smolagents.local_python_executor.LocalPythonExecutor

## Remote Python executors

[[autodoc]] smolagents.remote_executors.RemotePythonExecutor

### BlaxelExecutor

[[autodoc]] smolagents.remote_executors.BlaxelExecutor

### E2BExecutor

[[autodoc]] smolagents.remote_executors.E2BExecutor

### ModalExecutor

[[autodoc]] smolagents.remote_executors.ModalExecutor

### DockerExecutor

[[autodoc]] smolagents.remote_executors.DockerExecutor

### WasmExecutor

[[autodoc]] smolagents.remote_executors.WasmExecutor


================================================
FILE: docs/source/en/reference/tools.md
================================================
# Tools

<Tip warning={true}>

Smolagents is an experimental API which is subject to change at any time. Results returned by the agents
can vary as the APIs or underlying models are prone to change.

</Tip>

To learn more about agents and tools make sure to read the [introductory guide](../index). This page
contains the API docs for the underlying classes.

## Tool Base Classes

### load_tool

[[autodoc]] load_tool

### tool

[[autodoc]] tool

### Tool

[[autodoc]] Tool

### launch_gradio_demo

[[autodoc]] launch_gradio_demo

## ToolCollection

[[autodoc]] ToolCollection

## MCP Client

[[autodoc]] smolagents.mcp_client.MCPClient

## Agent Types

Agents can handle any type of object in-between tools; tools, being completely multimodal, can accept and return
text, image, audio, video, among other types. In order to increase compatibility between tools, as well as to
correctly render these returns in ipython (jupyter, colab, ipython notebooks, ...), we implement wrapper classes
around these types.

The wrapped objects should continue behaving as initially; a text object should still behave as a string, an image
object should still behave as a `PIL.Image`.

These types have three specific purposes:

- Calling `to_raw` on the type should return the underlying object
- Calling `to_string` on the type should return the object as a string: that can be the string in case of an `AgentText`
  but will be the path of the serialized version of the object in other instances
- Displaying it in an ipython kernel should display the object correctly

### AgentText

[[autodoc]] smolagents.agent_types.AgentText

### AgentImage

[[autodoc]] smolagents.agent_types.AgentImage

### AgentAudio

[[autodoc]] smolagents.agent_types.AgentAudio


================================================
FILE: docs/source/en/tutorials/building_good_agents.md
================================================
# Building good agents

[[open-in-colab]]

There's a world of difference between building an agent that works and one that doesn't.
How can we build agents that fall into the former category?
In this guide, we're going to talk about best practices for building agents.

> [!TIP]
> If you're new to building agents, make sure to first read the [intro to agents](../conceptual_guides/intro_agents) and the [guided tour of smolagents](../guided_tour).

### The best agentic systems are the simplest: simplify the workflow as much as you can

Giving an LLM some agency in your workflow introduces some risk of errors.

Well-programmed agentic systems have good error logging and retry mechanisms anyway, so the LLM engine has a chance to self-correct their mistake. But to reduce the risk of LLM error to the maximum, you should simplify your workflow!

Let's revisit the example from the [intro to agents](../conceptual_guides/intro_agents): a bot that answers user queries for a surf trip company.
Instead of letting the agent do 2 different calls for "travel distance API" and "weather API" each time they are asked about a new surf spot, you could just make one unified tool "return_spot_information", a function that calls both APIs at once and returns their concatenated outputs to the user.

This will reduce costs, latency, and error risk!

The main guideline is: Reduce the number of LLM calls as much as you can.

This leads to a few takeaways:
- Whenever possible, group 2 tools in one, like in our example of the two APIs.
- Whenever possible, logic should be based on deterministic functions rather than agentic decisions.

### Improve the information flow to the LLM engine

Remember that your LLM engine is like an *intelligent* robot, trapped into a room with the only communication with the outside world being notes passed under a door.

It won't know of anything that happened if you don't explicitly put that into its prompt.

So first start with making your task very clear!
Since an agent is powered by an LLM, minor variations in your task formulation might yield completely different results.

Then, improve the information flow towards your agent in tool use.

Particular guidelines to follow:
- Each tool should log (by simply using `print` statements inside the tool's `forward` method) everything that could be useful for the LLM engine.
  - In particular, logging detail on tool execution errors would help a lot!

For instance, here's a tool that retrieves weather data based on location and date-time:

First, here's a poor version:
```python
import datetime
from smolagents import tool

def get_weather_report_at_coordinates(coordinates, date_time):
    # Dummy function, returns a list of [temperature in °C, risk of rain on a scale 0-1, wave height in m]
    return [28.0, 0.35, 0.85]

def convert_location_to_coordinates(location):
    # Returns dummy coordinates
    return [3.3, -42.0]

@tool
def get_weather_api(location: str, date_time: str) -> str:
    """
    Returns the weather report.

    Args:
        location: the name of the place that you want the weather for.
        date_time: the date and time for which you want the report.
    """
    lon, lat = convert_location_to_coordinates(location)
    date_time = datetime.strptime(date_time)
    return str(get_weather_report_at_coordinates((lon, lat), date_time))
```

Why is it bad?
- there's no precision of the format that should be used for `date_time`
- there's no detail on how location should be specified.
- there's no logging mechanism trying to make explicit failure cases like location not being in a proper format, or date_time not being properly formatted.
- the output format is hard to understand

If the tool call fails, the error trace logged in memory can help the LLM reverse engineer the tool to fix the errors. But why leave it with so much heavy lifting to do?

A better way to build this tool would have been the following:
```python
@tool
def get_weather_api(location: str, date_time: str) -> str:
    """
    Returns the weather report.

    Args:
        location: the name of the place that you want the weather for. Should be a place name, followed by possibly a city name, then a country, like "Anchor Point, Taghazout, Morocco".
        date_time: the date and time for which you want the report, formatted as '%m/%d/%y %H:%M:%S'.
    """
    lon, lat = convert_location_to_coordinates(location)
    try:
        date_time = datetime.strptime(date_time)
    except Exception as e:
        raise ValueError("Conversion of `date_time` to datetime format failed, make sure to provide a string in format '%m/%d/%y %H:%M:%S'. Full trace:" + str(e))
    temperature_celsius, risk_of_rain, wave_height = get_weather_report_at_coordinates((lon, lat), date_time)
    return f"Weather report for {location}, {date_time}: Temperature will be {temperature_celsius}°C, risk of rain is {risk_of_rain*100:.0f}%, wave height is {wave_height}m."
```

In general, to ease the load on your LLM, the good question to ask yourself is: "How easy would it be for me, if I was dumb and using this tool for the first time ever, to program with this tool and correct my own errors?".

### Give more arguments to the agent

To pass some additional objects to your agent beyond the simple string describing the task, you can use the `additional_args` argument to pass any type of object:

```py
from smolagents import CodeAgent, InferenceClientModel

model_id = "meta-llama/Llama-3.3-70B-Instruct"

agent = CodeAgent(tools=[], model=InferenceClientModel(model_id=model_id), add_base_tools=True)

agent.run(
    "Why does Mike not know many people in New York?",
    additional_args={"mp3_sound_file_url":'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/recording.mp3'}
)
```
For instance, you can use this `additional_args` argument to pass images or strings that you want your agent to leverage.



## How to debug your agent

### 1. Use a stronger LLM

In an agentic workflows, some of the errors are actual errors, some other are the fault of your LLM engine not reasoning properly.
For instance, consider this trace for an `CodeAgent` that I asked to create a car picture:
```
==================================================================================================== New task ====================================================================================================
Make me a cool car picture
──────────────────────────────────────────────────────────────────────────────────────────────────── New step ────────────────────────────────────────────────────────────────────────────────────────────────────
Agent is executing the code below: ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
image_generator(prompt="A cool, futuristic sports car with LED headlights, aerodynamic design, and vibrant color, high-res, photorealistic")
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

Last output from code snippet: ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
/var/folders/6m/9b1tts6d5w960j80wbw9tx3m0000gn/T/tmpx09qfsdd/652f0007-3ee9-44e2-94ac-90dae6bb89a4.png
Step 1:

- Time taken: 16.35 seconds
- Input tokens: 1,383
- Output tokens: 77
──────────────────────────────────────────────────────────────────────────────────────────────────── New step ────────────────────────────────────────────────────────────────────────────────────────────────────
Agent is executing the code below: ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
final_answer("/var/folders/6m/9b1tts6d5w960j80wbw9tx3m0000gn/T/tmpx09qfsdd/652f0007-3ee9-44e2-94ac-90dae6bb89a4.png")
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Print outputs:

Last output from code snippet: ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
/var/folders/6m/9b1tts6d5w960j80wbw9tx3m0000gn/T/tmpx09qfsdd/652f0007-3ee9-44e2-94ac-90dae6bb89a4.png
Final answer:
/var/folders/6m/9b1tts6d5w960j80wbw9tx3m0000gn/T/tmpx09qfsdd/652f0007-3ee9-44e2-94ac-90dae6bb89a4.png
```
The user sees, instead of an image being returned, a path being returned to them.
It could look like a bug from the system, but actually the agentic system didn't cause the error: it's just that the LLM brain did the mistake of not saving the image output into a variable.
Thus it cannot access the image again except by leveraging the path that was logged while saving the image, so it returns the path instead of an image.

The first step to debugging your agent is thus "Use a more powerful LLM". Alternatives like `Qwen2/5-72B-Instruct` wouldn't have made that mistake.

### 2. Provide more information or specific instructions

You can also use less powerful models, provided you guide them more effectively.

Put yourself in the shoes of your model: if you were the model solving the task, would you struggle with the information available to you (from the system prompt + task formulation + tool description) ?

Would you need detailed instructions?

- If the instruction is to always be given to the agent (as we generally understand a system prompt to work): you can pass it as a string under argument `instructions` upon agent initialization. *(Note: instructions are appended to the system prompt, not replacing it.)*
- If it's about a specific task to solve: add all these details to the task. The task could be very long, like dozens of pages.
- If it's about how to use specific tools: include it in the `description` attribute of these tools.


### 3. Change the prompt templates (generally not advised)

If above clarifications are not sufficient, you can change the agent's prompt templates.

Let's see how it works. For example, let us check the default prompt templates for the [`CodeAgent`] (below version is shortened by skipping zero-shot examples).

```python
print(agent.prompt_templates["system_prompt"])
```
Here is what you get:
```text
You are an expert assistant who can solve any task using code blobs. You will be given a task to solve as best you can.
To do so, you have been given access to a list of tools: these tools are basically Python functions which you can call with code.
To solve the task, you must plan forward to proceed in a series of steps, in a cycle of Thought, Code, and Observation sequences.

At each step, in the 'Thought:' sequence, you should first explain your reasoning towards solving the task and the tools that you want to use.
Then in the Code sequence you should write the code in simple Python. The code sequence must be opened with '{{code_block_opening_tag}}', and closed with '{{code_block_closing_tag}}'.
During each intermediate step, you can use 'print()' to save whatever important information you will then need.
These print outputs will then appear in the 'Observation:' field, which will be available as input for the next step.
In the end you have to return a final answer using the `final_answer` tool.

Here are a few examples using notional tools:
---
Task: "Generate an image of the oldest person in this document."

Thought: I will proceed step by step and use the following tools: `document_qa` to find the oldest person in the document, then `image_generator` to generate an image according to the answer.
{{code_block_opening_tag}}
answer = document_qa(document=document, question="Who is the oldest person mentioned?")
print(answer)
{{code_block_closing_tag}}
Observation: "The oldest person in the document is John Doe, a 55 year old lumberjack living in Newfoundland."

Thought: I will now generate an image showcasing the oldest person.
{{code_block_opening_tag}}
image = image_generator("A portrait of John Doe, a 55-year-old man living in Canada.")
final_answer(image)
{{code_block_closing_tag}}

---
Task: "What is the result of the following operation: 5 + 3 + 1294.678?"

Thought: I will use python code to compute the result of the operation and then return the final answer using the `final_answer` tool
{{code_block_opening_tag}}
result = 5 + 3 + 1294.678
final_answer(result)
{{code_block_closing_tag}}

---
Task:
"Answer the question in the variable `question` about the image stored in the variable `image`. The question is in French.
You have been provided with these additional arguments, that you can access using the keys as variables in your python code:
{'question': 'Quel est l'animal sur l'image?', 'image': 'path/to/image.jpg'}"

Thought: I will use the following tools: `translator` to translate the question into English and then `image_qa` to answer the question on the input image.
{{code_block_opening_tag}}
translated_question = translator(question=question, src_lang="French", tgt_lang="English")
print(f"The translated question is {translated_question}.")
answer = image_qa(image=image, question=translated_question)
final_answer(f"The answer is {answer}")
{{code_block_closing_tag}}

---
Task:
In a 1979 interview, Stanislaus Ulam discusses with Martin Sherwin about other great physicists of his time, including Oppenheimer.
What does he say was the consequence of Einstein learning too much math on his creativity, in one word?

Thought: I need to find and read the 1979 interview of Stanislaus Ulam with Martin Sherwin.
{{code_block_opening_tag}}
pages = web_search(query="1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein")
print(pages)
{{code_block_closing_tag}}
Observation:
No result found for query "1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein".

Thought: The query was maybe too restrictive and did not find any results. Let's try again with a broader query.
{{code_block_opening_tag}}
pages = web_search(query="1979 interview Stanislaus Ulam")
print(pages)
{{code_block_closing_tag}}
Observation:
Found 6 pages:
[Stanislaus Ulam 1979 interview](https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/)

[Ulam discusses Manhattan Project](https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/)

(truncated)

Thought: I will read the first 2 pages to know more.
{{code_block_opening_tag}}
for url in ["https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/", "https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/"]:
    whole_page = visit_webpage(url)
    print(whole_page)
    print("\n" + "="*80 + "\n")  # Print separator between pages
{{code_block_closing_tag}}
Observation:
Manhattan Project Locations:
Los Alamos, NM
Stanislaus Ulam was a Polish-American mathematician. He worked on the Manhattan Project at Los Alamos and later helped design the hydrogen bomb. In this interview, he discusses his work at
(truncated)

Thought: I now have the final answer: from the webpages visited, Stanislaus Ulam says of Einstein: "He learned too much mathematics and sort of diminished, it seems to me personally, it seems to me his purely physics creativity." Let's answer in one word.
{{code_block_opening_tag}}
final_answer("diminished")
{{code_block_closing_tag}}

---
Task: "Which city has the highest population: Guangzhou or Shanghai?"

Thought: I need to get the populations for both cities and compare them: I will use the tool `web_search` to get the population of both cities.
{{code_block_opening_tag}}
for city in ["Guangzhou", "Shanghai"]:
    print(f"Population {city}:", web_search(f"{city} population")
{{code_block_closing_tag}}
Observation:
Population Guangzhou: ['Guangzhou has a population of 15 million inhabitants as of 2021.']
Population Shanghai: '26 million (2019)'

Thought: Now I know that Shanghai has the highest population.
{{code_block_opening_tag}}
final_answer("Shanghai")
{{code_block_closing_tag}}

---
Task: "What is the current age of the pope, raised to the power 0.36?"

Thought: I will use the tool `wikipedia_search` to get the age of the pope, and confirm that with a web search.
{{code_block_opening_tag}}
pope_age_wiki = wikipedia_search(query="current pope age")
print("Pope age as per wikipedia:", pope_age_wiki)
pope_age_search = web_search(query="current pope age")
print("Pope age as per google search:", pope_age_search)
{{code_block_closing_tag}}
Observation:
Pope age: "The pope Francis is currently 88 years old."

Thought: I know that the pope is 88 years old. Let's compute the result using python code.
{{code_block_opening_tag}}
pope_current_age = 88 ** 0.36
final_answer(pope_current_age)
{{code_block_closing_tag}}

Above example were using notional tools that might not exist for you. On top of performing computations in the Python code snippets that you create, you only have access to these tools, behaving like regular python functions:
{{code_block_opening_tag}}
{%- for tool in tools.values() %}
{{ tool.to_code_prompt() }}
{% endfor %}
{{code_block_closing_tag}}

{%- if managed_agents and managed_agents.values() | list %}
You can also give tasks to team members.
Calling a team member works similarly to calling a tool: provide the task description as the 'task' argument. Since this team member is a real human, be as detailed and verbose as necessary in your task description.
You can also include any relevant variables or context using the 'additional_args' argument.
Here is a list of the team members that you can call:
{{code_block_opening_tag}}
{%- for agent in managed_agents.values() %}
def {{ agent.name }}(task: str, additional_args: dict[str, Any]) -> str:
    """{{ agent.description }}

    Args:
        task: Long detailed description of the task.
        additional_args: Dictionary of extra inputs to pass to the managed agent, e.g. images, dataframes, or any other contextual data it may need.
    """
{% endfor %}
{{code_block_closing_tag}}
{%- endif %}

Here are the rules you should always follow to solve your task:
1. Always provide a 'Thought:' sequence, and a '{{code_block_opening_tag}}' sequence ending with '{{code_block_closing_tag}}', else you will fail.
2. Use only variables that you have defined!
3. Always use the right arguments for the tools. DO NOT pass the arguments as a dict as in 'answer = wikipedia_search({'query': "What is the place where James Bond lives?"})', but use the arguments directly as in 'answer = wikipedia_search(query="What is the place where James Bond lives?")'.
4. For tools WITHOUT JSON output schema: Take care to not chain too many sequential tool calls in the same code block, as their output format is unpredictable. For instance, a call to wikipedia_search without a JSON output schema has an unpredictable return format, so do not have another tool call that depends on its output in the same block: rather output results with print() to use them in the next block.
5. For tools WITH JSON output schema: You can confidently chain multiple tool calls and directly access structured output fields in the same code block! When a tool has a JSON output schema, you know exactly what fields and data types to expect, allowing you to write robust code that directly accesses the structured response (e.g., result['field_name']) without needing intermediate print() statements.
6. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.
7. Don't name any new variable with the same name as a tool: for instance don't name a variable 'final_answer'.
8. Never create any notional variables in our code, as having these in your logs will derail you from the true variables.
9. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}
10. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
11. Don't give up! You're in charge of solving the task, not providing directions to solve it.

{%- if custom_instructions %}
{{custom_instructions}}
{%- endif %}

Now Begin!
```

As you can see, there are placeholders like `"{{ tool.description }}"`: these will be used upon agent initialization to insert certain automatically generated descriptions of tools or managed agents.

So while you can overwrite this system prompt template by passing your custom prompt as an argument to the `system_prompt` parameter, your new system prompt can contain the following placeholders:
- To insert tool descriptions:
  ```
  {%- for tool in tools.values() %}
  - {{ tool.to_tool_calling_prompt() }}
  {%- endfor %}
  ```
- To insert the descriptions for managed agents if there are any:
  ```
  {%- if managed_agents and managed_agents.values() | list %}
  You can also give tasks to team members.
  Calling a team member works similarly to calling a tool: provide the task description as the 'task' argument. Since this team member is a real human, be as detailed and verbose as necessary in your task description.
  You can also include any relevant variables or context using the 'additional_args' argument.
  Here is a list of the team members that you can call:
  {%- for agent in managed_agents.values() %}
  - {{ agent.name }}: {{ agent.description }}
  {%- endfor %}
  {%- endif %}
  ```
- For `CodeAgent` only, to insert the list of authorized imports: `"{{authorized_imports}}"`

Then you can change the system prompt as follows:

```py
agent.prompt_templates["system_prompt"] = agent.prompt_templates["system_prompt"] + "\nHere you go!"
```

This also works with the [`ToolCallingAgent`].

But generally it's just simpler to pass argument `instructions` upon agent initalization, like:
```py
agent = CodeAgent(tools=[], model=InferenceClientModel(model_id=model_id), instructions="Always talk like a 5 year old.")
```

Note that `instructions` are appended to the system prompt, not replacing it.


### 4. Extra planning

We provide a model for a supplementary planning step, that an agent can run regularly in-between normal action steps. In this step, there is no tool call, the LLM is simply asked to update a list of facts it knows and to reflect on what steps it should take next based on those facts.

```py
from smolagents import load_tool, CodeAgent, InferenceClientModel, WebSearchTool
from dotenv import load_dotenv

load_dotenv()

# Import tool from Hub
image_generation_tool = load_tool("m-ric/text-to-image", trust_remote_code=True)

search_tool = WebSearchTool()

agent = CodeAgent(
    tools=[search_tool, image_generation_tool],
    model=InferenceClientModel(model_id="Qwen/Qwen2.5-72B-Instruct"),
    planning_interval=3 # This is where you activate planning!
)

# Run it!
result = agent.run(
    "How long would a cheetah at full speed take to run the length of Pont Alexandre III?",
Download .txt
gitextract_wncyz_3h/

├── .github/
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug_report.md
│   │   ├── doc_improvement.md
│   │   └── feature_request.md
│   └── workflows/
│       ├── build_documentation.yml
│       ├── build_pr_documentation.yml
│       ├── quality.yml
│       ├── tests.yml
│       ├── trufflehog.yml
│       └── upload_pr_documentation.yml
├── .gitignore
├── .pre-commit-config.yaml
├── AGENTS.md
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── Makefile
├── README.md
├── SECURITY.md
├── docs/
│   ├── README.md
│   └── source/
│       ├── en/
│       │   ├── _config.py
│       │   ├── _toctree.yml
│       │   ├── conceptual_guides/
│       │   │   ├── intro_agents.md
│       │   │   └── react.md
│       │   ├── examples/
│       │   │   ├── async_agent.md
│       │   │   ├── multiagents.md
│       │   │   ├── plan_customization.md
│       │   │   ├── rag.md
│       │   │   ├── text_to_sql.md
│       │   │   ├── using_different_models.md
│       │   │   └── web_browser.md
│       │   ├── guided_tour.md
│       │   ├── index.md
│       │   ├── installation.md
│       │   ├── reference/
│       │   │   ├── agents.md
│       │   │   ├── default_tools.md
│       │   │   ├── models.md
│       │   │   ├── python_executors.md
│       │   │   └── tools.md
│       │   └── tutorials/
│       │       ├── building_good_agents.md
│       │       ├── inspect_runs.md
│       │       ├── memory.md
│       │       ├── secure_code_execution.md
│       │       └── tools.md
│       ├── es/
│       │   ├── _config.py
│       │   ├── _toctree.yml
│       │   ├── index.md
│       │   └── installation.md
│       ├── hi/
│       │   ├── _config.py
│       │   ├── _toctree.yml
│       │   ├── conceptual_guides/
│       │   │   ├── intro_agents.md
│       │   │   └── react.md
│       │   ├── examples/
│       │   │   ├── multiagents.md
│       │   │   ├── rag.md
│       │   │   └── text_to_sql.md
│       │   ├── guided_tour.md
│       │   ├── index.md
│       │   ├── reference/
│       │   │   ├── agents.md
│       │   │   └── tools.md
│       │   └── tutorials/
│       │       ├── building_good_agents.md
│       │       ├── inspect_runs.md
│       │       ├── secure_code_execution.md
│       │       └── tools.md
│       ├── ko/
│       │   ├── _config.py
│       │   ├── _toctree.yml
│       │   ├── conceptual_guides/
│       │   │   └── react.md
│       │   ├── examples/
│       │   │   ├── async_agent.md
│       │   │   ├── multiagents.md
│       │   │   ├── plan_customization.md
│       │   │   ├── rag.md
│       │   │   ├── text_to_sql.md
│       │   │   ├── using_different_models.md
│       │   │   └── web_browser.md
│       │   ├── guided_tour.md
│       │   ├── index.md
│       │   ├── installation.md
│       │   ├── reference/
│       │   │   ├── agents.md
│       │   │   ├── models.md
│       │   │   └── tools.md
│       │   └── tutorials/
│       │       ├── building_good_agents.md
│       │       ├── inspect_runs.md
│       │       └── memory.md
│       └── zh/
│           ├── _config.py
│           ├── _toctree.yml
│           ├── conceptual_guides/
│           │   ├── intro_agents.md
│           │   └── react.md
│           ├── examples/
│           │   ├── multiagents.md
│           │   ├── rag.md
│           │   ├── text_to_sql.md
│           │   └── web_browser.md
│           ├── guided_tour.md
│           ├── index.md
│           ├── reference/
│           │   ├── agents.md
│           │   ├── models.md
│           │   └── tools.md
│           └── tutorials/
│               ├── building_good_agents.md
│               ├── inspect_runs.md
│               ├── memory.md
│               ├── secure_code_execution.md
│               └── tools.md
├── e2b.toml
├── examples/
│   ├── agent_from_any_llm.py
│   ├── async_agent/
│   │   ├── README.md
│   │   ├── main.py
│   │   └── requirements.txt
│   ├── gradio_ui.py
│   ├── inspect_multiagent_run.py
│   ├── multi_llm_agent.py
│   ├── multiple_tools.py
│   ├── open_deep_research/
│   │   ├── README.md
│   │   ├── analysis.ipynb
│   │   ├── app.py
│   │   ├── requirements.txt
│   │   ├── run.py
│   │   ├── run_gaia.py
│   │   ├── scripts/
│   │   │   ├── cookies.py
│   │   │   ├── gaia_scorer.py
│   │   │   ├── mdconvert.py
│   │   │   ├── reformulator.py
│   │   │   ├── run_agents.py
│   │   │   ├── text_inspector_tool.py
│   │   │   ├── text_web_browser.py
│   │   │   └── visual_qa.py
│   │   └── visual_vs_text_browser.ipynb
│   ├── plan_customization/
│   │   ├── README.md
│   │   └── plan_customization.py
│   ├── rag.py
│   ├── rag_using_chromadb.py
│   ├── sandboxed_execution.py
│   ├── server/
│   │   ├── README.md
│   │   └── main.py
│   ├── smolagents_benchmark/
│   │   ├── run.py
│   │   └── score.ipynb
│   ├── structured_output_tool.py
│   └── text_to_sql.py
├── pyproject.toml
├── src/
│   └── smolagents/
│       ├── __init__.py
│       ├── _function_type_hints_utils.py
│       ├── agent_types.py
│       ├── agents.py
│       ├── cli.py
│       ├── default_tools.py
│       ├── gradio_ui.py
│       ├── local_python_executor.py
│       ├── mcp_client.py
│       ├── memory.py
│       ├── models.py
│       ├── monitoring.py
│       ├── prompts/
│       │   ├── code_agent.yaml
│       │   ├── structured_code_agent.yaml
│       │   └── toolcalling_agent.yaml
│       ├── remote_executors.py
│       ├── serialization.py
│       ├── tool_validation.py
│       ├── tools.py
│       ├── utils.py
│       └── vision_web_browser.py
└── tests/
    ├── __init__.py
    ├── conftest.py
    ├── fixtures/
    │   ├── agents.py
    │   └── tools.py
    ├── test_agents.py
    ├── test_all_docs.py
    ├── test_cli.py
    ├── test_default_tools.py
    ├── test_final_answer.py
    ├── test_function_type_hints_utils.py
    ├── test_gradio_ui.py
    ├── test_import.py
    ├── test_local_python_executor.py
    ├── test_mcp_client.py
    ├── test_memory.py
    ├── test_models.py
    ├── test_monitoring.py
    ├── test_remote_executors.py
    ├── test_search.py
    ├── test_serialization.py
    ├── test_telemetry.py
    ├── test_tool_validation.py
    ├── test_tools.py
    ├── test_types.py
    ├── test_utils.py
    ├── test_vision_web_browser.py
    └── utils/
        └── markers.py
Download .txt
SYMBOL INDEX (1426 symbols across 61 files)

FILE: examples/agent_from_any_llm.py
  function get_weather (line 43) | def get_weather(location: str, celsius: bool | None = False) -> str:

FILE: examples/async_agent/main.py
  function get_agent (line 18) | def get_agent():
  function run_agent_in_thread (line 26) | async def run_agent_in_thread(task: str):
  function run_agent_endpoint (line 33) | async def run_agent_endpoint(request: Request):

FILE: examples/multiple_tools.py
  function get_weather (line 16) | def get_weather(location: str, celsius: bool | None = False) -> str:
  function convert_currency (line 52) | def convert_currency(amount: float, from_currency: str, to_currency: str...
  function get_news_headlines (line 88) | def get_news_headlines() -> str:
  function get_joke (line 119) | def get_joke() -> str:
  function get_time_in_timezone (line 148) | def get_time_in_timezone(location: str) -> str:
  function get_random_fact (line 174) | def get_random_fact() -> str:
  function search_wikipedia (line 195) | def search_wikipedia(query: str) -> str:

FILE: examples/open_deep_research/run.py
  function parse_args (line 34) | def parse_args():
  function create_agent (line 60) | def create_agent(model_id="o1"):
  function main (line 114) | def main():

FILE: examples/open_deep_research/run_gaia.py
  function parse_args (line 49) | def parse_args():
  function create_agent_team (line 82) | def create_agent_team(model: Model, token_counts: TokenUsage):
  function load_gaia_dataset (line 137) | def load_gaia_dataset(use_raw_dataset: bool, set_to_run: str) -> dataset...
  function append_answer (line 172) | def append_answer(entry: dict, jsonl_file: str) -> None:
  function answer_single_question (line 181) | def answer_single_question(
  function get_examples_to_answer (line 275) | def get_examples_to_answer(answers_file: str, eval_ds: datasets.Dataset)...
  function main (line 287) | def main():

FILE: examples/open_deep_research/scripts/gaia_scorer.py
  function normalize_number_str (line 6) | def normalize_number_str(number_str: str) -> float:
  function split_string (line 18) | def split_string(
  function is_float (line 26) | def is_float(element: any) -> bool:
  function question_scorer (line 34) | def question_scorer(
  function check_prediction_contains_answer_letters_in_order (line 73) | def check_prediction_contains_answer_letters_in_order(prediction, true_a...
  function check_close_call (line 87) | def check_close_call(prediction, true_answer, is_correct):
  function normalize_str (line 104) | def normalize_str(input_str, remove_punct=True) -> str:

FILE: examples/open_deep_research/scripts/mdconvert.py
  class _CustomMarkdownify (line 37) | class _CustomMarkdownify(markdownify.MarkdownConverter):
    method __init__ (line 47) | def __init__(self, **options: Any):
    method convert_hn (line 52) | def convert_hn(self, n: int, el: Any, text: str, convert_as_inline: bo...
    method convert_a (line 60) | def convert_a(self, el: Any, text: str, convert_as_inline: bool):
    method convert_img (line 92) | def convert_img(self, el: Any, text: str, convert_as_inline: bool) -> ...
    method convert_soup (line 108) | def convert_soup(self, soup: Any) -> str:
  class DocumentConverterResult (line 112) | class DocumentConverterResult:
    method __init__ (line 115) | def __init__(self, title: str | None = None, text_content: str = ""):
  class DocumentConverter (line 120) | class DocumentConverter:
    method convert (line 123) | def convert(self, local_path: str, **kwargs: Any) -> None | DocumentCo...
  class PlainTextConverter (line 127) | class PlainTextConverter(DocumentConverter):
    method convert (line 130) | def convert(self, local_path: str, **kwargs: Any) -> None | DocumentCo...
  class HtmlConverter (line 149) | class HtmlConverter(DocumentConverter):
    method convert (line 152) | def convert(self, local_path: str, **kwargs: Any) -> None | DocumentCo...
    method _convert (line 164) | def _convert(self, html_content: str) -> None | DocumentConverterResult:
  class WikipediaConverter (line 189) | class WikipediaConverter(DocumentConverter):
    method convert (line 192) | def convert(self, local_path: str, **kwargs: Any) -> None | DocumentCo...
  class YouTubeConverter (line 234) | class YouTubeConverter(DocumentConverter):
    method convert (line 237) | def convert(self, local_path: str, **kwargs: Any) -> None | DocumentCo...
    method _get (line 331) | def _get(self, metadata: dict[str, str], keys: list[str], default: str...
    method _findKey (line 337) | def _findKey(self, json: Any, key: str) -> str | None:  # TODO: Fix js...
  class PdfConverter (line 354) | class PdfConverter(DocumentConverter):
    method convert (line 359) | def convert(self, local_path, **kwargs) -> None | DocumentConverterRes...
  class DocxConverter (line 371) | class DocxConverter(HtmlConverter):
    method convert (line 376) | def convert(self, local_path, **kwargs) -> None | DocumentConverterRes...
  class XlsxConverter (line 391) | class XlsxConverter(HtmlConverter):
    method convert (line 396) | def convert(self, local_path, **kwargs) -> None | DocumentConverterRes...
  class PptxConverter (line 415) | class PptxConverter(HtmlConverter):
    method convert (line 420) | def convert(self, local_path, **kwargs) -> None | DocumentConverterRes...
    method _is_picture (line 487) | def _is_picture(self, shape):
    method _is_table (line 495) | def _is_table(self, shape):
  class MediaConverter (line 501) | class MediaConverter(DocumentConverter):
    method _get_metadata (line 506) | def _get_metadata(self, local_path):
  class WavConverter (line 518) | class WavConverter(MediaConverter):
    method convert (line 523) | def convert(self, local_path, **kwargs) -> None | DocumentConverterRes...
    method _transcribe_audio (line 561) | def _transcribe_audio(self, local_path) -> str:
  class Mp3Converter (line 568) | class Mp3Converter(WavConverter):
    method convert (line 573) | def convert(self, local_path, **kwargs) -> None | DocumentConverterRes...
  class ZipConverter (line 631) | class ZipConverter(DocumentConverter):
    method __init__ (line 636) | def __init__(self, extract_dir: str = "downloads"):
    method convert (line 647) | def convert(self, local_path: str, **kwargs: Any) -> None | DocumentCo...
  class ImageConverter (line 679) | class ImageConverter(MediaConverter):
    method convert (line 684) | def convert(self, local_path, **kwargs) -> None | DocumentConverterRes...
    method _get_mlm_description (line 727) | def _get_mlm_description(self, local_path, extension, client, model, p...
  class FileConversionException (line 760) | class FileConversionException(Exception):
  class UnsupportedFormatException (line 764) | class UnsupportedFormatException(Exception):
  class MarkdownConverter (line 768) | class MarkdownConverter:
    method __init__ (line 772) | def __init__(
    method convert (line 804) | def convert(
    method convert_local (line 823) | def convert_local(self, path: str, **kwargs: Any) -> DocumentConverter...
    method convert_stream (line 837) | def convert_stream(self, stream: Any, **kwargs: Any) -> DocumentConver...
    method convert_url (line 870) | def convert_url(self, url: str, **kwargs: Any) -> DocumentConverterRes...
    method convert_response (line 877) | def convert_response(
    method _convert (line 927) | def _convert(self, local_path: str, extensions: list[str | None], **kw...
    method _append_ext (line 972) | def _append_ext(self, extensions, ext):
    method _guess_ext_magic (line 983) | def _guess_ext_magic(self, path):
    method register_page_converter (line 1000) | def register_page_converter(self, converter: DocumentConverter) -> None:

FILE: examples/open_deep_research/scripts/reformulator.py
  function prepare_response (line 8) | def prepare_response(original_task: str, inner_messages, reformulation_m...

FILE: examples/open_deep_research/scripts/run_agents.py
  function serialize_agent_error (line 11) | def serialize_agent_error(obj):
  function get_image_description (line 18) | def get_image_description(file_name: str, question: str, visual_inspecti...
  function get_document_description (line 25) | def get_document_description(file_path: str, question: str, document_ins...
  function get_single_file_description (line 32) | def get_single_file_description(file_path: str, question: str, visual_in...
  function get_zip_description (line 56) | def get_zip_description(file_path: str, question: str, visual_inspection...
  function get_tasks_to_run (line 72) | def get_tasks_to_run(data, total: int, base_filename: Path, tasks_ids: l...

FILE: examples/open_deep_research/scripts/text_inspector_tool.py
  class TextInspectorTool (line 5) | class TextInspectorTool(Tool):
    method __init__ (line 24) | def __init__(self, model: Model = None, text_limit: int = 100000):
    method forward_initial_exam_mode (line 32) | def forward_initial_exam_mode(self, file_path, question):
    method forward (line 76) | def forward(self, file_path, question: str | None = None) -> str:

FILE: examples/open_deep_research/scripts/text_web_browser.py
  class SimpleTextBrowser (line 22) | class SimpleTextBrowser:
    method __init__ (line 25) | def __init__(
    method address (line 51) | def address(self) -> str:
    method set_address (line 55) | def set_address(self, uri_or_path: str, filter_year: int | None = None...
    method viewport (line 82) | def viewport(self) -> str:
    method page_content (line 88) | def page_content(self) -> str:
    method _set_page_content (line 92) | def _set_page_content(self, content: str) -> None:
    method page_down (line 99) | def page_down(self) -> None:
    method page_up (line 102) | def page_up(self) -> None:
    method find_on_page (line 105) | def find_on_page(self, query: str) -> str | None:
    method find_next (line 124) | def find_next(self) -> str | None:
    method _find_next_viewport (line 147) | def _find_next_viewport(self, query: str, starting_viewport: int) -> i...
    method visit_page (line 177) | def visit_page(self, path_or_uri: str, filter_year: int | None = None)...
    method _split_pages (line 182) | def _split_pages(self) -> None:
    method _serpapi_search (line 204) | def _serpapi_search(self, query: str, filter_year: int | None = None) ...
    method _fetch_page (line 263) | def _fetch_page(self, url: str) -> None:
    method _state (line 355) | def _state(self) -> tuple[str, str]:
  class SearchInformationTool (line 373) | class SearchInformationTool(Tool):
    method __init__ (line 384) | def __init__(self, browser):
    method forward (line 388) | def forward(self, query: str, filter_year: int | None = None) -> str:
  class VisitTool (line 394) | class VisitTool(Tool):
    method __init__ (line 400) | def __init__(self, browser=None):
    method forward (line 404) | def forward(self, url: str) -> str:
  class DownloadTool (line 410) | class DownloadTool(Tool):
    method __init__ (line 419) | def __init__(self, browser):
    method forward (line 423) | def forward(self, url: str) -> str:
  class ArchiveSearchTool (line 445) | class ArchiveSearchTool(Tool):
    method __init__ (line 457) | def __init__(self, browser=None):
    method forward (line 461) | def forward(self, url, date) -> str:
  class PageUpTool (line 488) | class PageUpTool(Tool):
    method __init__ (line 494) | def __init__(self, browser=None):
    method forward (line 498) | def forward(self) -> str:
  class PageDownTool (line 504) | class PageDownTool(Tool):
    method __init__ (line 512) | def __init__(self, browser=None):
    method forward (line 516) | def forward(self) -> str:
  class FinderTool (line 522) | class FinderTool(Tool):
    method __init__ (line 533) | def __init__(self, browser=None):
    method forward (line 537) | def forward(self, search_string: str) -> str:
  class FindNextTool (line 550) | class FindNextTool(Tool):
    method __init__ (line 556) | def __init__(self, browser=None):
    method forward (line 560) | def forward(self) -> str:

FILE: examples/open_deep_research/scripts/visual_qa.py
  function process_images_and_text (line 19) | def process_images_and_text(image_path, query, client):
  function encode_image (line 66) | def encode_image(image_path):
  function resize_image (line 96) | def resize_image(image_path):
  class VisualQATool (line 105) | class VisualQATool(Tool):
    method forward (line 119) | def forward(self, image_path: str, question: str | None = None) -> str:
  function visualizer (line 142) | def visualizer(image_path: str, question: str | None = None) -> str:

FILE: examples/plan_customization/plan_customization.py
  function display_plan (line 18) | def display_plan(plan_content):
  function get_user_choice (line 27) | def get_user_choice():
  function get_modified_plan (line 36) | def get_modified_plan(original_plan):
  function interrupt_after_plan (line 62) | def interrupt_after_plan(memory_step, agent):
  function main (line 100) | def main():

FILE: examples/rag.py
  class RetrieverTool (line 29) | class RetrieverTool(Tool):
    method __init__ (line 40) | def __init__(self, docs, **kwargs):
    method forward (line 44) | def forward(self, query: str) -> str:

FILE: examples/rag_using_chromadb.py
  class RetrieverTool (line 71) | class RetrieverTool(Tool):
    method __init__ (line 84) | def __init__(self, vector_store, **kwargs):
    method forward (line 88) | def forward(self, query: str) -> str:

FILE: examples/server/main.py
  function shutdown (line 24) | async def shutdown():
  function homepage (line 28) | async def homepage(request):
  function chat (line 197) | async def chat(request):

FILE: examples/smolagents_benchmark/run.py
  function parse_arguments (line 33) | def parse_arguments():
  function load_eval_dataset (line 91) | def load_eval_dataset(eval_dataset):
  function serialize_agent_error (line 103) | def serialize_agent_error(obj):
  function append_answer (line 110) | def append_answer(entry: dict, jsonl_file: str) -> None:
  function answer_single_question (line 125) | def answer_single_question(example, model, answers_file, action_type):
  function answer_questions (line 188) | def answer_questions(

FILE: examples/structured_output_tool.py
  function weather_server_script (line 22) | def weather_server_script() -> str:
  function main (line 55) | def main() -> None:

FILE: examples/text_to_sql.py
  function sql_engine (line 51) | def sql_engine(query: str) -> str:

FILE: src/smolagents/_function_type_hints_utils.py
  function get_package_name (line 46) | def get_package_name(import_name: str) -> str:
  function get_imports (line 59) | def get_imports(code: str) -> list[str]:
  class TypeHintParsingException (line 89) | class TypeHintParsingException(Exception):
  class DocstringParsingException (line 93) | class DocstringParsingException(Exception):
  function get_json_schema (line 97) | def get_json_schema(func: Callable) -> dict:
  function _parse_google_format_docstring (line 256) | def _parse_google_format_docstring(
  function _convert_type_hints_to_json_schema (line 291) | def _convert_type_hints_to_json_schema(func: Callable, error_on_missing_...
  function _parse_type_hint (line 326) | def _parse_type_hint(hint: type) -> dict:
  function _parse_union_type (line 387) | def _parse_union_type(args: tuple[Any, ...]) -> dict:
  function _get_json_schema_type (line 415) | def _get_json_schema_type(param_type: type) -> dict[str, str]:

FILE: src/smolagents/agent_types.py
  class AgentType (line 32) | class AgentType:
    method __init__ (line 43) | def __init__(self, value):
    method __str__ (line 46) | def __str__(self):
    method to_raw (line 49) | def to_raw(self):
    method to_string (line 55) | def to_string(self) -> str:
  class AgentText (line 62) | class AgentText(AgentType, str):
    method to_raw (line 67) | def to_raw(self):
    method to_string (line 70) | def to_string(self):
  class AgentImage (line 74) | class AgentImage(AgentType, PIL.Image.Image):
    method __init__ (line 79) | def __init__(self, value):
    method _ipython_display_ (line 111) | def _ipython_display_(self, include=None, exclude=None):
    method to_raw (line 119) | def to_raw(self):
    method to_string (line 136) | def to_string(self):
    method save (line 164) | def save(self, output_bytes, format: str = None, **params):
  class AgentAudio (line 176) | class AgentAudio(AgentType, str):
    method __init__ (line 181) | def __init__(self, value, samplerate=16_000):
    method _ipython_display_ (line 208) | def _ipython_display_(self, include=None, exclude=None):
    method to_raw (line 216) | def to_raw(self):
    method to_string (line 237) | def to_string(self):
  function handle_agent_input_types (line 257) | def handle_agent_input_types(*args, **kwargs):
  function handle_agent_output_types (line 263) | def handle_agent_output_types(output: Any, output_type: str | None = Non...

FILE: src/smolagents/agents.py
  function populate_template (line 102) | def populate_template(template: str, variables: dict[str, Any]) -> str:
  class ActionOutput (line 111) | class ActionOutput:
  class ToolOutput (line 117) | class ToolOutput:
  class PlanningPromptTemplate (line 125) | class PlanningPromptTemplate(TypedDict):
  class ManagedAgentPromptTemplate (line 140) | class ManagedAgentPromptTemplate(TypedDict):
  class FinalAnswerPromptTemplate (line 153) | class FinalAnswerPromptTemplate(TypedDict):
  class PromptTemplates (line 166) | class PromptTemplates(TypedDict):
  class RunResult (line 196) | class RunResult:
    method __init__ (line 217) | def __init__(self, output=None, state=None, steps=None, token_usage=No...
    method messages (line 237) | def messages(self):
    method dict (line 246) | def dict(self):
  class MultiStepAgent (line 268) | class MultiStepAgent(ABC):
    method __init__ (line 294) | def __init__(
    method system_prompt (line 355) | def system_prompt(self) -> str:
    method system_prompt (line 359) | def system_prompt(self, value: str):
    method _validate_name (line 364) | def _validate_name(self, name: str | None) -> str | None:
    method _setup_managed_agents (line 369) | def _setup_managed_agents(self, managed_agents: list | None = None) ->...
    method _setup_tools (line 389) | def _setup_tools(self, tools, add_base_tools):
    method _validate_tools_and_managed_agents (line 404) | def _validate_tools_and_managed_agents(self, tools, managed_agents):
    method _setup_step_callbacks (line 416) | def _setup_step_callbacks(self, step_callbacks):
    method run (line 436) | def run(
    method _run_stream (line 540) | def _run_stream(
    method _validate_final_answer (line 613) | def _validate_final_answer(self, final_answer: Any):
    method _finalize_step (line 620) | def _finalize_step(self, memory_step: ActionStep | PlanningStep | Fina...
    method _handle_max_steps_reached (line 625) | def _handle_max_steps_reached(self, task: str) -> Any:
    method _generate_planning_step (line 639) | def _generate_planning_step(
    method initialize_system_prompt (line 750) | def initialize_system_prompt(self) -> str:
    method interrupt (line 754) | def interrupt(self):
    method write_memory_to_messages (line 758) | def write_memory_to_messages(
    method _step_stream (line 772) | def _step_stream(
    method step (line 782) | def step(self, memory_step: ActionStep) -> Any:
    method extract_action (line 789) | def extract_action(self, model_output: str, split_token: str) -> tuple...
    method provide_final_answer (line 810) | def provide_final_answer(self, task: str) -> ChatMessage:
    method visualize (line 855) | def visualize(self):
    method replay (line 859) | def replay(self, detailed: bool = False):
    method __call__ (line 868) | def __call__(self, task: str, **kwargs):
    method save (line 892) | def save(self, output_dir: str | Path, relative_path: str | None = None):
    method to_dict (line 970) | def to_dict(self) -> dict[str, Any]:
    method from_dict (line 1011) | def from_dict(cls, agent_dict: dict[str, Any], **kwargs) -> "MultiStep...
    method from_hub (line 1065) | def from_hub(
    method from_folder (line 1119) | def from_folder(cls, folder: str | Path, **kwargs):
    method push_to_hub (line 1160) | def push_to_hub(
  class ToolCallingAgent (line 1215) | class ToolCallingAgent(MultiStepAgent):
    method __init__ (line 1231) | def __init__(
    method tools_and_managed_agents (line 1261) | def tools_and_managed_agents(self):
    method initialize_system_prompt (line 1265) | def initialize_system_prompt(self) -> str:
    method _step_stream (line 1276) | def _step_stream(
    method process_tool_calls (line 1361) | def process_tool_calls(
    method _substitute_state_variables (line 1444) | def _substitute_state_variables(self, arguments: dict[str, str] | str)...
    method execute_tool_call (line 1453) | def execute_tool_call(self, tool_name: str, arguments: dict[str, str] ...
  class CodeAgent (line 1505) | class CodeAgent(MultiStepAgent):
    method __init__ (line 1527) | def __init__(
    method __enter__ (line 1587) | def __enter__(self):
    method __exit__ (line 1590) | def __exit__(self, exc_type, exc_value, traceback):
    method cleanup (line 1593) | def cleanup(self):
    method create_python_executor (line 1598) | def create_python_executor(self) -> PythonExecutor:
    method initialize_system_prompt (line 1621) | def initialize_system_prompt(self) -> str:
    method _step_stream (line 1639) | def _step_stream(
    method to_dict (line 1767) | def to_dict(self) -> dict[str, Any]:
    method from_dict (line 1781) | def from_dict(cls, agent_dict: dict[str, Any], **kwargs) -> "CodeAgent":

FILE: src/smolagents/cli.py
  function parse_arguments (line 45) | def parse_arguments():
  function interactive_mode (line 110) | def interactive_mode():
  function load_model (line 188) | def load_model(
  function run_smolagent (line 219) | def run_smolagent(
  function main (line 262) | def main() -> None:

FILE: src/smolagents/default_tools.py
  class PreTool (line 30) | class PreTool:
  class PythonInterpreterTool (line 39) | class PythonInterpreterTool(Tool):
    method __init__ (line 50) | def __init__(self, *args, authorized_imports=None, timeout_seconds=MAX...
    method forward (line 69) | def forward(self, code: str) -> str:
  class FinalAnswerTool (line 83) | class FinalAnswerTool(Tool):
    method forward (line 89) | def forward(self, answer: Any) -> Any:
  class UserInputTool (line 93) | class UserInputTool(Tool):
    method forward (line 99) | def forward(self, question):
  class DuckDuckGoSearchTool (line 104) | class DuckDuckGoSearchTool(Tool):
    method __init__ (line 126) | def __init__(self, max_results: int = 10, rate_limit: float | None = 1...
    method forward (line 140) | def forward(self, query: str) -> str:
    method _enforce_rate_limit (line 148) | def _enforce_rate_limit(self) -> None:
  class GoogleSearchTool (line 162) | class GoogleSearchTool(Tool):
    method __init__ (line 175) | def __init__(self, provider: str = "serpapi"):
    method forward (line 190) | def forward(self, query: str, filter_year: int | None = None) -> str:
  class ApiWebSearchTool (line 249) | class ApiWebSearchTool(Tool):
    method __init__ (line 278) | def __init__(
    method _enforce_rate_limit (line 299) | def _enforce_rate_limit(self) -> None:
    method forward (line 312) | def forward(self, query: str) -> str:
    method extract_results (line 323) | def extract_results(self, data: dict) -> list:
    method format_markdown (line 331) | def format_markdown(self, results: list) -> str:
  class WebSearchTool (line 342) | class WebSearchTool(Tool):
    method __init__ (line 348) | def __init__(self, max_results: int = 10, engine: str = "duckduckgo"):
    method forward (line 353) | def forward(self, query: str) -> str:
    method search (line 359) | def search(self, query: str) -> list:
    method parse_results (line 367) | def parse_results(self, results: list) -> str:
    method search_duckduckgo (line 372) | def search_duckduckgo(self, query: str) -> list:
    method _create_duckduckgo_parser (line 385) | def _create_duckduckgo_parser(self):
    method search_bing (line 431) | def search_bing(self, query: str) -> list:
  class VisitWebpageTool (line 454) | class VisitWebpageTool(Tool):
    method __init__ (line 467) | def __init__(self, max_output_length: int = 40000):
    method _truncate_content (line 471) | def _truncate_content(self, content: str, max_length: int) -> str:
    method forward (line 478) | def forward(self, url: str) -> str:
  class WikipediaSearchTool (line 510) | class WikipediaSearchTool(Tool):
    method __init__ (line 550) | def __init__(
    method forward (line 586) | def forward(self, query: str) -> str:
  class SpeechToTextTool (line 609) | class SpeechToTextTool(PipelineTool):
    method __new__ (line 621) | def __new__(cls, *args, **kwargs):
    method encode (line 628) | def encode(self, audio):
    method forward (line 634) | def forward(self, inputs):
    method decode (line 637) | def decode(self, outputs):

FILE: src/smolagents/gradio_ui.py
  function get_step_footnote_content (line 29) | def get_step_footnote_content(step_log: ActionStep | PlanningStep, step_...
  function _clean_model_output (line 39) | def _clean_model_output(model_output: str) -> str:
  function _format_code_content (line 59) | def _format_code_content(content: str) -> str:
  function _process_action_step (line 80) | def _process_action_step(step_log: ActionStep, skip_model_outputs: bool ...
  function _process_planning_step (line 166) | def _process_planning_step(step_log: PlanningStep, skip_model_outputs: b...
  function _process_final_answer_step (line 189) | def _process_final_answer_step(step_log: FinalAnswerStep) -> Generator:
  function pull_messages_from_step (line 226) | def pull_messages_from_step(step_log: ActionStep | PlanningStep | FinalA...
  function stream_to_gradio (line 248) | def stream_to_gradio(
  class GradioUI (line 279) | class GradioUI:
    method __init__ (line 310) | def __init__(self, agent: MultiStepAgent, file_upload_folder: str | No...
    method _save_uploaded_file (line 324) | def _save_uploaded_file(self, file_path: str) -> str:
    method upload_file (line 335) | def upload_file(self, file, file_uploads_log: list, allowed_file_types...
    method _process_message (line 362) | def _process_message(self, message: str | dict) -> tuple[str, list[str...
    method _stream_response (line 378) | def _stream_response(self, message: str | dict, history: list[dict]) -...
    method launch (line 422) | def launch(self, share: bool = True, **kwargs):
    method create_app (line 432) | def create_app(self):

FILE: src/smolagents/local_python_executor.py
  class InterpreterError (line 42) | class InterpreterError(ValueError):
  function custom_print (line 64) | def custom_print(*args):
  function nodunder_getattr (line 68) | def nodunder_getattr(obj, name, default=None):
  function check_safer_result (line 156) | def check_safer_result(result: Any, static_tools: dict[str, Callable] = ...
  function safer_eval (line 185) | def safer_eval(func: Callable):
  function safer_func (line 211) | def safer_func(
  class PrintContainer (line 240) | class PrintContainer:
    method __init__ (line 241) | def __init__(self):
    method append (line 244) | def append(self, text):
    method __iadd__ (line 248) | def __iadd__(self, other):
    method __str__ (line 253) | def __str__(self):
    method __repr__ (line 257) | def __repr__(self):
    method __len__ (line 261) | def __len__(self):
  class BreakException (line 266) | class BreakException(Exception):
  class ContinueException (line 270) | class ContinueException(Exception):
  class ReturnException (line 274) | class ReturnException(Exception):
    method __init__ (line 275) | def __init__(self, value):
  class ExecutionTimeoutError (line 279) | class ExecutionTimeoutError(Exception):
  function timeout (line 285) | def timeout(timeout_seconds: int):
  function get_iterable (line 323) | def get_iterable(obj):
  function fix_final_answer_code (line 332) | def fix_final_answer_code(code: str) -> str:
  function build_import_tree (line 360) | def build_import_tree(authorized_imports: list[str]) -> dict[str, Any]:
  function check_import_authorized (line 372) | def check_import_authorized(import_to_check: str, authorized_imports: li...
  function evaluate_attribute (line 383) | def evaluate_attribute(
  function evaluate_unaryop (line 396) | def evaluate_unaryop(
  function evaluate_lambda (line 416) | def evaluate_lambda(
  function evaluate_while (line 440) | def evaluate_while(
  function create_function (line 462) | def create_function(
  function evaluate_function_def (line 529) | def evaluate_function_def(
  function evaluate_class_def (line 540) | def evaluate_class_def(
  function evaluate_annassign (line 621) | def evaluate_annassign(
  function evaluate_augassign (line 638) | def evaluate_augassign(
  function evaluate_boolop (line 710) | def evaluate_boolop(
  function evaluate_binop (line 730) | def evaluate_binop(
  function evaluate_assign (line 770) | def evaluate_assign(
  function set_value (line 794) | def set_value(
  function evaluate_call (line 825) | def evaluate_call(
  function evaluate_subscript (line 921) | def evaluate_subscript(
  function evaluate_name (line 941) | def evaluate_name(
  function evaluate_condition (line 962) | def evaluate_condition(
  function evaluate_if (line 1004) | def evaluate_if(
  function evaluate_for (line 1026) | def evaluate_for(
  function _evaluate_comprehensions (line 1056) | def _evaluate_comprehensions(
  function evaluate_listcomp (line 1099) | def evaluate_listcomp(
  function evaluate_setcomp (line 1118) | def evaluate_setcomp(
  function evaluate_dictcomp (line 1137) | def evaluate_dictcomp(
  function evaluate_try (line 1159) | def evaluate_try(
  function evaluate_raise (line 1194) | def evaluate_raise(
  function evaluate_assert (line 1218) | def evaluate_assert(
  function evaluate_with (line 1236) | def evaluate_with(
  function get_safe_module (line 1271) | def get_safe_module(raw_module, authorized_imports, visited=None):
  function evaluate_import (line 1309) | def evaluate_import(expression, state, authorized_imports):
  function evaluate_generatorexp (line 1345) | def evaluate_generatorexp(
  function evaluate_delete (line 1380) | def evaluate_delete(
  function evaluate_ast (line 1417) | def evaluate_ast(
  class FinalAnswerException (line 1572) | class FinalAnswerException(BaseException):
    method __init__ (line 1579) | def __init__(self, value):
  function evaluate_python_code (line 1583) | def evaluate_python_code(
  class CodeOutput (line 1671) | class CodeOutput:
  class PythonExecutor (line 1677) | class PythonExecutor(ABC):
    method send_tools (line 1679) | def send_tools(self, tools: dict[str, Tool]) -> None: ...
    method send_variables (line 1682) | def send_variables(self, variables: dict[str, Any]) -> None: ...
    method __call__ (line 1685) | def __call__(self, code_action: str) -> CodeOutput: ...
  class LocalPythonExecutor (line 1688) | class LocalPythonExecutor(PythonExecutor):
    method __init__ (line 1708) | def __init__(
    method _check_authorized_imports_are_installed (line 1727) | def _check_authorized_imports_are_installed(self):
    method __call__ (line 1747) | def __call__(self, code_action: str) -> CodeOutput:
    method send_variables (line 1760) | def send_variables(self, variables: dict[str, Any]):
    method send_tools (line 1763) | def send_tools(self, tools: dict[str, Tool]):

FILE: src/smolagents/mcp_client.py
  class MCPClient (line 33) | class MCPClient:
    method __init__ (line 85) | def __init__(
    method connect (line 124) | def connect(self):
    method disconnect (line 128) | def disconnect(
    method get_tools (line 137) | def get_tools(self) -> list[Tool]:
    method __enter__ (line 156) | def __enter__(self) -> list[Tool]:
    method __exit__ (line 164) | def __exit__(

FILE: src/smolagents/memory.py
  class ToolCall (line 25) | class ToolCall:
    method dict (line 30) | def dict(self):
  class MemoryStep (line 42) | class MemoryStep:
    method dict (line 43) | def dict(self):
    method to_messages (line 46) | def to_messages(self, summary_mode: bool = False) -> list[ChatMessage]:
  class ActionStep (line 51) | class ActionStep(MemoryStep):
    method dict (line 66) | def dict(self):
    method to_messages (line 92) | def to_messages(self, summary_mode: bool = False) -> list[ChatMessage]:
  class PlanningStep (line 154) | class PlanningStep(MemoryStep):
    method dict (line 161) | def dict(self):
    method to_messages (line 174) | def to_messages(self, summary_mode: bool = False) -> list[ChatMessage]:
  class TaskStep (line 187) | class TaskStep(MemoryStep):
    method to_messages (line 191) | def to_messages(self, summary_mode: bool = False) -> list[ChatMessage]:
  class SystemPromptStep (line 200) | class SystemPromptStep(MemoryStep):
    method to_messages (line 203) | def to_messages(self, summary_mode: bool = False) -> list[ChatMessage]:
  class FinalAnswerStep (line 210) | class FinalAnswerStep(MemoryStep):
  class AgentMemory (line 214) | class AgentMemory:
    method __init__ (line 228) | def __init__(self, system_prompt: str):
    method reset (line 232) | def reset(self):
    method get_succinct_steps (line 236) | def get_succinct_steps(self) -> list[dict]:
    method get_full_steps (line 242) | def get_full_steps(self) -> list[dict]:
    method replay (line 248) | def replay(self, logger: AgentLogger, detailed: bool = False):
    method return_full_code (line 273) | def return_full_code(self) -> str:
  class CallbackRegistry (line 280) | class CallbackRegistry:
    method __init__ (line 286) | def __init__(self):
    method register (line 289) | def register(self, step_cls: Type[MemoryStep], callback: Callable):
    method callback (line 300) | def callback(self, memory_step, **kwargs):

FILE: src/smolagents/models.py
  function get_dict_from_nested_dataclasses (line 70) | def get_dict_from_nested_dataclasses(obj, ignore_key=None):
  function remove_content_after_stop_sequences (line 79) | def remove_content_after_stop_sequences(content: str | None, stop_sequen...
  class ChatMessageToolCallFunction (line 95) | class ChatMessageToolCallFunction:
  class ChatMessageToolCall (line 102) | class ChatMessageToolCall:
    method __str__ (line 107) | def __str__(self) -> str:
  class MessageRole (line 111) | class MessageRole(str, Enum):
    method roles (line 119) | def roles(cls):
  class ChatMessage (line 124) | class ChatMessage:
    method __post_init__ (line 131) | def __post_init__(self) -> None:
    method model_dump_json (line 136) | def model_dump_json(self):
    method from_dict (line 140) | def from_dict(cls, data: dict, raw: Any | None = None, token_usage: To...
    method dict (line 157) | def dict(self):
    method render_as_markdown (line 160) | def render_as_markdown(self) -> str:
  function _coerce_tool_call (line 172) | def _coerce_tool_call(tool_call: Any) -> ChatMessageToolCall:
  function parse_json_if_needed (line 193) | def parse_json_if_needed(arguments: str | dict) -> str | dict:
  class ChatMessageToolCallStreamDelta (line 204) | class ChatMessageToolCallStreamDelta:
  class ChatMessageStreamDelta (line 214) | class ChatMessageStreamDelta:
  function agglomerate_stream_deltas (line 220) | def agglomerate_stream_deltas(
  function get_tool_json_schema (line 288) | def get_tool_json_schema(tool: Tool) -> dict:
  function get_clean_message_list (line 332) | def get_clean_message_list(
  function get_tool_call_from_text (line 400) | def get_tool_call_from_text(text: str, tool_name_key: str, tool_argument...
  function supports_stop_parameter (line 418) | def supports_stop_parameter(model_id: str) -> bool:
  class _ParameterRemove (line 441) | class _ParameterRemove:
    method __repr__ (line 444) | def __repr__(self):
  class Model (line 452) | class Model:
    method __init__ (line 484) | def __init__(
    method supports_stop_parameter (line 499) | def supports_stop_parameter(self) -> bool:
    method _prepare_completion_kwargs (line 502) | def _prepare_completion_kwargs(
    method generate (line 553) | def generate(
    method __call__ (line 580) | def __call__(self, *args, **kwargs):
    method parse_tool_calls (line 583) | def parse_tool_calls(self, message: ChatMessage) -> ChatMessage:
    method to_dict (line 596) | def to_dict(self) -> dict:
    method from_dict (line 629) | def from_dict(cls, model_dictionary: dict[str, Any]) -> "Model":
  class VLLMModel (line 633) | class VLLMModel(Model):
    method __init__ (line 648) | def __init__(
    method cleanup (line 670) | def cleanup(self):
    method generate (line 687) | def generate(
  class MLXModel (line 751) | class MLXModel(Model):
    method __init__ (line 791) | def __init__(
    method generate (line 816) | def generate(
  class TransformersModel (line 860) | class TransformersModel(Model):
    method __init__ (line 906) | def __init__(
    method make_stopping_criteria (line 980) | def make_stopping_criteria(self, stop_sequences: list[str], tokenizer)...
    method _prepare_completion_args (line 1001) | def _prepare_completion_args(
    method generate (line 1052) | def generate(
    method generate_stream (line 1093) | def generate_stream(
  class ApiModel (line 1138) | class ApiModel(Model):
    method __init__ (line 1161) | def __init__(
    method create_client (line 1185) | def create_client(self):
    method _apply_rate_limit (line 1189) | def _apply_rate_limit(self):
  function is_rate_limit_error (line 1194) | def is_rate_limit_error(exception: BaseException) -> bool:
  class LiteLLMModel (line 1205) | class LiteLLMModel(ApiModel):
    method __init__ (line 1224) | def __init__(
    method create_client (line 1255) | def create_client(self):
    method generate (line 1266) | def generate(
    method generate_stream (line 1309) | def generate_stream(
  class LiteLLMRouterModel (line 1363) | class LiteLLMRouterModel(LiteLLMModel):
    method __init__ (line 1426) | def __init__(
    method create_client (line 1446) | def create_client(self):
  class InferenceClientModel (line 1456) | class InferenceClientModel(ApiModel):
    method __init__ (line 1514) | def __init__(
    method create_client (line 1547) | def create_client(self):
    method generate (line 1553) | def generate(
    method generate_stream (line 1591) | def generate_stream(
  class OpenAIModel (line 1646) | class OpenAIModel(ApiModel):
    method __init__ (line 1671) | def __init__(
    method create_client (line 1697) | def create_client(self):
    method generate_stream (line 1707) | def generate_stream(
    method generate (line 1761) | def generate(
  class AzureOpenAIModel (line 1799) | class AzureOpenAIModel(OpenAIModel):
    method __init__ (line 1820) | def __init__(
    method create_client (line 1845) | def create_client(self):
  class AmazonBedrockModel (line 1859) | class AmazonBedrockModel(ApiModel):
    method __init__ (line 1940) | def __init__(
    method _prepare_completion_kwargs (line 1968) | def _prepare_completion_kwargs(
    method create_client (line 2010) | def create_client(self):
    method generate (line 2020) | def generate(

FILE: src/smolagents/monitoring.py
  class TokenUsage (line 37) | class TokenUsage:
    method __post_init__ (line 46) | def __post_init__(self):
    method dict (line 49) | def dict(self):
  class Timing (line 58) | class Timing:
    method duration (line 67) | def duration(self):
    method dict (line 70) | def dict(self):
    method __repr__ (line 77) | def __repr__(self) -> str:
  class Monitor (line 81) | class Monitor:
    method __init__ (line 82) | def __init__(self, tracked_model, logger):
    method get_total_token_counts (line 89) | def get_total_token_counts(self) -> TokenUsage:
    method reset (line 95) | def reset(self):
    method update_metrics (line 100) | def update_metrics(self, step_log):
  class LogLevel (line 120) | class LogLevel(IntEnum):
  class AgentLogger (line 130) | class AgentLogger:
    method __init__ (line 131) | def __init__(self, level: LogLevel = LogLevel.INFO, console: Console |...
    method log (line 138) | def log(self, *args, level: int | str | LogLevel = LogLevel.INFO, **kw...
    method log_error (line 149) | def log_error(self, error_message: str) -> None:
    method log_markdown (line 152) | def log_markdown(self, content: str, title: str | None = None, level=L...
    method log_code (line 174) | def log_code(self, title: str, content: str, level: int = LogLevel.INF...
    method log_rule (line 190) | def log_rule(self, title: str, level: int = LogLevel.INFO) -> None:
    method log_task (line 200) | def log_task(self, content: str, subtitle: str, title: str | None = No...
    method log_messages (line 220) | def log_messages(self, messages: list[dict], level: LogLevel = LogLeve...
    method visualize_agent_tree (line 232) | def visualize_agent_tree(self, agent):

FILE: src/smolagents/remote_executors.py
  class RemotePythonExecutor (line 56) | class RemotePythonExecutor(PythonExecutor):
    method __init__ (line 73) | def __init__(
    method run_code_raise_errors (line 85) | def run_code_raise_errors(self, code: str) -> CodeOutput:
    method send_tools (line 97) | def send_tools(self, tools: dict[str, Tool]):
    method send_variables (line 118) | def send_variables(self, variables: dict[str, Any]):
    method __call__ (line 136) | def __call__(self, code_action: str) -> CodeOutput:
    method install_packages (line 140) | def install_packages(self, additional_imports: list[str]):
    method _patch_final_answer_with_exception (line 146) | def _patch_final_answer_with_exception(self, final_answer_tool: FinalA...
    method _deserialize_final_answer (line 310) | def _deserialize_final_answer(encoded_value: str, allow_pickle: bool =...
  class E2BExecutor (line 338) | class E2BExecutor(RemotePythonExecutor):
    method __init__ (line 354) | def __init__(
    method run_code_raise_errors (line 377) | def run_code_raise_errors(self, code: str) -> CodeOutput:
    method cleanup (line 441) | def cleanup(self):
  function _websocket_send_execute_request (line 453) | def _websocket_send_execute_request(code: str, ws) -> str:
  function _websocket_run_code_raise_errors (line 484) | def _websocket_run_code_raise_errors(
  function _create_kernel_http (line 527) | def _create_kernel_http(crate_kernel_endpoint: str, logger, headers: Opt...
  class DockerExecutor (line 546) | class DockerExecutor(RemotePythonExecutor):
    method __init__ (line 567) | def __init__(
    method run_code_raise_errors (line 674) | def run_code_raise_errors(self, code: str) -> CodeOutput:
    method cleanup (line 689) | def cleanup(self):
    method delete (line 701) | def delete(self):
    method _wait_for_server (line 705) | def _wait_for_server(self, token: str):
  class ModalExecutor (line 721) | class ModalExecutor(RemotePythonExecutor):
    method __init__ (line 743) | def __init__(
    method run_code_raise_errors (line 808) | def run_code_raise_errors(self, code: str) -> CodeOutput:
    method cleanup (line 823) | def cleanup(self):
    method delete (line 828) | def delete(self):
    method _wait_for_server (line 832) | def _wait_for_server(self, host: str, token: str):
    method _strip_ansi_colors (line 849) | def _strip_ansi_colors(cls, text: str) -> str:
  class BlaxelExecutor (line 854) | class BlaxelExecutor(RemotePythonExecutor):
    method __init__ (line 877) | def __init__(
    method _create_sandbox (line 949) | def _create_sandbox(config):
    method run_code_raise_errors (line 958) | def run_code_raise_errors(self, code: str) -> CodeOutput:
    method install_packages (line 977) | def install_packages(self, additional_imports: list[str]) -> list[str]:
    method _delete_sandbox (line 1036) | def _delete_sandbox(self):
    method cleanup (line 1044) | def cleanup(self):
    method delete (line 1062) | def delete(self):
    method __del__ (line 1066) | def __del__(self):
  class WasmExecutor (line 1074) | class WasmExecutor(RemotePythonExecutor):
    method __init__ (line 1099) | def __init__(
    method _create_deno_runner (line 1160) | def _create_deno_runner(self):
    method _build_js_code (line 1174) | def _build_js_code(self) -> str:
    method _start_deno_server (line 1182) | def _start_deno_server(self):
    method run_code_raise_errors (line 1213) | def run_code_raise_errors(self, code: str) -> CodeOutput:
    method install_packages (line 1274) | def install_packages(self, additional_imports: list[str]) -> list[str]:
    method cleanup (line 1290) | def cleanup(self):
    method delete (line 1309) | def delete(self):

FILE: src/smolagents/serialization.py
  class SerializationError (line 39) | class SerializationError(Exception):
  class SafeSerializer (line 45) | class SafeSerializer:
    method _get_optional_type (line 64) | def _get_optional_type(cls, module: str, attr: str):
    method to_json_safe (line 76) | def to_json_safe(obj: Any) -> Any:
    method from_json_safe (line 174) | def from_json_safe(obj: Any) -> Any:
    method dumps (line 252) | def dumps(obj: Any, allow_pickle: bool = False) -> str:
    method loads (line 295) | def loads(data: str, allow_pickle: bool = False) -> Any:
    method _extract_method_body (line 349) | def _extract_method_body(method) -> str:
    method get_safe_serializer_code (line 377) | def get_safe_serializer_code() -> str:
    method get_deserializer_code (line 452) | def get_deserializer_code(allow_pickle: bool) -> str:

FILE: src/smolagents/tool_validation.py
  class MethodChecker (line 11) | class MethodChecker(ast.NodeVisitor):
    method __init__ (line 18) | def __init__(self, class_attributes: set[str], check_imports: bool = T...
    method visit_arguments (line 30) | def visit_arguments(self, node):
    method visit_Import (line 38) | def visit_Import(self, node):
    method visit_ImportFrom (line 43) | def visit_ImportFrom(self, node):
    method visit_Assign (line 49) | def visit_Assign(self, node):
    method visit_With (line 59) | def visit_With(self, node):
    method visit_ExceptHandler (line 67) | def visit_ExceptHandler(self, node):
    method visit_AnnAssign (line 73) | def visit_AnnAssign(self, node):
    method visit_For (line 80) | def visit_For(self, node):
    method _handle_comprehension_generators (line 90) | def _handle_comprehension_generators(self, generators):
    method visit_ListComp (line 100) | def visit_ListComp(self, node):
    method visit_DictComp (line 105) | def visit_DictComp(self, node):
    method visit_SetComp (line 110) | def visit_SetComp(self, node):
    method visit_Attribute (line 115) | def visit_Attribute(self, node):
    method visit_ClassDef (line 119) | def visit_ClassDef(self, node):
    method visit_Name (line 124) | def visit_Name(self, node):
    method visit_Call (line 140) | def visit_Call(self, node):
  function validate_tool_attributes (line 157) | def validate_tool_attributes(cls, check_imports: bool = True) -> None:

FILE: src/smolagents/tools.py
  function validate_after_init (line 70) | def validate_after_init(cls):
  class BaseTool (line 98) | class BaseTool(ABC):
    method __call__ (line 102) | def __call__(self, *args, **kwargs) -> Any:
  class Tool (line 106) | class Tool(BaseTool):
    method __init__ (line 137) | def __init__(self, *args, **kwargs):
    method __init_subclass__ (line 140) | def __init_subclass__(cls, **kwargs):
    method validate_arguments (line 144) | def validate_arguments(self):
    method forward (line 228) | def forward(self, *args, **kwargs):
    method __call__ (line 231) | def __call__(self, *args, sanitize_inputs_outputs: bool = False, **kwa...
    method setup (line 251) | def setup(self):
    method to_code_prompt (line 258) | def to_code_prompt(self) -> str:
    method to_tool_calling_prompt (line 289) | def to_tool_calling_prompt(self) -> str:
    method to_dict (line 292) | def to_dict(self) -> dict:
    method from_dict (line 368) | def from_dict(cls, tool_dict: dict[str, Any], **kwargs) -> "Tool":
    method save (line 390) | def save(self, output_dir: str | Path, tool_file_name: str = "tool", m...
    method _write_file (line 417) | def _write_file(self, file_path: Path, content: str) -> None:
    method push_to_hub (line 421) | def push_to_hub(
    method _initialize_hub_repo (line 461) | def _initialize_hub_repo(repo_id: str, token: bool | str | None, priva...
    method _prepare_hub_files (line 474) | def _prepare_hub_files(self) -> list:
    method _get_tool_code (line 495) | def _get_tool_code(self) -> str:
    method _get_gradio_app_code (line 499) | def _get_gradio_app_code(self, tool_module_name: str = "tool") -> str:
    method _get_requirements (line 512) | def _get_requirements(self) -> str:
    method from_hub (line 517) | def from_hub(
    method from_code (line 572) | def from_code(cls, tool_code: str, **kwargs):
    method from_space (line 600) | def from_space(
    method from_gradio (line 742) | def from_gradio(gradio_tool):
    method from_langchain (line 763) | def from_langchain(langchain_tool):
  function launch_gradio_demo (line 794) | def launch_gradio_demo(tool: Tool):
  function load_tool (line 840) | def load_tool(
  function add_description (line 882) | def add_description(description):
  class ToolCollection (line 895) | class ToolCollection:
    method __init__ (line 906) | def __init__(self, tools: list[Tool]):
    method from_hub (line 910) | def from_hub(
    method from_mcp (line 951) | def from_mcp(
  function tool (line 1061) | def tool(tool_function: Callable) -> Tool:
  class PipelineTool (line 1171) | class PipelineTool(Tool):
    method __init__ (line 1219) | def __init__(
    method setup (line 1255) | def setup(self):
    method encode (line 1291) | def encode(self, raw_inputs):
    method forward (line 1297) | def forward(self, inputs):
    method decode (line 1306) | def decode(self, outputs):
    method __call__ (line 1312) | def __call__(self, *args, sanitize_inputs_outputs: bool = False, **kwa...
  function get_tools_definition_code (line 1335) | def get_tools_definition_code(tools: dict[str, Tool]) -> str:
  function validate_tool_arguments (line 1361) | def validate_tool_arguments(tool: Tool, arguments: Any) -> None:

FILE: src/smolagents/utils.py
  function _is_package_available (line 45) | def _is_package_available(package_name: str) -> bool:
  function sanitize_for_rich (line 64) | def sanitize_for_rich(value) -> str:
  class AgentError (line 92) | class AgentError(Exception):
    method __init__ (line 95) | def __init__(self, message, logger: "AgentLogger"):
    method dict (line 100) | def dict(self) -> dict[str, str]:
  class AgentParsingError (line 104) | class AgentParsingError(AgentError):
  class AgentExecutionError (line 110) | class AgentExecutionError(AgentError):
  class AgentMaxStepsError (line 116) | class AgentMaxStepsError(AgentError):
  class AgentToolCallError (line 122) | class AgentToolCallError(AgentExecutionError):
  class AgentToolExecutionError (line 128) | class AgentToolExecutionError(AgentExecutionError):
  class AgentGenerationError (line 134) | class AgentGenerationError(AgentError):
  function make_json_serializable (line 140) | def make_json_serializable(obj: Any) -> Any:
  function parse_json_blob (line 166) | def parse_json_blob(json_blob: str) -> tuple[dict[str, str], str]:
  function extract_code_from_text (line 189) | def extract_code_from_text(text: str, code_block_tags: tuple[str, str]) ...
  function parse_code_blobs (line 198) | def parse_code_blobs(text: str, code_block_tags: tuple[str, str]) -> str:
  function truncate_content (line 257) | def truncate_content(content: str, max_length: int = MAX_LENGTH_TRUNCATE...
  class ImportFinder (line 268) | class ImportFinder(ast.NodeVisitor):
    method __init__ (line 269) | def __init__(self):
    method visit_Import (line 272) | def visit_Import(self, node):
    method visit_ImportFrom (line 278) | def visit_ImportFrom(self, node):
  function instance_to_source (line 285) | def instance_to_source(instance, base_cls=None):
  function get_source (line 376) | def get_source(obj) -> str:
  function encode_image_base64 (line 430) | def encode_image_base64(image):
  function make_image_url (line 436) | def make_image_url(base64_image):
  function make_init_file (line 440) | def make_init_file(folder: str | Path):
  function is_valid_name (line 447) | def is_valid_name(name: str) -> bool:
  function create_agent_gradio_app_template (line 490) | def create_agent_gradio_app_template():
  class RateLimiter (line 497) | class RateLimiter:
    method __init__ (line 512) | def __init__(self, requests_per_minute: float | None = None):
    method throttle (line 517) | def throttle(self):
  class Retrying (line 528) | class Retrying:
    method __init__ (line 531) | def __init__(
    method __call__ (line 551) | def __call__(self, fn, *args: Any, **kwargs: Any) -> Any:

FILE: src/smolagents/vision_web_browser.py
  function parse_arguments (line 27) | def parse_arguments():
  function save_screenshot (line 66) | def save_screenshot(memory_step: ActionStep, agent: CodeAgent) -> None:
  function _escape_xpath_string (line 87) | def _escape_xpath_string(s: str) -> str:
  function search_item_ctrl_f (line 106) | def search_item_ctrl_f(text: str, nth_result: int = 1) -> str:
  function go_back (line 125) | def go_back() -> None:
  function close_popups (line 131) | def close_popups() -> str:
  function initialize_driver (line 138) | def initialize_driver():
  function initialize_agent (line 148) | def initialize_agent(model):
  function run_webagent (line 217) | def run_webagent(
  function main (line 240) | def main() -> None:

FILE: tests/conftest.py
  function patch_multi_step_agent_with_suppressed_logging (line 16) | def patch_multi_step_agent_with_suppressed_logging():

FILE: tests/fixtures/agents.py
  function get_agent_dict (line 134) | def get_agent_dict():

FILE: tests/fixtures/tools.py
  function test_tool (line 7) | def test_tool():
  function no_input_tool (line 23) | def no_input_tool():
  function single_input_tool (line 37) | def single_input_tool():
  function multi_input_tool (line 51) | def multi_input_tool():
  function multiline_description_tool (line 68) | def multiline_description_tool():
  function example_tool (line 82) | def example_tool():
  function boolean_default_tool_class (line 96) | def boolean_default_tool_class():
  function boolean_default_tool_function (line 113) | def boolean_default_tool_function():
  function optional_input_tool_class (line 129) | def optional_input_tool_class():
  function optional_input_tool_function (line 148) | def optional_input_tool_function():

FILE: tests/test_agents.py
  class ChoiceDeltaToolCallFunction (line 81) | class ChoiceDeltaToolCallFunction:
  class ChoiceDeltaToolCall (line 87) | class ChoiceDeltaToolCall:
  class ChoiceDelta (line 95) | class ChoiceDelta:
  function get_new_path (line 103) | def get_new_path(suffix="") -> str:
  function agent_logger (line 109) | def agent_logger():
  class FakeToolCallModel (line 115) | class FakeToolCallModel(Model):
    method generate (line 116) | def generate(self, messages, tools_to_call_from=None, stop_sequences=N...
  class FakeToolCallModelImage (line 145) | class FakeToolCallModelImage(Model):
    method generate (line 146) | def generate(self, messages, tools_to_call_from=None, stop_sequences=N...
  class FakeToolCallModelVL (line 176) | class FakeToolCallModelVL(Model):
    method generate (line 177) | def generate(self, messages, tools_to_call_from=None, stop_sequences=N...
  class FakeCodeModel (line 210) | class FakeCodeModel(Model):
    method generate (line 211) | def generate(self, messages, stop_sequences=None):
  class FakeCodeModelImageGeneration (line 235) | class FakeCodeModelImageGeneration(Model):
    method generate (line 236) | def generate(self, messages, stop_sequences=None):
  class FakeCodeModelPlanning (line 260) | class FakeCodeModelPlanning(Model):
    method generate (line 261) | def generate(self, messages, stop_sequences=None):
  class FakeCodeModelError (line 288) | class FakeCodeModelError(Model):
    method generate (line 289) | def generate(self, messages, stop_sequences=None):
  class FakeCodeModelSyntaxError (line 317) | class FakeCodeModelSyntaxError(Model):
    method generate (line 318) | def generate(self, messages, stop_sequences=None):
  class FakeCodeModelImport (line 345) | class FakeCodeModelImport(Model):
    method generate (line 346) | def generate(self, messages, stop_sequences=None):
  class FakeCodeModelFunctionDef (line 359) | class FakeCodeModelFunctionDef(Model):
    method generate (line 360) | def generate(self, messages, stop_sequences=None):
  class FakeCodeModelSingleStep (line 389) | class FakeCodeModelSingleStep(Model):
    method generate (line 390) | def generate(self, messages, stop_sequences=None):
  class FakeCodeModelNoReturn (line 403) | class FakeCodeModelNoReturn(Model):
    method generate (line 404) | def generate(self, messages, stop_sequences=None):
  class TestAgent (line 417) | class TestAgent:
    method test_fake_toolcalling_agent (line 418) | def test_fake_toolcalling_agent(self):
    method test_toolcalling_agent_handles_image_tool_outputs (line 427) | def test_toolcalling_agent_handles_image_tool_outputs(self, shared_dat...
    method test_toolcalling_agent_handles_image_inputs (line 447) | def test_toolcalling_agent_handles_image_inputs(self, shared_datadir):
    method test_fake_code_agent (line 466) | def test_fake_code_agent(self):
    method test_additional_args_added_to_task (line 476) | def test_additional_args_added_to_task(self):
    method test_reset_conversations (line 484) | def test_reset_conversations(self):
    method test_setup_agent_with_empty_toolbox (line 498) | def test_setup_agent_with_empty_toolbox(self):
    method test_fails_max_steps (line 501) | def test_fails_max_steps(self):
    method test_tool_descriptions_get_baked_in_system_prompt (line 522) | def test_tool_descriptions_get_baked_in_system_prompt(self):
    method test_module_imports_get_baked_in_system_prompt (line 532) | def test_module_imports_get_baked_in_system_prompt(self):
    method test_init_agent_with_different_toolsets (line 538) | def test_init_agent_with_different_toolsets(self):
    method test_function_persistence_across_steps (line 562) | def test_function_persistence_across_steps(self):
    method test_init_managed_agent (line 572) | def test_init_managed_agent(self):
    method test_agent_description_gets_correctly_inserted_in_system_prompt (line 577) | def test_agent_description_gets_correctly_inserted_in_system_prompt(se...
    method test_replay_shows_logs (line 590) | def test_replay_shows_logs(self, agent_logger):
    method test_code_nontrivial_final_answer_works (line 615) | def test_code_nontrivial_final_answer_works(self):
    method test_transformers_toolcalling_agent (line 633) | def test_transformers_toolcalling_agent(self):
    method test_final_answer_checks (line 664) | def test_final_answer_checks(self):
    method test_final_answer_checks_with_agent_access (line 686) | def test_final_answer_checks_with_agent_access(self):
    method test_generation_errors_are_raised (line 739) | def test_generation_errors_are_raised(self):
    method test_planning_step_with_injected_memory (line 750) | def test_planning_step_with_injected_memory(self):
  class CustomFinalAnswerTool (line 824) | class CustomFinalAnswerTool(FinalAnswerTool):
    method forward (line 825) | def forward(self, answer) -> str:
  class MockTool (line 829) | class MockTool(Tool):
    method __init__ (line 830) | def __init__(self, name):
    method forward (line 836) | def forward(self):
  class MockAgent (line 840) | class MockAgent:
    method __init__ (line 841) | def __init__(self, name, tools, description="Mock agent description"):
  class DummyMultiStepAgent (line 847) | class DummyMultiStepAgent(MultiStepAgent):
    method step (line 848) | def step(self, memory_step: ActionStep) -> Generator[None]:
    method initialize_system_prompt (line 851) | def initialize_system_prompt(self):
  class FakeLLMModel (line 855) | class FakeLLMModel(Model):
    method __init__ (line 856) | def __init__(self, give_token_usage: bool = True):
    method generate (line 859) | def generate(self, prompt, tools_to_call_from=None, **kwargs):
  class TestRunResult (line 885) | class TestRunResult:
    method test_backward_compatibility (line 886) | def test_backward_compatibility(self):
    method test_no_token_usage (line 927) | def test_no_token_usage(self, agent_class):
    method test_full_result (line 953) | def test_full_result(self, init_return_full_result, run_return_full_re...
  class TestMultiStepAgent (line 973) | class TestMultiStepAgent:
    method test_instantiation_disables_logging_to_terminal (line 974) | def test_instantiation_disables_logging_to_terminal(self):
    method test_instantiation_with_prompt_templates (line 979) | def test_instantiation_with_prompt_templates(self, prompt_templates):
    method test_instantiation_with_final_answer_tool (line 991) | def test_instantiation_with_final_answer_tool(self, tools, expected_fi...
    method test_system_prompt_property (line 996) | def test_system_prompt_property(self):
    method test_setup_step_callbacks (line 1090) | def test_setup_step_callbacks(self, step_callbacks, expected_registry_...
    method test_finalize_step_callbacks_with_list (line 1112) | def test_finalize_step_callbacks_with_list(self):
    method test_finalize_step_callbacks_by_type (line 1147) | def test_finalize_step_callbacks_by_type(self):
    method test_logs_display_thoughts_even_if_error (line 1218) | def test_logs_display_thoughts_even_if_error(self):
    method test_step_number (line 1245) | def test_step_number(self):
    method test_planning_step (line 1292) | def test_planning_step(self, step, expected_messages_list):
    method test_provide_final_answer (line 1387) | def test_provide_final_answer(self, expected_messages_list):
    method test_interrupt (line 1429) | def test_interrupt(self):
    method test_validate_tools_and_managed_agents (line 1486) | def test_validate_tools_and_managed_agents(self, tools, managed_agents...
    method test_from_dict (line 1496) | def test_from_dict(self):
    method test_multiagent_to_dict_from_dict_roundtrip (line 1546) | def test_multiagent_to_dict_from_dict_roundtrip(self):
    method test_from_dict_invalid_model_class (line 1597) | def test_from_dict_invalid_model_class(self):
    method test_from_dict_invalid_agent_class (line 1614) | def test_from_dict_invalid_agent_class(self):
  class TestToolCallingAgent (line 1645) | class TestToolCallingAgent:
    method test_toolcalling_agent_instructions (line 1646) | def test_toolcalling_agent_instructions(self):
    method test_toolcalling_agent_passes_both_tools_and_managed_agents (line 1651) | def test_toolcalling_agent_passes_both_tools_and_managed_agents(self, ...
    method test_toolcalling_agent_api (line 1679) | def test_toolcalling_agent_api(self, mock_inference_client):
    method test_toolcalling_agent_stream_logs_multiple_tool_calls_observations (line 1731) | def test_toolcalling_agent_stream_logs_multiple_tool_calls_observation...
    method test_toolcalling_agent_final_answer_cannot_be_called_with_parallel_tool_calls (line 1816) | def test_toolcalling_agent_final_answer_cannot_be_called_with_parallel...
    method test_toolcalling_agent_api_misformatted_output (line 1891) | def test_toolcalling_agent_api_misformatted_output(self, mock_inferenc...
    method test_change_tools_after_init (line 1920) | def test_change_tools_after_init(self):
    method test_custom_final_answer_with_custom_inputs (line 1945) | def test_custom_final_answer_with_custom_inputs(self, test_tool):
    method test_process_tool_calls (line 2065) | def test_process_tool_calls(self, test_case, test_tool):
  class TestCodeAgent (line 2092) | class TestCodeAgent:
    method test_code_agent_instructions (line 2093) | def test_code_agent_instructions(self):
    method test_call_with_provide_run_summary (line 2105) | def test_call_with_provide_run_summary(self, provide_run_summary):
    method test_code_agent_image_output (line 2123) | def test_code_agent_image_output(self):
    method test_errors_logging (line 2137) | def test_errors_logging(self):
    method test_missing_import_triggers_advice_in_error_log (line 2150) | def test_missing_import_triggers_advice_in_error_log(self):
    method test_errors_show_offending_line_and_error (line 2159) | def test_errors_show_offending_line_and_error(self):
    method test_error_saves_previous_print_outputs (line 2167) | def test_error_saves_previous_print_outputs(self):
    method test_syntax_error_show_offending_lines (line 2172) | def test_syntax_error_show_offending_lines(self):
    method test_end_code_appending (line 2184) | def test_end_code_appending(self):
    method test_change_tools_after_init (line 2212) | def test_change_tools_after_init(self):
    method test_local_python_executor_with_custom_functions (line 2237) | def test_local_python_executor_with_custom_functions(self):
    method test_from_folder (line 2251) | def test_from_folder(self, agent_dict_version, get_agent_dict):
    method test_from_dict (line 2284) | def test_from_dict(self):
    method test_custom_final_answer_with_custom_inputs (line 2346) | def test_custom_final_answer_with_custom_inputs(self):
    method test_use_structured_outputs_internally (line 2364) | def test_use_structured_outputs_internally(self):
  class TestMultiAgents (line 2381) | class TestMultiAgents:
    method test_multiagents_save (line 2382) | def test_multiagents_save(self, tmp_path):
    method test_multiagents (line 2445) | def test_multiagents(self):
  function prompt_templates (line 2574) | def prompt_templates():
  function test_tool_calling_agents_raises_tool_call_error_being_invoked_with_wrong_arguments (line 2596) | def test_tool_calling_agents_raises_tool_call_error_being_invoked_with_w...
  function test_tool_calling_agents_raises_agent_execution_error_when_tool_raises (line 2613) | def test_tool_calling_agents_raises_agent_execution_error_when_tool_rais...

FILE: tests/test_all_docs.py
  class SubprocessCallException (line 31) | class SubprocessCallException(Exception):
  function run_command (line 35) | def run_command(command: list[str], return_stdout=False, env=None):
  class DocCodeExtractor (line 59) | class DocCodeExtractor:
    method extract_python_code (line 63) | def extract_python_code(content: str) -> list[str]:
    method create_test_script (line 70) | def create_test_script(code_blocks: list[str], tmp_dir: str) -> Path:
  class TestDocs (line 84) | class TestDocs:
    method setup_class (line 88) | def setup_class(cls):
    method teardown_class (line 104) | def teardown_class(cls):
    method test_single_doc (line 108) | def test_single_doc(self, doc_path: Path):
    method _setup (line 157) | def _setup(self):
  function pytest_generate_tests (line 166) | def pytest_generate_tests(metafunc):

FILE: tests/test_cli.py
  function set_env_vars (line 11) | def set_env_vars(monkeypatch):
  function test_load_model_openai_model (line 16) | def test_load_model_openai_model(set_env_vars):
  function test_load_model_litellm_model (line 26) | def test_load_model_litellm_model():
  function test_load_model_transformers_model (line 34) | def test_load_model_transformers_model():
  function test_load_model_hf_api_model (line 48) | def test_load_model_hf_api_model(set_env_vars):
  function test_load_model_invalid_model_type (line 57) | def test_load_model_invalid_model_type():
  function test_cli_main (line 62) | def test_cli_main(capsys):
  function test_vision_web_browser_main (line 87) | def test_vision_web_browser_main():

FILE: tests/test_default_tools.py
  class DefaultToolTests (line 33) | class DefaultToolTests(unittest.TestCase):
    method test_visit_webpage (line 34) | def test_visit_webpage(self):
    method test_ddgs_with_kwargs (line 41) | def test_ddgs_with_kwargs(self):
  class TestPythonInterpreterTool (line 46) | class TestPythonInterpreterTool(ToolTesterMixin):
    method setup_method (line 47) | def setup_method(self):
    method test_exact_match_arg (line 51) | def test_exact_match_arg(self):
    method test_exact_match_kwarg (line 55) | def test_exact_match_kwarg(self):
    method test_agent_type_output (line 59) | def test_agent_type_output(self):
    method test_agent_types_inputs (line 65) | def test_agent_types_inputs(self):
    method test_imports_work (line 81) | def test_imports_work(self):
    method test_unauthorized_imports_fail (line 85) | def test_unauthorized_imports_fail(self):
    method test_custom_timeout (line 90) | def test_custom_timeout(self):
    method test_disabled_timeout (line 103) | def test_disabled_timeout(self):
  class TestSpeechToTextTool (line 118) | class TestSpeechToTextTool:
    method test_new_instance (line 119) | def test_new_instance(self):
    method test_initialization (line 127) | def test_initialization(self):
  function test_wikipedia_search (line 145) | def test_wikipedia_search(language, content_type, extract_format, query):

FILE: tests/test_final_answer.py
  class TestFinalAnswerTool (line 28) | class TestFinalAnswerTool(ToolTesterMixin):
    method setup_method (line 29) | def setup_method(self):
    method test_exact_match_arg (line 33) | def test_exact_match_arg(self):
    method test_exact_match_kwarg (line 37) | def test_exact_match_kwarg(self):
    method test_agent_type_output (line 42) | def test_agent_type_output(self, inputs):
    method inputs (line 49) | def inputs(self, shared_datadir):

FILE: tests/test_function_type_hints_utils.py
  function valid_func (line 23) | def valid_func():
  function no_docstring_func (line 42) | def no_docstring_func():
  function missing_arg_doc_func (line 52) | def missing_arg_doc_func():
  function bad_return_func (line 68) | def bad_return_func():
  function complex_types_func (line 84) | def complex_types_func():
  function optional_types_func (line 103) | def optional_types_func():
  function enum_choices_func (line 121) | def enum_choices_func():
  function union_types_func (line 138) | def union_types_func():
  function nested_types_func (line 155) | def nested_types_func():
  function typed_docstring_func (line 172) | def typed_docstring_func():
  function mismatched_types_func (line 190) | def mismatched_types_func():
  function complex_docstring_types_func (line 207) | def complex_docstring_types_func():
  function keywords_in_description_func (line 224) | def keywords_in_description_func():
  class TestGetJsonSchema (line 240) | class TestGetJsonSchema:
    method test_get_json_schema_example (line 241) | def test_get_json_schema_example(self):
    method test_get_json_schema (line 282) | def test_get_json_schema(self, request, fixture_name, should_fail):
    method test_get_json_schema_raises (line 298) | def test_get_json_schema_raises(self, request, fixture_name, should_fa...
    method test_property_types (line 310) | def test_property_types(self, request, fixture_name, expected_properti...
    method test_schema_basic_structure (line 319) | def test_schema_basic_structure(self, valid_func):
    method test_complex_types (line 346) | def test_complex_types(self, complex_types_func):
    method test_optional_types (line 360) | def test_optional_types(self, optional_types_func):
    method test_enum_choices (line 372) | def test_enum_choices(self, enum_choices_func):
    method test_union_types (line 379) | def test_union_types(self, union_types_func):
    method test_nested_types (line 389) | def test_nested_types(self, nested_types_func):
    method test_typed_docstring_parsing (line 395) | def test_typed_docstring_parsing(self, typed_docstring_func):
    method test_mismatched_docstring_types (line 414) | def test_mismatched_docstring_types(self, mismatched_types_func):
    method test_complex_docstring_types (line 422) | def test_complex_docstring_types(self, complex_docstring_types_func):
    method test_type_in_description_handling (line 442) | def test_type_in_description_handling(self, request, fixture_name, exp...
    method test_with_special_words_in_description_func (line 450) | def test_with_special_words_in_description_func(self, keywords_in_desc...
  class TestGetCode (line 455) | class TestGetCode:
    method test_get_imports (line 513) | def test_get_imports(self, code: str, expected: list[str]):

FILE: tests/test_gradio_ui.py
  class GradioUITester (line 31) | class GradioUITester(unittest.TestCase):
    method setUp (line 32) | def setUp(self):
    method tearDown (line 39) | def tearDown(self):
    method test_upload_file_default_types (line 43) | def test_upload_file_default_types(self):
    method test_upload_file_default_types_disallowed (line 57) | def test_upload_file_default_types_disallowed(self):
    method test_upload_file_success (line 70) | def test_upload_file_success(self):
    method test_upload_file_none (line 83) | def test_upload_file_none(self):
    method test_upload_file_invalid_type (line 90) | def test_upload_file_invalid_type(self):
    method test_upload_file_special_chars (line 101) | def test_upload_file_special_chars(self):
    method test_upload_file_custom_types (line 122) | def test_upload_file_custom_types(self):
  class TestStreamToGradio (line 134) | class TestStreamToGradio:
    method test_stream_to_gradio_memory_step (line 138) | def test_stream_to_gradio_memory_step(self, mock_pull_messages):
    method test_stream_to_gradio_stream_delta (line 153) | def test_stream_to_gradio_stream_delta(self):
    method test_stream_to_gradio_multiple_deltas (line 165) | def test_stream_to_gradio_multiple_deltas(self):
    method test_stream_to_gradio_parameters (line 188) | def test_stream_to_gradio_parameters(self, task, task_images, reset_me...
  class TestPullMessagesFromStep (line 209) | class TestPullMessagesFromStep:
    method test_action_step_basic (line 210) | def test_action_step_basic(
    method test_action_step_with_tool_calls (line 236) | def test_action_step_with_tool_calls(self):
    method test_action_step_tool_call_formats (line 258) | def test_action_step_tool_call_formats(self, tool_name, args, expected):
    method test_action_step_with_error (line 277) | def test_action_step_with_error(self):
    method test_action_step_with_images (line 290) | def test_action_step_with_images(self):
    method test_planning_step (line 309) | def test_planning_step(self, skip_model_outputs, expected_messages_len...
    method test_final_answer_step (line 339) | def test_final_answer_step(self, answer_type, answer_value, expected_c...
    method test_final_answer_step_image (line 353) | def test_final_answer_step_image(self):
    method test_final_answer_step_audio (line 362) | def test_final_answer_step_audio(self):
    method test_unsupported_step_type (line 371) | def test_unsupported_step_type(self):

FILE: tests/test_import.py
  function test_import_smolagents_without_extras (line 6) | def test_import_smolagents_without_extras(monkeypatch):

FILE: tests/test_local_python_executor.py
  function add_two (line 48) | def add_two(x):
  class TestEvaluatePythonCode (line 52) | class TestEvaluatePythonCode:
    method assertDictEqualNoPrint (line 53) | def assertDictEqualNoPrint(self, dict1, dict2):
    method test_evaluate_assign (line 58) | def test_evaluate_assign(self):
    method test_assignment_cannot_overwrite_tool (line 77) | def test_assignment_cannot_overwrite_tool(self):
    method test_subscript_call (line 83) | def test_subscript_call(self):
    method test_evaluate_call (line 91) | def test_evaluate_call(self):
    method test_evaluate_call_starred_kwargs (line 163) | def test_evaluate_call_starred_kwargs(self, code, expected_result):
    method test_evaluate_call_starred_kwargs_errors (line 203) | def test_evaluate_call_starred_kwargs_errors(self, code, expected_erro...
    method test_evaluate_class_def (line 209) | def test_evaluate_class_def(self):
    method test_evaluate_class_def_with_assign_attribute_target (line 228) | def test_evaluate_class_def_with_assign_attribute_target(self):
    method test_evaluate_constant (line 250) | def test_evaluate_constant(self):
    method test_evaluate_dict (line 257) | def test_evaluate_dict(self):
    method test_evaluate_expression (line 266) | def test_evaluate_expression(self):
    method test_evaluate_f_string (line 274) | def test_evaluate_f_string(self):
    method test_evaluate_f_string_with_format (line 282) | def test_evaluate_f_string_with_format(self):
    method test_evaluate_f_string_with_complex_format (line 291) | def test_evaluate_f_string_with_complex_format(self):
    method test_evaluate_if (line 307) | def test_evaluate_if(self):
    method test_evaluate_list (line 321) | def test_evaluate_list(self):
    method test_evaluate_name (line 328) | def test_evaluate_name(self):
    method test_evaluate_subscript (line 335) | def test_evaluate_subscript(self):
    method test_subscript_string_with_string_index_raises_appropriate_error (line 355) | def test_subscript_string_with_string_index_raises_appropriate_error(s...
    method test_evaluate_for (line 367) | def test_evaluate_for(self):
    method test_evaluate_binop (line 374) | def test_evaluate_binop(self):
    method test_recursive_function (line 381) | def test_recursive_function(self):
    method test_max_operations (line 392) | def test_max_operations(self):
    method test_operations_count (line 410) | def test_operations_count(self):
    method test_evaluate_string_methods (line 424) | def test_evaluate_string_methods(self):
    method test_evaluate_slicing (line 429) | def test_evaluate_slicing(self):
    method test_access_attributes (line 434) | def test_access_attributes(self):
    method test_list_comprehension (line 442) | def test_list_comprehension(self):
    method test_string_indexing (line 447) | def test_string_indexing(self):
    method test_tuples (line 460) | def test_tuples(self):
    method test_dictcomp (line 513) | def test_dictcomp(self):
    method test_dictcomp_nested (line 529) | def test_dictcomp_nested(self):
    method test_listcomp (line 540) | def test_listcomp(self):
    method test_listcomp_nested (line 545) | def test_listcomp_nested(self):
    method test_setcomp (line 556) | def test_setcomp(self):
    method test_setcomp_nested (line 561) | def test_setcomp_nested(self):
    method test_generatorexp (line 572) | def test_generatorexp(self):
    method test_generatorexp_with_infinite_sequence (line 579) | def test_generatorexp_with_infinite_sequence(self):
    method test_break (line 614) | def test_break(self):
    method test_pass (line 619) | def test_pass(self):
    method test_continue (line 624) | def test_continue(self):
    method test_call_int (line 633) | def test_call_int(self):
    method test_lambda (line 638) | def test_lambda(self):
    method test_tuple_assignment (line 643) | def test_tuple_assignment(self):
    method test_while (line 648) | def test_while(self):
    method test_generator (line 671) | def test_generator(self):
    method test_boolops (line 676) | def test_boolops(self):
    method test_if_conditions (line 713) | def test_if_conditions(self):
    method test_imports (line 721) | def test_imports(self):
    method test_additional_imports (line 765) | def test_additional_imports(self):
    method test_multiple_comparators (line 789) | def test_multiple_comparators(self):
    method test_print_output (line 806) | def test_print_output(self):
    method test_tuple_target_in_iterator (line 833) | def test_tuple_target_in_iterator(self):
    method test_classes (line 838) | def test_classes(self):
    method test_variable_args (line 920) | def test_variable_args(self):
    method test_exceptions (line 931) | def test_exceptions(self):
    method test_print (line 949) | def test_print(self):
    method test_types_as_objects (line 955) | def test_types_as_objects(self):
    method test_tuple_id (line 963) | def test_tuple_id(self):
    method test_nonsimple_augassign (line 972) | def test_nonsimple_augassign(self):
    method test_adding_int_to_list_raises_error (line 992) | def test_adding_int_to_list_raises_error(self):
    method test_error_highlights_correct_line_of_code (line 1000) | def test_error_highlights_correct_line_of_code(self):
    method test_error_type_returned_in_function_call (line 1011) | def test_error_type_returned_in_function_call(self):
    method test_assert (line 1021) | def test_assert(self):
    method test_with_context_manager (line 1030) | def test_with_context_manager(self):
    method test_with_context_manager_enter_returns_different_object (line 1054) | def test_with_context_manager_enter_returns_different_object(self):
    method test_with_context_manager_no_as_clause_exit_called (line 1079) | def test_with_context_manager_no_as_clause_exit_called(self):
    method test_with_exception_suppressed_by_exit (line 1101) | def test_with_exception_suppressed_by_exit(self):
    method test_with_exception_not_suppressed_by_exit (line 1121) | def test_with_exception_not_suppressed_by_exit(self):
    method test_with_multiple_cms_inner_suppresses_outer_sees_no_exception (line 1136) | def test_with_multiple_cms_inner_suppresses_outer_sees_no_exception(se...
    method test_with_multiple_cms_neither_suppresses (line 1161) | def test_with_multiple_cms_neither_suppresses(self):
    method test_with_multiple_cms_outer_suppresses (line 1180) | def test_with_multiple_cms_outer_suppresses(self):
    method test_with_exit_raising_replaces_original_exception (line 1205) | def test_with_exit_raising_replaces_original_exception(self):
    method test_default_arg_in_function (line 1219) | def test_default_arg_in_function(self):
    method test_set (line 1229) | def test_set(self):
    method test_return (line 1241) | def test_return(self):
    method test_nested_for_loop (line 1270) | def test_nested_for_loop(self):
    method test_pandas (line 1286) | def test_pandas(self):
    method test_starred (line 1337) | def test_starred(self):
    method test_for (line 1359) | def test_for(self):
    method test_syntax_error_points_error (line 1374) | def test_syntax_error_points_error(self):
    method test_close_matches_subscript (line 1381) | def test_close_matches_subscript(self):
    method test_dangerous_builtins_calls_are_blocked (line 1387) | def test_dangerous_builtins_calls_are_blocked(self):
    method test_final_answer_accepts_kwarg_answer (line 1401) | def test_final_answer_accepts_kwarg_answer(self):
    method test_final_answer_not_caught_by_except_exception (line 1406) | def test_final_answer_not_caught_by_except_exception(self):
    method test_dangerous_builtins_are_callable_if_explicitly_added (line 1424) | def test_dangerous_builtins_are_callable_if_explicitly_added(self):
    method test_can_import_os_if_explicitly_authorized (line 1433) | def test_can_import_os_if_explicitly_authorized(self):
    method test_can_import_os_if_all_imports_authorized (line 1437) | def test_can_import_os_if_all_imports_authorized(self):
    method test_can_import_scipy_if_explicitly_authorized (line 1442) | def test_can_import_scipy_if_explicitly_authorized(self):
    method test_can_import_sklearn_if_explicitly_authorized (line 1447) | def test_can_import_sklearn_if_explicitly_authorized(self):
    method test_function_def_recovers_source_code (line 1451) | def test_function_def_recovers_source_code(self):
    method test_evaluate_class_def_with_pass (line 1469) | def test_evaluate_class_def_with_pass(self):
    method test_evaluate_class_def_with_ann_assign_name (line 1482) | def test_evaluate_class_def_with_ann_assign_name(self):
    method test_evaluate_class_def_with_ann_assign_attribute (line 1512) | def test_evaluate_class_def_with_ann_assign_attribute(self):
    method test_evaluate_class_def_with_ann_assign_subscript (line 1538) | def test_evaluate_class_def_with_ann_assign_subscript(self):
    method test_evaluate_class_def_with_enum (line 1566) | def test_evaluate_class_def_with_enum(self):
    method test_evaluate_annassign (line 1598) | def test_evaluate_annassign(self):
    method test_evaluate_augassign (line 1661) | def test_evaluate_augassign(self, code, expected_result):
    method test_evaluate_augassign_number (line 1683) | def test_evaluate_augassign_number(self, operator, expected_result):
    method test_evaluate_augassign_custom (line 1709) | def test_evaluate_augassign_custom(self, operator, expected_result):
    method test_evaluate_delete (line 1775) | def test_evaluate_delete(self, code, expected_error_message):
    method test_non_standard_comparisons (line 1781) | def test_non_standard_comparisons(self):
  class TestEvaluateBoolop (line 1806) | class TestEvaluateBoolop:
    method test_evaluate_boolop_and (line 1810) | def test_evaluate_boolop_and(self, a, b, c):
    method test_evaluate_boolop_or (line 1819) | def test_evaluate_boolop_or(self, a, b, c):
  class TestEvaluateDelete (line 1826) | class TestEvaluateDelete:
    method test_evaluate_delete (line 1836) | def test_evaluate_delete(self, code, state, expectation):
  class TestEvaluateCondition (line 1848) | class TestEvaluateCondition:
    method test_evaluate_condition (line 1883) | def test_evaluate_condition(self, condition, state, expected_result):
    method test_evaluate_condition_with_pandas (line 1929) | def test_evaluate_condition_with_pandas(self, condition, state, expect...
    method test_evaluate_condition_with_pandas_exceptions (line 1965) | def test_evaluate_condition_with_pandas_exceptions(self, condition, st...
  class TestEvaluateSubscript (line 1972) | class TestEvaluateSubscript:
    method test_evaluate_subscript (line 2031) | def test_evaluate_subscript(self, subscript, state, expected_result):
    method test_evaluate_subscript_error (line 2052) | def test_evaluate_subscript_error(self, subscript, state, expected_err...
    method test_evaluate_subscript_with_custom_class (line 2065) | def test_evaluate_subscript_with_custom_class(self, subscriptable_clas...
  function test_get_safe_module_handle_lazy_imports (line 2088) | def test_get_safe_module_handle_lazy_imports():
  class TestPrintContainer (line 2108) | class TestPrintContainer:
    method test_initial_value (line 2109) | def test_initial_value(self):
    method test_append (line 2113) | def test_append(self):
    method test_iadd (line 2118) | def test_iadd(self):
    method test_str (line 2123) | def test_str(self):
    method test_repr (line 2128) | def test_repr(self):
    method test_len (line 2133) | def test_len(self):
  function test_fix_final_answer_code (line 2139) | def test_fix_final_answer_code():
  class TestTimeout (line 2177) | class TestTimeout:
    method test_timeout_decorator_completes_within_limit (line 2180) | def test_timeout_decorator_completes_within_limit(self):
    method test_timeout_decorator_raises_error_when_exceeded (line 2190) | def test_timeout_decorator_raises_error_when_exceeded(self):
    method test_evaluate_python_code_with_timeout_completes (line 2201) | def test_evaluate_python_code_with_timeout_completes(self):
    method test_evaluate_python_code_with_timeout_raises (line 2207) | def test_evaluate_python_code_with_timeout_raises(self):
    method test_timeout_works_in_thread (line 2218) | def test_timeout_works_in_thread(self):
    method test_custom_timeout_value (line 2256) | def test_custom_timeout_value(self):
    method test_longer_timeout_value (line 2266) | def test_longer_timeout_value(self):
    method test_disabled_timeout (line 2277) | def test_disabled_timeout(self):
    method test_local_executor_custom_timeout (line 2289) | def test_local_executor_custom_timeout(self):
    method test_local_executor_disabled_timeout (line 2302) | def test_local_executor_disabled_timeout(self):
  function test_check_import_authorized (line 2330) | def test_check_import_authorized(module: str, authorized_imports: list[s...
  class TestLocalPythonExecutor (line 2334) | class TestLocalPythonExecutor:
    method test_additional_authorized_imports_are_installed (line 2350) | def test_additional_authorized_imports_are_installed(self, additional_...
    method test_state_name (line 2359) | def test_state_name(self):
    method test_call_from_dict (line 2370) | def test_call_from_dict(self, code):
    method test_chained_assignments (line 2401) | def test_chained_assignments(self, code):
    method test_evaluate_assign_error (line 2407) | def test_evaluate_assign_error(self):
    method test_function_def_recovers_source_code (line 2413) | def test_function_def_recovers_source_code(self):
    method test_isinstance_builtin_type (line 2433) | def test_isinstance_builtin_type(self, code, expected_result):
  class TestLocalPythonExecutorSecurity (line 2440) | class TestLocalPythonExecutorSecurity:
    method test_vulnerability_import (line 2445) | def test_vulnerability_import(self, additional_authorized_imports, exp...
    method test_vulnerability_builtins (line 2458) | def test_vulnerability_builtins(self, additional_authorized_imports, e...
    method test_vulnerability_builtins_safe_functions (line 2471) | def test_vulnerability_builtins_safe_functions(self, additional_author...
    method test_vulnerability_builtins_dangerous_functions (line 2488) | def test_vulnerability_builtins_dangerous_functions(
    method test_vulnerability_dangerous_functions (line 2511) | def test_vulnerability_dangerous_functions(self, additional_authorized...
    method test_vulnerability_for_all_dangerous_functions (line 2525) | def test_vulnerability_for_all_dangerous_functions(self, dangerous_fun...
    method test_vulnerability_via_sys (line 2545) | def test_vulnerability_via_sys(self, additional_authorized_imports, ex...
    method test_vulnerability_via_sys_for_all_dangerous_modules (line 2562) | def test_vulnerability_via_sys_for_all_dangerous_modules(self, dangero...
    method test_vulnerability_via_importlib (line 2583) | def test_vulnerability_via_importlib(self, additional_authorized_impor...
    method test_vulnerability_via_submodules (line 2661) | def test_vulnerability_via_submodules(self, code, additional_authorize...
    method test_vulnerability_via_submodules_through_indirect_attribute_access (line 2710) | def test_vulnerability_via_submodules_through_indirect_attribute_access(
    method test_vulnerability_builtins_via_sys (line 2733) | def test_vulnerability_builtins_via_sys(self, additional_authorized_im...
    method test_vulnerability_builtins_via_traceback (line 2768) | def test_vulnerability_builtins_via_traceback(
    method test_vulnerability_builtins_via_class_catch_warnings (line 2816) | def test_vulnerability_builtins_via_class_catch_warnings(
    method test_vulnerability_load_module_via_builtin_importer (line 2856) | def test_vulnerability_load_module_via_builtin_importer(self, addition...
    method test_vulnerability_class_via_subclasses (line 2876) | def test_vulnerability_class_via_subclasses(self):
    method test_vulnerability_via_dunder_access (line 2904) | def test_vulnerability_via_dunder_access(self, code, dunder_attribute):
    method test_vulnerability_via_dunder_indirect_access (line 2909) | def test_vulnerability_via_dunder_indirect_access(self):
    method test_vulnerability_via_dunder_call (line 2970) | def test_vulnerability_via_dunder_call(

FILE: tests/test_mcp_client.py
  function echo_server_script (line 11) | def echo_server_script():
  function structured_output_server_script (line 29) | def structured_output_server_script():
  function test_mcp_client_with_syntax (line 55) | def test_mcp_client_with_syntax(echo_server_script: str):
  function test_mcp_client_with_structured_output (line 64) | def test_mcp_client_with_structured_output(structured_output_server_scri...
  function test_mcp_client_without_structured_output (line 87) | def test_mcp_client_without_structured_output(structured_output_server_s...
  function test_mcp_client_try_finally_syntax (line 105) | def test_mcp_client_try_finally_syntax(echo_server_script: str):
  function test_multiple_servers (line 120) | def test_multiple_servers(echo_server_script: str):

FILE: tests/test_memory.py
  class TestAgentMemory (line 20) | class TestAgentMemory:
    method test_initialization (line 21) | def test_initialization(self):
    method test_return_all_code_actions (line 27) | def test_return_all_code_actions(self):
  class TestMemoryStep (line 37) | class TestMemoryStep:
    method test_initialization (line 38) | def test_initialization(self):
    method test_dict (line 42) | def test_dict(self):
    method test_to_messages (line 46) | def test_to_messages(self):
  function test_action_step_dict (line 52) | def test_action_step_dict():
  function test_action_step_to_messages (line 119) | def test_action_step_to_messages():
  function test_action_step_to_messages_no_tool_calls_with_observations (line 159) | def test_action_step_to_messages_no_tool_calls_with_observations():
  function test_planning_step_to_messages (line 180) | def test_planning_step_to_messages():
  function test_task_step_to_messages (line 201) | def test_task_step_to_messages():
  function test_system_prompt_step_to_messages (line 220) | def test_system_prompt_step_to_messages():
  function test_memory_step_json_serialization (line 235) | def test_memory_step_json_serialization():

FILE: tests/test_models.py
  class TestModel (line 49) | class TestModel:
    method test_prepare_completion_kwargs_parameter_precedence (line 50) | def test_prepare_completion_kwargs_parameter_precedence(self):
    method test_agglomerate_stream_deltas (line 80) | def test_agglomerate_stream_deltas(self):
    method test_prepare_completion_kwargs_stop_sequences (line 154) | def test_prepare_completion_kwargs_stop_sequences(self, model_id, stop...
    method test_prepare_completion_kwargs_tool_choice (line 194) | def test_prepare_completion_kwargs_tool_choice(self, with_tools, tool_...
    method test_get_json_schema_has_nullable_args (line 210) | def test_get_json_schema_has_nullable_args(self):
    method test_chatmessage_has_model_dumps_json (line 225) | def test_chatmessage_has_model_dumps_json(self):
    method test_chatmessage_from_dict_role_conversion (line 230) | def test_chatmessage_from_dict_role_conversion(self):
    method test_get_mlx_message_no_tool (line 247) | def test_get_mlx_message_no_tool(self):
    method test_get_mlx_message_tricky_stop_sequence (line 254) | def test_get_mlx_message_tricky_stop_sequence(self):
    method test_transformers_message_no_tool (line 268) | def test_transformers_message_no_tool(self, monkeypatch):
    method test_transformers_message_vl_no_tool (line 286) | def test_transformers_message_vl_no_tool(self, shared_datadir, monkeyp...
    method test_parse_json_if_needed (line 312) | def test_parse_json_if_needed(self):
  class TestInferenceClientModel (line 330) | class TestInferenceClientModel:
    method test_call_with_custom_role_conversions (line 331) | def test_call_with_custom_role_conversions(self):
    method test_init_model_with_tokens (line 344) | def test_init_model_with_tokens(self):
    method test_structured_outputs_with_unsupported_provider (line 354) | def test_structured_outputs_with_unsupported_provider(self):
    method test_get_hfapi_message_no_tool (line 365) | def test_get_hfapi_message_no_tool(self):
    method test_get_hfapi_message_no_tool_external_provider (line 371) | def test_get_hfapi_message_no_tool_external_provider(self):
    method test_get_hfapi_message_stream_no_tool (line 377) | def test_get_hfapi_message_stream_no_tool(self):
    method test_get_hfapi_message_stream_no_tool_external_provider (line 384) | def test_get_hfapi_message_stream_no_tool_external_provider(self):
  class TestLiteLLMModel (line 391) | class TestLiteLLMModel:
    method test_call_different_providers_without_key (line 400) | def test_call_different_providers_without_key(self, model_id):
    method test_retry_on_rate_limit_error (line 429) | def test_retry_on_rate_limit_error(self):
    method test_passing_flatten_messages (line 477) | def test_passing_flatten_messages(self):
  class TestLiteLLMRouterModel (line 485) | class TestLiteLLMRouterModel:
    method test_flatten_messages_as_text (line 494) | def test_flatten_messages_as_text(self, model_id, expected):
    method test_create_client (line 503) | def test_create_client(self):
  class TestOpenAIModel (line 520) | class TestOpenAIModel:
    method test_client_kwargs_passed_correctly (line 521) | def test_client_kwargs_passed_correctly(self):
    method test_streaming_tool_calls (line 544) | def test_streaming_tool_calls(self):
    method test_stop_sequence_cutting_for_o4_mini (line 567) | def test_stop_sequence_cutting_for_o4_mini(self):
  class TestAmazonBedrockModel (line 593) | class TestAmazonBedrockModel:
    method test_client_for_bedrock (line 594) | def test_client_for_bedrock(self):
  class TestAzureOpenAIModel (line 605) | class TestAzureOpenAIModel:
    method test_client_kwargs_passed_correctly (line 606) | def test_client_kwargs_passed_correctly(self):
  class TestTransformersModel (line 638) | class TestTransformersModel:
    method test_init (line 656) | def test_init(self, patching):
  function test_get_clean_message_list_basic (line 685) | def test_get_clean_message_list_basic():
  function test_get_clean_message_list_with_dicts (line 718) | def test_get_clean_message_list_with_dicts(messages, expected_roles, exp...
  function test_get_clean_message_list_role_conversions (line 726) | def test_get_clean_message_list_role_conversions():
  function test_remove_content_after_stop_sequences (line 739) | def test_remove_content_after_stop_sequences():
  function test_remove_content_after_stop_sequences_handles_none (line 746) | def test_remove_content_after_stop_sequences_handles_none():
  function test_get_clean_message_list_image_encoding (line 782) | def test_get_clean_message_list_image_encoding(convert_images_to_image_u...
  function test_get_clean_message_list_flatten_messages_as_text (line 796) | def test_get_clean_message_list_flatten_messages_as_text():
  function test_flatten_messages_as_text_for_all_models (line 843) | def test_flatten_messages_as_text_for_all_models(
  function test_supports_stop_parameter (line 910) | def test_supports_stop_parameter(model_id, expected):
  class TestGetToolCallFromText (line 915) | class TestGetToolCallFromText:
    method mock_uuid4 (line 917) | def mock_uuid4(self):
    method test_get_tool_call_from_text_basic (line 921) | def test_get_tool_call_from_text_basic(self):
    method test_get_tool_call_from_text_name_key_missing (line 930) | def test_get_tool_call_from_text_name_key_missing(self):
    method test_get_tool_call_from_text_json_object_args (line 938) | def test_get_tool_call_from_text_json_object_args(self):
    method test_get_tool_call_from_text_json_string_args (line 943) | def test_get_tool_call_from_text_json_string_args(self):
    method test_get_tool_call_from_text_missing_args (line 948) | def test_get_tool_call_from_text_missing_args(self):
    method test_get_tool_call_from_text_custom_keys (line 953) | def test_get_tool_call_from_text_custom_keys(self):
    method test_get_tool_call_from_text_numeric_args (line 959) | def test_get_tool_call_from_text_numeric_args(self):
  function test_tool_calls_json_serialization (line 973) | def test_tool_calls_json_serialization(model_class, model_id):

FILE: tests/test_monitoring.py
  class FakeLLMModel (line 38) | class FakeLLMModel(Model):
    method generate (line 39) | def generate(self, prompt, tools_to_call_from=None, **kwargs):
  class MonitoringTester (line 65) | class MonitoringTester(unittest.TestCase):
    method test_code_agent_metrics_max_steps (line 66) | def test_code_agent_metrics_max_steps(self):
    method test_code_agent_metrics_generation_error (line 86) | def test_code_agent_metrics_generation_error(self):
    method test_streaming_agent_text_output (line 100) | def test_streaming_agent_text_output(self):
    method test_streaming_agent_image_output (line 119) | def test_streaming_agent_image_output(self):
    method test_streaming_with_agent_error (line 156) | def test_streaming_with_agent_error(self):
  function test_code_agent_metrics (line 177) | def test_code_agent_metrics(agent_class):
  class ReplayTester (line 189) | class ReplayTester(unittest.TestCase):
    method test_replay_with_chatmessage (line 190) | def test_replay_with_chatmessage(self):
  class AgentLoggerLogTaskTester (line 204) | class AgentLoggerLogTaskTester(unittest.TestCase):
    method test_logger_log_task_does_not_crash_on_stray_markup_or_control_chars (line 205) | def test_logger_log_task_does_not_crash_on_stray_markup_or_control_cha...
    method test_logger_log_task_accepts_non_string_payloads (line 228) | def test_logger_log_task_accepts_non_string_payloads(self):

FILE: tests/test_remote_executors.py
  class TestRemotePythonExecutor (line 28) | class TestRemotePythonExecutor:
    method test_send_tools_empty_tools (line 29) | def test_send_tools_empty_tools(self):
    method test_send_variables_with_empty_dict_is_noop (line 37) | def test_send_variables_with_empty_dict_is_noop(self):
    method test_send_variables_non_empty_generates_executable_deserializer_code (line 43) | def test_send_variables_non_empty_generates_executable_deserializer_co...
    method test_send_variables_allow_pickle_handles_prefixed_payload (line 62) | def test_send_variables_allow_pickle_handles_prefixed_payload(self):
    method test_deserialize_final_answer_rejects_unprefixed_payload (line 76) | def test_deserialize_final_answer_rejects_unprefixed_payload(self):
    method test_send_tools_with_default_wikipedia_search_tool (line 81) | def test_send_tools_with_default_wikipedia_search_tool(self):
  class TestE2BExecutorUnit (line 91) | class TestE2BExecutorUnit:
    method test_e2b_executor_instantiation (line 92) | def test_e2b_executor_instantiation(self):
    method test_cleanup (line 120) | def test_cleanup(self):
  function e2b_executor (line 144) | def e2b_executor():
  class TestE2BExecutorIntegration (line 154) | class TestE2BExecutorIntegration:
    method set_executor (line 156) | def set_executor(self, e2b_executor):
    method test_final_answer_patterns (line 191) | def test_final_answer_patterns(self, code_action, expected_result):
    method test_custom_final_answer (line 197) | def test_custom_final_answer(self):
    method test_custom_final_answer_with_custom_inputs (line 210) | def test_custom_final_answer_with_custom_inputs(self):
  class TestDockerExecutorUnit (line 232) | class TestDockerExecutorUnit:
    method test_cleanup (line 233) | def test_cleanup(self):
  class CommonDockerExecutorIntegration (line 265) | class CommonDockerExecutorIntegration:
    method set_executor (line 267) | def set_executor(self, custom_executor):
    method test_state_persistence (line 270) | def test_state_persistence(self):
    method test_execute_output (line 279) | def test_execute_output(self):
    method test_execute_multiline_output (line 286) | def test_execute_multiline_output(self):
    method test_execute_image_output (line 293) | def test_execute_image_output(self):
    method test_syntax_error_handling (line 306) | def test_syntax_error_handling(self):
    method test_final_answer_patterns (line 345) | def test_final_answer_patterns(self, code_action, expected_result):
    method test_custom_final_answer (line 351) | def test_custom_final_answer(self):
    method test_custom_final_answer_with_custom_inputs (line 364) | def test_custom_final_answer_with_custom_inputs(self):
  class TestDockerExecutorIntegration (line 387) | class TestDockerExecutorIntegration(CommonDockerExecutorIntegration):
    method custom_executor (line 389) | def custom_executor(self):
    method test_initialization (line 397) | def test_initialization(self):
    method test_cleanup_on_deletion (line 401) | def test_cleanup_on_deletion(self):
  class TestModalExecutorIntegration (line 412) | class TestModalExecutorIntegration(CommonDockerExecutorIntegration):
    method custom_executor (line 414) | def custom_executor(self):
  class TestModalExecutorUnit (line 423) | class TestModalExecutorUnit:
    method test_sandbox_lifecycle (line 430) | def test_sandbox_lifecycle(
  class TestWasmExecutorUnit (line 478) | class TestWasmExecutorUnit:
    method test_wasm_executor_instantiation (line 479) | def test_wasm_executor_instantiation(self):
  class TestWasmExecutorIntegration (line 528) | class TestWasmExecutorIntegration:
    method setup_and_teardown (line 537) | def setup_and_teardown(self):
    method test_basic_execution (line 557) | def test_basic_execution(self):
    method test_state_persistence (line 563) | def test_state_persistence(self):
    method test_final_answer (line 572) | def test_final_answer(self):
    method test_numpy_execution (line 580) | def test_numpy_execution(self):
    method test_error_handling (line 590) | def test_error_handling(self):
    method test_syntax_error_handling (line 597) | def test_syntax_error_handling(self):
  class TestBlaxelExecutorUnit (line 605) | class TestBlaxelExecutorUnit:
    method test_blaxel_executor_instantiation_without_blaxel_sdk (line 606) | def test_blaxel_executor_instantiation_without_blaxel_sdk(self):
    method test_blaxel_executor_instantiation_with_blaxel_sdk (line 617) | def test_blaxel_executor_instantiation_with_blaxel_sdk(
    method test_blaxel_executor_custom_parameters (line 659) | def test_blaxel_executor_custom_parameters(
    method test_blaxel_executor_cleanup (line 706) | def test_blaxel_executor_cleanup(self, mock_settings, mock_sandbox_ins...

FILE: tests/test_search.py
  class TestDuckDuckGoSearchTool (line 23) | class TestDuckDuckGoSearchTool(ToolTesterMixin):
    method setup_method (line 24) | def setup_method(self):
    method test_exact_match_arg (line 29) | def test_exact_match_arg(self):
    method test_agent_type_output (line 34) | def test_agent_type_output(self):

FILE: tests/test_serialization.py
  class PicklableCustomClass (line 37) | class PicklableCustomClass:
    method __init__ (line 40) | def __init__(self):
  class TestSafeSerializationSecurity (line 44) | class TestSafeSerializationSecurity:
    method test_safe_mode_blocks_custom_classes (line 47) | def test_safe_mode_blocks_custom_classes(self):
    method test_safe_mode_blocks_pickle_deserialization (line 60) | def test_safe_mode_blocks_pickle_deserialization(self):
    method test_pickle_fallback_with_warning (line 70) | def test_pickle_fallback_with_warning(self):
  class TestSafeSerializationRoundtrip (line 95) | class TestSafeSerializationRoundtrip:
    method test_primitives (line 98) | def test_primitives(self):
    method test_collections (line 117) | def test_collections(self):
    method test_datetime_types (line 132) | def test_datetime_types(self):
    method test_special_types (line 147) | def test_special_types(self):
    method test_complex_nested_structure (line 159) | def test_complex_nested_structure(self):
  class TestBackwardCompatibility (line 185) | class TestBackwardCompatibility:
    method test_read_legacy_pickle_data (line 188) | def test_read_legacy_pickle_data(self):
    method test_safe_data_is_preferred (line 204) | def test_safe_data_is_preferred(self):
  class TestDefaultBehavior (line 219) | class TestDefaultBehavior:
    method test_dumps_defaults_to_safe (line 222) | def test_dumps_defaults_to_safe(self):
    method test_loads_defaults_to_safe (line 234) | def test_loads_defaults_to_safe(self):
  class TestEdgeCases (line 252) | class TestEdgeCases:
    method test_empty_data (line 255) | def test_empty_data(self):
    method test_nested_empty_structures (line 272) | def test_nested_empty_structures(self):
    method test_very_large_numbers (line 288) | def test_very_large_numbers(self):
    method test_special_float_values (line 302) | def test_special_float_values(self):
    method test_unicode_strings (line 323) | def test_unicode_strings(self):
    method test_very_long_strings (line 338) | def test_very_long_strings(self):
    method test_deeply_nested_structures (line 346) | def test_deeply_nested_structures(self):
    method test_dict_with_tuple_keys (line 359) | def test_dict_with_tuple_keys(self):
    method test_dict_with_integer_keys (line 371) | def test_dict_with_integer_keys(self):
    method test_mixed_collection_types (line 383) | def test_mixed_collection_types(self):
  class TestErrorHandling (line 406) | class TestErrorHandling:
    method test_invalid_json_data (line 409) | def test_invalid_json_data(self):
    method test_corrupted_safe_prefix (line 414) | def test_corrupted_safe_prefix(self):
    method test_missing_type_field (line 419) | def test_missing_type_field(self):
    method test_unknown_type_marker (line 428) | def test_unknown_type_marker(self):
    method test_invalid_base64_in_bytes (line 436) | def test_invalid_base64_in_bytes(self):
    method test_serialization_of_none_type (line 443) | def test_serialization_of_none_type(self):
    method test_serialization_of_function (line 450) | def test_serialization_of_function(self):
    method test_serialization_of_class (line 459) | def test_serialization_of_class(self):
    method test_serialization_of_module (line 468) | def test_serialization_of_module(self):
  class TestTypeCoverage (line 476) | class TestTypeCoverage:
    method test_all_datetime_types (line 479) | def test_all_datetime_types(self):
    method test_decimal_precision (line 499) | def test_decimal_precision(self):
    method test_pathlib_types (line 518) | def test_pathlib_types(self):
    method test_complex_numbers (line 535) | def test_complex_numbers(self):
    method test_bytes_types (line 551) | def test_bytes_types(self):
  class TestNumpySupport (line 567) | class TestNumpySupport:
    method test_numpy_array (line 570) | def test_numpy_array(self):
    method test_numpy_scalars (line 583) | def test_numpy_scalars(self):
    method test_numpy_various_dtypes (line 598) | def test_numpy_various_dtypes(self):
    method test_numpy_multidimensional (line 630) | def test_numpy_multidimensional(self):
    method test_numpy_empty_array (line 647) | def test_numpy_empty_array(self):
  class TestPILSupport (line 658) | class TestPILSupport:
    method test_pil_image (line 661) | def test_pil_image(self):
    method test_pil_various_modes (line 676) | def test_pil_various_modes(self):
    method test_pil_various_sizes (line 692) | def test_pil_various_sizes(self):
  class TestDataclasses (line 707) | class TestDataclasses:
    method test_simple_dataclass (line 710) | def test_simple_dataclass(self):
    method test_nested_dataclass (line 728) | def test_nested_dataclass(self):
  class TestPerformance (line 750) | class TestPerformance:
    method test_large_list (line 753) | def test_large_list(self):
    method test_large_dict (line 762) | def test_large_dict(self):
    method test_deeply_nested_performance (line 771) | def test_deeply_nested_performance(self):
  class TestPrefixHandling (line 785) | class TestPrefixHandling:
    method test_safe_prefix_detection (line 788) | def test_safe_prefix_detection(self):
    method test_pickle_prefix_with_allow_pickle (line 797) | def test_pickle_prefix_with_allow_pickle(self):
    method test_legacy_format_detection (line 809) | def test_legacy_format_detection(self):
  class TestRealWorldScenarios (line 820) | class TestRealWorldScenarios:
    method test_agent_variables_scenario (line 823) | def test_agent_variables_scenario(self):
    method test_final_answer_scenario (line 851) | def test_final_answer_scenario(self):
  class TestGeneratedDeserializerCode (line 868) | class TestGeneratedDeserializerCode:
    method test_generated_deserializer_executes_for_safe_payload (line 871) | def test_generated_deserializer_executes_for_safe_payload(self):
    method test_generated_deserializer_handles_pickle_prefix_when_enabled (line 887) | def test_generated_deserializer_handles_pickle_prefix_when_enabled(self):
  class TestConcurrency (line 897) | class TestConcurrency:
    method test_concurrent_serialization (line 900) | def test_concurrent_serialization(self):

FILE: tests/test_telemetry.py
  function in_memory_span_exporter (line 42) | def in_memory_span_exporter() -> InMemorySpanExporter:
  function tracer_provider (line 47) | def tracer_provider(in_memory_span_exporter: InMemorySpanExporter) -> tr...
  function instrument (line 56) | def instrument(
  class TestOpenTelemetry (line 67) | class TestOpenTelemetry:
    method test_model (line 68) | def test_model(self, in_memory_span_exporter: InMemorySpanExporter):

FILE: tests/test_tool_validation.py
  function test_validate_tool_attributes_with_default_tools (line 23) | def test_validate_tool_attributes_with_default_tools(tool_class):
  class ValidTool (line 27) | class ValidTool(Tool):
    method __init__ (line 35) | def __init__(self, optional_param="default"):
    method forward (line 39) | def forward(self, input: str) -> str:
  function valid_tool_function (line 44) | def valid_tool_function(input: str) -> str:
  function test_validate_tool_attributes_valid (line 54) | def test_validate_tool_attributes_valid(tool_class):
  class InvalidToolName (line 58) | class InvalidToolName(Tool):
    method __init__ (line 64) | def __init__(self):
    method forward (line 67) | def forward(self, input: str) -> str:
  class InvalidToolComplexAttrs (line 71) | class InvalidToolComplexAttrs(Tool):
    method __init__ (line 78) | def __init__(self):
    method forward (line 81) | def forward(self, input: str) -> str:
  class InvalidToolRequiredParams (line 85) | class InvalidToolRequiredParams(Tool):
    method __init__ (line 91) | def __init__(self, required_param, kwarg1=1):  # No default value
    method forward (line 95) | def forward(self, input: str) -> str:
  class InvalidToolNonLiteralDefaultParam (line 99) | class InvalidToolNonLiteralDefaultParam(Tool):
    method __init__ (line 105) | def __init__(self, default_param=UNDEFINED_VARIABLE):  # UNDEFINED_VAR...
    method forward (line 109) | def forward(self, input: str) -> str:
  class InvalidToolUndefinedNames (line 113) | class InvalidToolUndefinedNames(Tool):
    method forward (line 119) | def forward(self, input: str) -> str:
  function test_validate_tool_attributes_exceptions (line 139) | def test_validate_tool_attributes_exceptions(tool_class, expected_error):
  class MultipleAssignmentsTool (line 144) | class MultipleAssignmentsTool(Tool):
    method __init__ (line 150) | def __init__(self):
    method forward (line 153) | def forward(self, input: str) -> str:
  function test_validate_tool_attributes_multiple_assignments (line 158) | def test_validate_tool_attributes_multiple_assignments():
  function tool_function_with_multiple_assignments (line 163) | def tool_function_with_multiple_assignments(input: str) -> str:
  function test_tool_to_dict_validation_with_multiple_assignments (line 174) | def test_tool_to_dict_validation_with_multiple_assignments(tool_instance):
  class TestMethodChecker (line 178) | class TestMethodChecker:
    method test_multiple_assignments (line 179) | def test_multiple_assignments(self):

FILE: tests/test_tools.py
  class ToolTesterMixin (line 33) | class ToolTesterMixin:
    method test_inputs_output (line 34) | def test_inputs_output(self):
    method test_common_attributes (line 50) | def test_common_attributes(self):
    method test_agent_type_output (line 56) | def test_agent_type_output(self, create_inputs):
    method create_inputs (line 64) | def create_inputs(self, shared_datadir):
  class TestTool (line 85) | class TestTool:
    method test_tool_input_type_validation (line 99) | def test_tool_input_type_validation(self, type_value, should_raise_err...
    method test_tool_to_code_prompt_output_format (line 144) | def test_tool_to_code_prompt_output_format(self, tool_fixture, expecte...
    method test_tool_to_tool_calling_prompt_output_format (line 171) | def test_tool_to_tool_calling_prompt_output_format(self, tool_fixture,...
    method test_tool_init_with_decorator (line 177) | def test_tool_init_with_decorator(self):
    method test_tool_init_vanilla (line 190) | def test_tool_init_vanilla(self):
    method test_tool_init_decorator_raises_issues (line 211) | def test_tool_init_decorator_raises_issues(self):
    method test_saving_tool_raises_error_imports_outside_function (line 241) | def test_saving_tool_raises_error_imports_outside_function(self, tmp_p...
    method test_tool_definition_raises_no_error_imports_in_function (line 273) | def test_tool_definition_raises_no_error_imports_in_function(self):
    method test_tool_to_dict_allows_no_arg_in_init (line 294) | def test_tool_to_dict_allows_no_arg_in_init(self):
    method test_saving_tool_allows_no_imports_from_outside_methods (line 331) | def test_saving_tool_allows_no_imports_from_outside_methods(self, tmp_...
    method test_tool_missing_class_attributes_raises_error (line 372) | def test_tool_missing_class_attributes_raises_error(self):
    method test_tool_from_decorator_optional_args (line 392) | def test_tool_from_decorator_optional_args(self):
    method test_tool_mismatching_nullable_args_raises_error (line 409) | def test_tool_mismatching_nullable_args_raises_error(self):
    method test_tool_default_parameters_is_nullable (line 471) | def test_tool_default_parameters_is_nullable(self):
    method test_tool_supports_any_none (line 485) | def test_tool_supports_any_none(self, tmp_path):
    method test_tool_supports_array (line 500) | def test_tool_supports_array(self):
    method test_tool_supports_string_literal (line 515) | def test_tool_supports_string_literal(self):
    method test_tool_supports_numeric_literal (line 529) | def test_tool_supports_numeric_literal(self):
    method test_tool_supports_nullable_literal (line 543) | def test_tool_supports_nullable_literal(self):
    method test_saving_tool_produces_valid_pyhon_code_with_multiline_description (line 558) | def test_saving_tool_produces_valid_pyhon_code_with_multiline_descript...
    method test_to_dict_boolean_default_input (line 576) | def test_to_dict_boolean_default_input(self, fixture_name, request):
    method test_to_dict_optional_input (line 586) | def test_to_dict_optional_input(self, fixture_name, request):
    method test_from_dict_roundtrip (line 595) | def test_from_dict_roundtrip(self, example_tool):
    method test_tool_from_dict_invalid (line 609) | def test_tool_from_dict_invalid(self):
    method test_tool_decorator_preserves_original_function (line 615) | def test_tool_decorator_preserves_original_function(self):
    method test_tool_with_union_type_return (line 646) | def test_tool_with_union_type_return(self):
  class TestToolDecorator (line 661) | class TestToolDecorator:
    method test_tool_decorator_source_extraction_with_multiple_decorators (line 662) | def test_tool_decorator_source_extraction_with_multiple_decorators(self):
    method test_tool_decorator_source_extraction_with_multiline_signature (line 695) | def test_tool_decorator_source_extraction_with_multiline_signature(self):
    method test_tool_decorator_source_extraction_with_multiple_decorators_and_multiline (line 742) | def test_tool_decorator_source_extraction_with_multiple_decorators_and...
  function mock_server_parameters (line 800) | def mock_server_parameters():
  function mock_mcp_adapt (line 805) | def mock_mcp_adapt():
  function mock_smolagents_adapter (line 813) | def mock_smolagents_adapter():
  class TestToolCollection (line 820) | class TestToolCollection:
    method test_from_mcp (line 821) | def test_from_mcp(self, mock_server_parameters, mock_mcp_adapt, mock_s...
    method test_integration_from_mcp (line 829) | def test_integration_from_mcp(self):
    method test_integration_from_mcp_with_streamable_http (line 853) | def test_integration_from_mcp_with_streamable_http(self):
    method test_integration_from_mcp_with_sse (line 890) | def test_integration_from_mcp_with_sse(self):
  function test_launch_gradio_demo_does_not_raise (line 929) | def test_launch_gradio_demo_does_not_raise(tool_fixture_name, request):
  function test_validate_tool_arguments (line 954) | def test_validate_tool_arguments(tool_input_type, expected_input, expect...
  function test_validate_tool_arguments_nullable (line 1035) | def test_validate_tool_arguments_nullable(scenario, type_hint, default, ...

FILE: tests/test_types.py
  function get_new_path (line 27) | def get_new_path(suffix="") -> str:
  class AgentAudioTests (line 34) | class AgentAudioTests(unittest.TestCase):
    method test_from_tensor (line 35) | def test_from_tensor(self):
    method test_from_string (line 55) | def test_from_string(self):
  class TestAgentImage (line 70) | class TestAgentImage:
    method test_from_tensor (line 71) | def test_from_tensor(self):
    method test_from_string (line 87) | def test_from_string(self, shared_datadir):
    method test_from_image (line 99) | def test_from_image(self, shared_datadir):
  class AgentTextTests (line 112) | class AgentTextTests(unittest.TestCase):
    method test_from_string (line 113) | def test_from_string(self):

FILE: tests/test_utils.py
  class ValidTool (line 35) | class ValidTool(Tool):
    method __init__ (line 43) | def __init__(self, optional_param="default"):
    method forward (line 47) | def forward(self, input: str) -> str:
  function valid_tool_function (line 52) | def valid_tool_function(input: str) -> str:
  class AgentTextTests (line 102) | class AgentTextTests(unittest.TestCase):
    method test_parse_code_blobs (line 103) | def test_parse_code_blobs(self):
    method test_multiple_code_blobs (line 140) | def test_multiple_code_blobs(self):
  function ipython_shell (line 147) | def ipython_shell():
  function test_get_source_ipython (line 162) | def test_get_source_ipython(ipython_shell, obj_name, code_blob):
  function test_get_source_standard_class (line 168) | def test_get_source_standard_class():
  function test_get_source_standard_function (line 176) | def test_get_source_standard_function():
  function test_get_source_ipython_errors_empty_cells (line 184) | def test_get_source_ipython_errors_empty_cells(ipython_shell):
  function test_get_source_ipython_errors_definition_not_found (line 192) | def test_get_source_ipython_errors_definition_not_found(ipython_shell):
  function test_get_source_ipython_errors_type_error (line 200) | def test_get_source_ipython_errors_type_error():
  function test_instance_to_source (line 208) | def test_instance_to_source(tool, expected_tool_source):
  function test_e2e_class_tool_save (line 213) | def test_e2e_class_tool_save(tmp_path):
  function test_e2e_ipython_class_tool_save (line 267) | def test_e2e_ipython_class_tool_save(tmp_path):
  function test_e2e_function_tool_save (line 324) | def test_e2e_function_tool_save(tmp_path):
  function test_e2e_ipython_function_tool_save (line 374) | def test_e2e_ipython_function_tool_save(tmp_path):
  function test_parse_json_blob_with_valid_json (line 467) | def test_parse_json_blob_with_valid_json(raw_json, expected_data, expect...
  function test_parse_json_blob_with_invalid_json (line 484) | def test_parse_json_blob_with_invalid_json(raw_json):
  function test_is_valid_name (line 515) | def test_is_valid_name(name, expected):
  function test_agent_gradio_app_template_excludes_class_keyword (line 520) | def test_agent_gradio_app_template_excludes_class_keyword():

FILE: tests/test_vision_web_browser.py
  function mock_driver (line 11) | def mock_driver():
  class TestXPathEscaping (line 19) | class TestXPathEscaping:
    method test_escape_xpath_string_basic (line 39) | def test_escape_xpath_string_basic(self, input_text, expected_pattern):
    method test_escape_xpath_string_mixed_quotes (line 52) | def test_escape_xpath_string_mixed_quotes(self, input_text):
    method test_escape_prevents_injection (line 67) | def test_escape_prevents_injection(self, malicious_input):
  class TestSearchItemCtrlF (line 78) | class TestSearchItemCtrlF:
    method test_search_item_prevents_injection (line 91) | def test_search_item_prevents_injection(self, search_text, mock_driver):
    method test_search_item_nth_result (line 115) | def test_search_item_nth_result(self, mock_driver):
    method test_search_item_not_found (line 126) | def test_search_item_not_found(self, mock_driver):
Condensed preview — 183 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (1,937K chars).
[
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "chars": 1385,
    "preview": "---\nname: Bug report\nabout: The clearer your bug report, the faster it will be fixed!\ntitle: \"BUG: \"\nlabels: bug\nassigne"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/doc_improvement.md",
    "chars": 1042,
    "preview": "---\nname: Documentation Improvement\nabout: Report wrong or missing documentation\ntitle: 'DOC: '\nlabels: documentation\nas"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "chars": 1249,
    "preview": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: 'ENH: '\nlabels: enhancement\nassignees: ''\n\n---\n"
  },
  {
    "path": ".github/workflows/build_documentation.yml",
    "chars": 695,
    "preview": "name: Build documentation\n\non:\n  push:\n    branches:\n      - main\n      - doc-builder*\n      - v*-release\n      - use_te"
  },
  {
    "path": ".github/workflows/build_pr_documentation.yml",
    "chars": 628,
    "preview": "name: Build PR Documentation\n\non:\n  pull_request:\n    paths:\n      - 'docs/source/**'\n      - 'assets/**'\n      - '.gith"
  },
  {
    "path": ".github/workflows/quality.yml",
    "chars": 703,
    "preview": "name: Quality Check\n\non: [pull_request]\n\nenv:\n  UV_SYSTEM_PYTHON: 1\n\njobs:\n  check_code_quality:\n    runs-on: ubuntu-lat"
  },
  {
    "path": ".github/workflows/tests.yml",
    "chars": 832,
    "preview": "name: Python tests\n\non:\n  pull_request:\n  push:\n    branches:\n      - ci-*\n\nenv:\n  UV_SYSTEM_PYTHON: 1\n\njobs:\n  build-ub"
  },
  {
    "path": ".github/workflows/trufflehog.yml",
    "chars": 298,
    "preview": "on:\n  push:\n\nname: Secret Leaks\n\npermissions:\n  contents: read\n\njobs:\n  trufflehog:\n    runs-on: ubuntu-latest\n    steps"
  },
  {
    "path": ".github/workflows/upload_pr_documentation.yml",
    "chars": 383,
    "preview": "name: Upload PR Documentation\n\non:\n  workflow_run:\n    workflows: [\"Build PR Documentation\"]\n    types:\n      - complete"
  },
  {
    "path": ".gitignore",
    "chars": 1438,
    "preview": "# Logging\nlogs\ntmp\nwandb\n\n# Data\ndata\noutputs\ndata/\n\n# Apple\n.DS_Store\n\n# VS Code\n.vscode\n\n# Byte-compiled / optimized /"
  },
  {
    "path": ".pre-commit-config.yaml",
    "chars": 302,
    "preview": "repos:\n  - repo: https://github.com/astral-sh/ruff-pre-commit\n    rev: v0.2.1\n    hooks:\n      - id: ruff\n        args:\n"
  },
  {
    "path": "AGENTS.md",
    "chars": 157,
    "preview": "# Contributor Guidelines\n- Follow OOP principles\n- Be Pythonic: follow Python best practices and idiomatic patterns\n- Wr"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "chars": 5488,
    "preview": "\n# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nWe as members, contributors, and leaders pledge to make particip"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 5452,
    "preview": "<!---\nCopyright 2025 The HuggingFace Team. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"Li"
  },
  {
    "path": "LICENSE",
    "chars": 11357,
    "preview": "                                 Apache License\n                           Version 2.0, January 2004\n                   "
  },
  {
    "path": "Makefile",
    "chars": 326,
    "preview": ".PHONY: quality style test docs\n\ncheck_dirs := examples src tests\n\n# Check code quality of the source code\nquality:\n\truf"
  },
  {
    "path": "README.md",
    "chars": 14223,
    "preview": "<!---\nCopyright 2024 The HuggingFace Team. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"Li"
  },
  {
    "path": "SECURITY.md",
    "chars": 960,
    "preview": "# Security Policy\n\n## Reporting a Vulnerability\n\nTo report a security vulnerability, please contact: security@huggingfac"
  },
  {
    "path": "docs/README.md",
    "chars": 10844,
    "preview": "<!---\nCopyright 2024 The HuggingFace Team. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"Li"
  },
  {
    "path": "docs/source/en/_config.py",
    "chars": 488,
    "preview": "# docstyle-ignore\nINSTALL_CONTENT = \"\"\"\n# Installation\n! pip install smolagents\n# To install from source instead of the "
  },
  {
    "path": "docs/source/en/_toctree.yml",
    "chars": 1791,
    "preview": "- title: Get started\n  sections:\n  - local: index\n    title: Introduction\n  - local: installation\n    title: Installatio"
  },
  {
    "path": "docs/source/en/conceptual_guides/intro_agents.md",
    "chars": 8852,
    "preview": "# What are agents? 🤔\n\n## An introduction to agentic systems.\n\nAny efficient system using AI will need to provide LLMs so"
  },
  {
    "path": "docs/source/en/conceptual_guides/react.md",
    "chars": 2777,
    "preview": "# How do multi-step agents work?\n\nThe ReAct framework ([Yao et al., 2022](https://huggingface.co/papers/2210.03629)) is "
  },
  {
    "path": "docs/source/en/examples/async_agent.md",
    "chars": 2779,
    "preview": "# Async Applications with Agents\n\nThis guide demonstrates how to integrate a synchronous agent from the `smolagents` lib"
  },
  {
    "path": "docs/source/en/examples/multiagents.md",
    "chars": 6560,
    "preview": "# Orchestrate a multi-agent system 🤖🤝🤖\n\n[[open-in-colab]]\n\nIn this notebook we will make a **multi-agent web browser: an"
  },
  {
    "path": "docs/source/en/examples/plan_customization.md",
    "chars": 3912,
    "preview": "# Human-in-the-Loop: Customize Agent Plan Interactively\n\nThis page demonstrates advanced usage of the smolagents library"
  },
  {
    "path": "docs/source/en/examples/rag.md",
    "chars": 9351,
    "preview": "# Agentic RAG\n\n[[open-in-colab]]\n\n## Introduction to Retrieval-Augmented Generation (RAG)\n\nRetrieval-Augmented Generatio"
  },
  {
    "path": "docs/source/en/examples/text_to_sql.md",
    "chars": 6508,
    "preview": "# Text-to-SQL\n\n[[open-in-colab]]\n\nIn this tutorial, we’ll see how to implement an agent that leverages SQL using `smolag"
  },
  {
    "path": "docs/source/en/examples/using_different_models.md",
    "chars": 4102,
    "preview": "# Using different models\n\n[[open-in-colab]]\n\n`smolagents` provides a flexible framework that allows you to use various l"
  },
  {
    "path": "docs/source/en/examples/web_browser.md",
    "chars": 6821,
    "preview": "# Web Browser Automation with Agents 🤖🌐\n\n[[open-in-colab]]\n\nIn this notebook, we'll create an **agent-powered web browse"
  },
  {
    "path": "docs/source/en/guided_tour.md",
    "chars": 29975,
    "preview": "# Agents - Guided tour\n\n[[open-in-colab]]\n\nIn this guided visit, you will learn how to build an agent, how to run it, an"
  },
  {
    "path": "docs/source/en/index.md",
    "chars": 6345,
    "preview": "# `smolagents`\n\n<div class=\"flex justify-center\">\n    <img src=\"https://huggingface.co/datasets/huggingface/documentatio"
  },
  {
    "path": "docs/source/en/installation.md",
    "chars": 6997,
    "preview": "# Installation Options\n\nThe `smolagents` library can be installed using pip. Here are the different installation methods"
  },
  {
    "path": "docs/source/en/reference/agents.md",
    "chars": 1545,
    "preview": "# Agents\n\n<Tip warning={true}>\n\nSmolagents is an experimental API which is subject to change at any time. Results return"
  },
  {
    "path": "docs/source/en/reference/default_tools.md",
    "chars": 2186,
    "preview": "# Built-in Tools\n\nReady-to-use tool implementations provided by the `smolagents` library.\n\nThese built-in tools are conc"
  },
  {
    "path": "docs/source/en/reference/models.md",
    "chars": 9646,
    "preview": "# Models\n\n<Tip warning={true}>\n\nSmolagents is an experimental API which is subject to change at any time. Results return"
  },
  {
    "path": "docs/source/en/reference/python_executors.md",
    "chars": 1209,
    "preview": "# Python code executors\n\nPython executors are responsible for running the code generated by code agents in a controlled "
  },
  {
    "path": "docs/source/en/reference/tools.md",
    "chars": 1746,
    "preview": "# Tools\n\n<Tip warning={true}>\n\nSmolagents is an experimental API which is subject to change at any time. Results returne"
  },
  {
    "path": "docs/source/en/tutorials/building_good_agents.md",
    "chars": 23291,
    "preview": "# Building good agents\n\n[[open-in-colab]]\n\nThere's a world of difference between building an agent that works and one th"
  },
  {
    "path": "docs/source/en/tutorials/inspect_runs.md",
    "chars": 7811,
    "preview": "# Inspecting runs with OpenTelemetry\n\n[[open-in-colab]]\n\n> [!TIP]\n> If you're new to building agents, make sure to first"
  },
  {
    "path": "docs/source/en/tutorials/memory.md",
    "chars": 4851,
    "preview": "# 📚 Manage your agent's memory\n\n[[open-in-colab]]\n\nIn the end, an agent can be defined by simple components: it has tool"
  },
  {
    "path": "docs/source/en/tutorials/secure_code_execution.md",
    "chars": 22009,
    "preview": "# Secure code execution\n\n[[open-in-colab]]\n\n> [!TIP]\n> If you're new to building agents, make sure to first read the [in"
  },
  {
    "path": "docs/source/en/tutorials/tools.md",
    "chars": 18636,
    "preview": "# Tools\n\n[[open-in-colab]]\n\nHere, we're going to see advanced tool usage.\n\n> [!TIP]\n> If you're new to building agents, "
  },
  {
    "path": "docs/source/es/_config.py",
    "chars": 488,
    "preview": "# docstyle-ignore\nINSTALL_CONTENT = \"\"\"\n# Installation\n! pip install smolagents\n# To install from source instead of the "
  },
  {
    "path": "docs/source/es/_toctree.yml",
    "chars": 1787,
    "preview": "- title: Primeros Pasos\n  sections:\n  - local: index\n    title: Introducción\n  - local: installation\n    title: Opciones"
  },
  {
    "path": "docs/source/es/index.md",
    "chars": 7095,
    "preview": "# `smolagents`\n\n<div class=\"flex justify-center\">\n    <img src=\"https://huggingface.co/datasets/huggingface/documentatio"
  },
  {
    "path": "docs/source/es/installation.md",
    "chars": 7574,
    "preview": "# Opciones de instalación\n\nLa biblioteca `smolagents` se puede instalar usando pip. Existen varias formas y opciones dis"
  },
  {
    "path": "docs/source/hi/_config.py",
    "chars": 488,
    "preview": "# docstyle-ignore\nINSTALL_CONTENT = \"\"\"\n# Installation\n! pip install smolagents\n# To install from source instead of the "
  },
  {
    "path": "docs/source/hi/_toctree.yml",
    "chars": 1113,
    "preview": "- title: Get started\n  sections:\n  - local: index\n    title: 🤗 Agents\n  - local: guided_tour\n    title: गाइडेड टूर\n- tit"
  },
  {
    "path": "docs/source/hi/conceptual_guides/intro_agents.md",
    "chars": 8443,
    "preview": "# Agents का परिचय\n\n## 🤔 Agents क्या हैं?\n\nAI का उपयोग करने वाली किसी भी कुशल प्रणाली को LLM को वास्तविक दुनिया तक किसी प"
  },
  {
    "path": "docs/source/hi/conceptual_guides/react.md",
    "chars": 1640,
    "preview": "# मल्टी-स्टेप एजेंट्स कैसे काम करते हैं?\n\nReAct फ्रेमवर्क ([Yao et al., 2022](https://huggingface.co/papers/2210.03629))"
  },
  {
    "path": "docs/source/hi/examples/multiagents.md",
    "chars": 7086,
    "preview": "# मल्टी-एजेंट सिस्टम का आयोजन करें 🤖🤝🤖\n\n[[open-in-colab]]\n\nइस नोटबुक में हम एक **मल्टी-एजेंट वेब ब्राउज़र बनाएंगे: एक एज"
  },
  {
    "path": "docs/source/hi/examples/rag.md",
    "chars": 7384,
    "preview": "# एजेंटिक RAG\n\n[[open-in-colab]]\n\nरिट्रीवल-ऑगमेंटेड-जनरेशन (RAG) है \"एक यूजर के प्रश्न का उत्तर देने के लिए LLM का उपयोग"
  },
  {
    "path": "docs/source/hi/examples/text_to_sql.md",
    "chars": 6376,
    "preview": "# Text-to-SQL\n\n[[open-in-colab]]\n\nइस ट्यूटोरियल में, हम देखेंगे कि कैसे `smolagents` का उपयोग करके एक एजेंट को SQL का उप"
  },
  {
    "path": "docs/source/hi/guided_tour.md",
    "chars": 17532,
    "preview": "# Agents - गाइडेड टूर\n\n[[open-in-colab]]\n\nइस गाइडेड विजिट में, आप सीखेंगे कि एक एजेंट कैसे बनाएं, इसे कैसे चलाएं, और अपन"
  },
  {
    "path": "docs/source/hi/index.md",
    "chars": 3086,
    "preview": "# `smolagents`\n\n<div class=\"flex justify-center\">\n    <img src=\"https://huggingface.co/datasets/huggingface/documentatio"
  },
  {
    "path": "docs/source/hi/reference/agents.md",
    "chars": 5089,
    "preview": "# Agents\n\n<Tip warning={true}>\n\nSmolagents एक experimental API है जो किसी भी समय बदल सकता है। एजेंट्स द्वारा लौटाए गए पर"
  },
  {
    "path": "docs/source/hi/reference/tools.md",
    "chars": 2034,
    "preview": "# Tools\n\n<Tip warning={true}>\n\nSmolagents एक experimental API है जो किसी भी समय बदल सकता है। एजेंट्स द्वारा लौटाए गए परि"
  },
  {
    "path": "docs/source/hi/tutorials/building_good_agents.md",
    "chars": 21868,
    "preview": "# अच्छे Agents का निर्माण\n\n[[open-in-colab]]\n\nएक ऐसा एजेंट बनाने में जो काम करता है और जो काम नहीं करता है, इसमें ज़मीन-"
  },
  {
    "path": "docs/source/hi/tutorials/inspect_runs.md",
    "chars": 3630,
    "preview": "# OpenTelemetry के साथ runs का निरीक्षण\n\n[[open-in-colab]]\n\n> [!TIP]\n> यदि आप एजेंट्स बनाने में नए हैं, तो पहले [एजेंट्स"
  },
  {
    "path": "docs/source/hi/tutorials/secure_code_execution.md",
    "chars": 4472,
    "preview": "# सुरक्षित कोड एक्जीक्यूशन\n\n[[open-in-colab]]\n\n> [!TIP]\n> यदि आप एजेंट्स बनाने में नए हैं, तो सबसे पहले [एजेंट्स का परिच"
  },
  {
    "path": "docs/source/hi/tutorials/tools.md",
    "chars": 11162,
    "preview": "# Tools\n\n[[open-in-colab]]\n\nयहाँ, हम एडवांस्ड tools उपयोग देखेंगे।\n\n> [!TIP]\n> यदि आप एजेंट्स बनाने में नए हैं, तो सबसे "
  },
  {
    "path": "docs/source/ko/_config.py",
    "chars": 488,
    "preview": "# docstyle-ignore\nINSTALL_CONTENT = \"\"\"\n# Installation\n! pip install smolagents\n# To install from source instead of the "
  },
  {
    "path": "docs/source/ko/_toctree.yml",
    "chars": 1461,
    "preview": "- title: Get started\n  sections:\n  - local: index\n    title: 소개\n  - local: installation\n    title: 설치 옵션\n  - local: guid"
  },
  {
    "path": "docs/source/ko/conceptual_guides/react.md",
    "chars": 2110,
    "preview": "# 멀티스텝 에이전트는 어떻게 동작하나요?[[how-do-multi-step-agents-work]]\n\nReAct 프레임워크([Yao et al., 2022](https://huggingface.co/papers/2"
  },
  {
    "path": "docs/source/ko/examples/async_agent.md",
    "chars": 2422,
    "preview": "# 에이전트를 활용한 비동기 애플리케이션[[async-applications-with-agents]]\n\n이 가이드는 smolagents 라이브러리의 동기 에이전트를 Starlette 기반의 비동기 Python 웹 애"
  },
  {
    "path": "docs/source/ko/examples/multiagents.md",
    "chars": 4753,
    "preview": "# 멀티 에이전트 시스템 오케스트레이션 🤖🤝🤖\n\n[[Colab에서 열기]]\n\n이 노트북에서는 **멀티 에이전트 웹 브라우저**를 만들어보겠습니다. 이는 웹을 사용하여 문제를 해결하기 위해 여러 에이전트가 협력하는 에"
  },
  {
    "path": "docs/source/ko/examples/plan_customization.md",
    "chars": 3041,
    "preview": "# Human-in-the-Loop: 사용자와 상호작용하며 에이전트 계획 수정하기 [[humanintheloop-customize-agent-plan-interactively]]\n\n이 페이지에서는 smolagents"
  },
  {
    "path": "docs/source/ko/examples/rag.md",
    "chars": 6843,
    "preview": "# Agentic RAG[[agentic-rag]]\n\n[[open-in-colab]]\n\n## RAG(검색 증강 생성) 소개[[introduction-to-retrieval-augmented-generation-rag"
  },
  {
    "path": "docs/source/ko/examples/text_to_sql.md",
    "chars": 5497,
    "preview": "# Text-to-SQL[[text-to-sql]]\n\n[[open-in-colab]]\n\n이 튜토리얼에서는 `smolagents`를 사용해 SQL을 다루는 에이전트를 구현해보겠습니다.\n\n> 먼저 중요한 질문 하나로 시"
  },
  {
    "path": "docs/source/ko/examples/using_different_models.md",
    "chars": 3272,
    "preview": "# 다양한 모델 사용하기 [[using-different-models]]\n\n[[open-in-colab]]\n\n`smolagents`는 다양한 프로바이더의 여러 언어 모델을 사용할 수 있는 유연한 프레임워크를 제공합니"
  },
  {
    "path": "docs/source/ko/examples/web_browser.md",
    "chars": 6210,
    "preview": "# 에이전트를 활용한 웹 브라우저 자동화 🤖🌐[[web-browser-automation-with-agents-🤖🌐]]\n\n[[open-in-colab]]\n\n이 노트북에서는 **에이전트 기반 웹 브라우저 자동화 시스템"
  },
  {
    "path": "docs/source/ko/guided_tour.md",
    "chars": 22043,
    "preview": "# 에이전트 안내서[[agents---guided-tour]]\n\n[[open-in-colab]]\n\n이 안내서에서는 에이전트를 구축하는 방법, 실행하는 방법, 그리고 사용 사례에 맞게 더 잘 작동하도록 맞춤 설정하는 "
  },
  {
    "path": "docs/source/ko/index.md",
    "chars": 5094,
    "preview": "# `smolagents`[[smolagents]]\n\n<div class=\"flex justify-center\">\n    <img src=\"https://huggingface.co/datasets/huggingfac"
  },
  {
    "path": "docs/source/ko/installation.md",
    "chars": 5727,
    "preview": "# 설치 옵션[[installation-options]]\n\n`smolagents` 라이브러리는 pip를 사용하여 설치할 수 있습니다. 사용 가능한 다양한 설치 방법과 옵션을 소개합니다.\n\n## 사전 요구사항[[pre"
  },
  {
    "path": "docs/source/ko/reference/agents.md",
    "chars": 2017,
    "preview": "# 에이전트[[agents]]\n\n<Tip warning={true}>\n\nSmolagents는 실험적인 API로 언제든지 변경될 수 있습니다. API나 사용되는 모델이 변경될 수 있기 때문에 에이전트가 반환하는 결과도"
  },
  {
    "path": "docs/source/ko/reference/models.md",
    "chars": 7986,
    "preview": "# 모델[[models]]\n\n<Tip warning={true}>\n\nSmolagents는 언제든지 변경될 수 있는 실험적인 API입니다. API 또는 기반 모델이 바뀌면 에이전트가 반환하는 결과도 달라질 수 있습니다"
  },
  {
    "path": "docs/source/ko/reference/tools.md",
    "chars": 1499,
    "preview": "# 도구[[tools]]\n\n<Tip warning={true}>\n\nSmolagents는 언제든지 변경될 수 있는 실험적인 API입니다. API나 사용되는 모델이 변경될 수 있기 때문에 에이전트가 반환하는 결과도 달라"
  },
  {
    "path": "docs/source/ko/tutorials/building_good_agents.md",
    "chars": 20364,
    "preview": "# 좋은 에이전트 구축하기[[building-good-agents]]\n\n[[open-in-colab]]\n\n성공하는 에이전트와 실패하는 에이전트 사이에는 큰 차이가 있습니다.\n성공하는 에이전트는 어떻게 만들 수 있을까"
  },
  {
    "path": "docs/source/ko/tutorials/inspect_runs.md",
    "chars": 5755,
    "preview": "# OpenTelemetry로 실행 검사하기[[inspecting-runs-with-opentelemetry]]\n\n[[open-in-colab]]\n\n> [!TIP]\n> 에이전트 구축이 처음이라면 먼저 [에이전트 소개"
  },
  {
    "path": "docs/source/ko/tutorials/memory.md",
    "chars": 4120,
    "preview": "# 📚 에이전트 메모리 관리[[-manage-your-agents-memory]]\n\n[[open-in-colab]]\n\n결국 에이전트는 도구와 프롬프트로 이루어진 단순한 구성요소로 정의됩니다.\n그리고 무엇보다 중요한 "
  },
  {
    "path": "docs/source/zh/_config.py",
    "chars": 488,
    "preview": "# docstyle-ignore\nINSTALL_CONTENT = \"\"\"\n# Installation\n! pip install smolagents\n# To install from source instead of the "
  },
  {
    "path": "docs/source/zh/_toctree.yml",
    "chars": 1090,
    "preview": "- title: 起步\n  sections:\n  - local: index\n    title: 🤗 Agents\n  - local: guided_tour\n    title: 导览\n- title: Tutorials\n  s"
  },
  {
    "path": "docs/source/zh/conceptual_guides/intro_agents.md",
    "chars": 4307,
    "preview": "# Agent 简介\n\n> [!TIP]\n> 译者注:Agent 的业内术语是“智能体”。本译文将保留 agent,不作翻译,以带来更高效的阅读体验。(在中文为主的文章中,It's easier to 注意到英文。Attention Is "
  },
  {
    "path": "docs/source/zh/conceptual_guides/react.md",
    "chars": 1090,
    "preview": "# 多步骤 agent 是如何工作的?\n\nReAct 框架([Yao et al., 2022](https://huggingface.co/papers/2210.03629))是目前构建 agent 的主要方法。\n\n该名称基于两个词的"
  },
  {
    "path": "docs/source/zh/examples/multiagents.md",
    "chars": 5374,
    "preview": "# 编排 multi-agent 系统 🤖🤝🤖\n\n[[open-in-colab]]\n\n此notebook将构建一个 **multi-agent 网络浏览器:一个有多个代理协作,使用网络进行搜索解决问题的代理系统**\n\n`ManagedAg"
  },
  {
    "path": "docs/source/zh/examples/rag.md",
    "chars": 4576,
    "preview": "# Agentic RAG\n\n[[open-in-colab]]\n\nRetrieval-Augmented-Generation (RAG) 是“使用大语言模型(LLM)来回答用户查询,但基于从知识库中检索的信息”。它比使用普通或微调的 L"
  },
  {
    "path": "docs/source/zh/examples/text_to_sql.md",
    "chars": 4964,
    "preview": "# Text-to-SQL\n\n[[open-in-colab]]\n\n在此教程中,我们将看到如何使用 `smolagents` 实现一个利用 SQL 的 agent。\n\n> 让我们从经典问题开始:为什么不简单地使用标准的 text-to-SQ"
  },
  {
    "path": "docs/source/zh/examples/web_browser.md",
    "chars": 6042,
    "preview": "# 使用Agent实现网页浏览器自动化 🤖🌐\n\n[[open-in-colab]]\n\n在本notebook中,我们将创建一个**基于Agent的网页浏览器自动化系统**!该系统可以自动导航网站、与网页元素交互并提取信息。\n\n该Agent将能"
  },
  {
    "path": "docs/source/zh/guided_tour.md",
    "chars": 14436,
    "preview": "# Agents - 导览\n\n[[open-in-colab]]\n\n在本导览中,您将学习如何构建一个 agent(智能体),如何运行它,以及如何自定义它以使其更好地适应您的使用场景。\n\n> [!TIP]\n> 译者注:Agent 的业内术语是"
  },
  {
    "path": "docs/source/zh/index.md",
    "chars": 2212,
    "preview": "# `smolagents`\n\n这是构建强大 agent 的最简单框架!顺便问一下,什么是 \"agent\"?我们在[此页面](conceptual_guides/intro_agents)提供了我们的定义,您还可以找到关于何时使用或不使用它"
  },
  {
    "path": "docs/source/zh/reference/agents.md",
    "chars": 960,
    "preview": "# Agents(智能体)\n\n<Tip warning={true}>\n\nSmolagents 是一个实验性的 API,可能会随时发生变化。由于 API 或底层模型可能发生变化,代理返回的结果也可能有所不同。\n\n</Tip>\n\n要了解有关智"
  },
  {
    "path": "docs/source/zh/reference/models.md",
    "chars": 4040,
    "preview": "# 模型\n\n<Tip warning={true}>\n\nSmolagents 是一个实验性 API,其可能会随时发生更改。由于 API 或底层模型可能会变化,智能体返回的结果可能会有所不同。\n\n</Tip>\n\n要了解有关智能体和工具的更多信"
  },
  {
    "path": "docs/source/zh/reference/tools.md",
    "chars": 1291,
    "preview": "# 工具\n\n<Tip warning={true}>\n\nSmolagents 是一个实验性 API,可能会随时更改。由于 API 或底层模型可能发生变化,代理返回的结果可能会有所不同。\n\n</Tip>\n\n要了解更多关于智能体和工具的信息,请"
  },
  {
    "path": "docs/source/zh/tutorials/building_good_agents.md",
    "chars": 17288,
    "preview": "# 构建好用的 agent\n\n[[open-in-colab]]\n\n能良好工作的 agent 和不能工作的 agent 之间,有天壤之别。\n我们怎么样才能构建出属于前者的 agent 呢?\n在本指南中,我们将看到构建 agent 的最佳实践"
  },
  {
    "path": "docs/source/zh/tutorials/inspect_runs.md",
    "chars": 4946,
    "preview": "# 使用 OpenTelemetry 检查运行记录\n\n[[open-in-colab]]\n\n> [!TIP]\n> 如果您是初次构建Agent,建议先阅读 [Agent 入门指南](../conceptual_guides/intro_age"
  },
  {
    "path": "docs/source/zh/tutorials/memory.md",
    "chars": 3702,
    "preview": "# 📚 管理Agent的记忆\n\n[[open-in-colab]]\n\n归根结底,Agent可以定义为由几个简单组件构成:它拥有工具、提示词。最重要的是,它具备对过往步骤的记忆,能够追溯完整的规划、执行和错误历史。\n\n### 回放Agent的"
  },
  {
    "path": "docs/source/zh/tutorials/secure_code_execution.md",
    "chars": 2183,
    "preview": "# 安全代码执行\n\n[[open-in-colab]]\n\n> [!TIP]\n> 如果你是第一次构建 agent,请先阅读 [agent 介绍](../conceptual_guides/intro_agents) 和 [smolagents"
  },
  {
    "path": "docs/source/zh/tutorials/tools.md",
    "chars": 6681,
    "preview": "# 工具\n\n[[open-in-colab]]\n\n在这里,我们将学习高级工具的使用。\n\n> [!TIP]\n> 如果你是构建 agent 的新手,请确保先阅读 [agent 介绍](../conceptual_guides/intro_age"
  },
  {
    "path": "e2b.toml",
    "chars": 569,
    "preview": "# This is a config for E2B sandbox template.\n# You can use template ID (qywp2ctmu2q7jzprcf4j) to create a sandbox:\n\n# Py"
  },
  {
    "path": "examples/agent_from_any_llm.py",
    "chars": 2259,
    "preview": "from smolagents import (\n    CodeAgent,\n    InferenceClientModel,\n    LiteLLMModel,\n    OpenAIModel,\n    ToolCallingAgen"
  },
  {
    "path": "examples/async_agent/README.md",
    "chars": 1897,
    "preview": "# Async Applications with Agents\n\nThis example demonstrates how to use a `CodeAgent` from the `smolagents` library in an"
  },
  {
    "path": "examples/async_agent/main.py",
    "chars": 1422,
    "preview": "\"\"\"\nAsync CodeAgent Example with Starlette\n\nThis example demonstrates how to use a CodeAgent in an async Starlette app,\n"
  },
  {
    "path": "examples/async_agent/requirements.txt",
    "chars": 35,
    "preview": "smolagents\nstarlette\nanyio\nuvicorn\n"
  },
  {
    "path": "examples/gradio_ui.py",
    "chars": 503,
    "preview": "from smolagents import CodeAgent, GradioUI, InferenceClientModel, WebSearchTool\n\n\nagent = CodeAgent(\n    tools=[WebSearc"
  },
  {
    "path": "examples/inspect_multiagent_run.py",
    "chars": 1028,
    "preview": "from openinference.instrumentation.smolagents import SmolagentsInstrumentor\nfrom phoenix.otel import register\n\n\nregister"
  },
  {
    "path": "examples/multi_llm_agent.py",
    "chars": 1488,
    "preview": "import os\n\nfrom smolagents import CodeAgent, LiteLLMRouterModel, WebSearchTool\n\n\n# Make sure to setup the necessary envi"
  },
  {
    "path": "examples/multiple_tools.py",
    "chars": 8527,
    "preview": "import requests\n\n# from smolagents.agents import ToolCallingAgent\nfrom smolagents import CodeAgent, InferenceClientModel"
  },
  {
    "path": "examples/open_deep_research/README.md",
    "chars": 2518,
    "preview": "# Open Deep Research\n\nWelcome to this open replication of [OpenAI's Deep Research](https://openai.com/index/introducing-"
  },
  {
    "path": "examples/open_deep_research/analysis.ipynb",
    "chars": 13131,
    "preview": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": "
  },
  {
    "path": "examples/open_deep_research/app.py",
    "chars": 167,
    "preview": "from run import create_agent\n\nfrom smolagents.gradio_ui import GradioUI\n\n\nagent = create_agent()\n\ndemo = GradioUI(agent)"
  },
  {
    "path": "examples/open_deep_research/requirements.txt",
    "chars": 710,
    "preview": "anthropic>=0.37.1\naudioop-lts<1.0; python_version >= \"3.13\" # required to use pydub in Python >=3.13; LTS port of the re"
  },
  {
    "path": "examples/open_deep_research/run.py",
    "chars": 3874,
    "preview": "import argparse\nimport os\nimport threading\n\nfrom dotenv import load_dotenv\nfrom huggingface_hub import login\nfrom script"
  },
  {
    "path": "examples/open_deep_research/run_gaia.py",
    "chars": 11937,
    "preview": "# EXAMPLE COMMAND: from folder examples/open_deep_research, run: python run_gaia.py --concurrency 32 --run-name generate"
  },
  {
    "path": "examples/open_deep_research/scripts/cookies.py",
    "chars": 23304,
    "preview": "from requests.cookies import RequestsCookieJar\n\n\nCOOKIES_LIST = [\n    {\n        \"domain\": \".youtube.com\",\n        \"expir"
  },
  {
    "path": "examples/open_deep_research/scripts/gaia_scorer.py",
    "chars": 3827,
    "preview": "import re\nimport string\nimport warnings\n\n\ndef normalize_number_str(number_str: str) -> float:\n    # we replace these com"
  },
  {
    "path": "examples/open_deep_research/scripts/mdconvert.py",
    "chars": 36705,
    "preview": "# This is copied from Magentic-one's great repo: https://github.com/microsoft/autogen/blob/v0.4.4/python/packages/autoge"
  },
  {
    "path": "examples/open_deep_research/scripts/reformulator.py",
    "chars": 4430,
    "preview": "# Shamelessly stolen from Microsoft Autogen team: thanks to them for this great resource!\n# https://github.com/microsoft"
  },
  {
    "path": "examples/open_deep_research/scripts/run_agents.py",
    "chars": 3738,
    "preview": "import json\nimport os\nimport shutil\nimport textwrap\nfrom pathlib import Path\n\n# import tqdm.asyncio\nfrom smolagents.util"
  },
  {
    "path": "examples/open_deep_research/scripts/text_inspector_tool.py",
    "chars": 4687,
    "preview": "from smolagents import Tool\nfrom smolagents.models import Model\n\n\nclass TextInspectorTool(Tool):\n    name = \"inspect_fil"
  },
  {
    "path": "examples/open_deep_research/scripts/text_web_browser.py",
    "chars": 23353,
    "preview": "# Shamelessly stolen from Microsoft Autogen team: thanks to them for this great resource!\n# https://github.com/microsoft"
  },
  {
    "path": "examples/open_deep_research/scripts/visual_qa.py",
    "chars": 6107,
    "preview": "import base64\nimport json\nimport mimetypes\nimport os\nimport uuid\nfrom io import BytesIO\n\nimport PIL.Image\nimport request"
  },
  {
    "path": "examples/open_deep_research/visual_vs_text_browser.ipynb",
    "chars": 11008,
    "preview": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Compare a text-based vs a vision-"
  },
  {
    "path": "examples/plan_customization/README.md",
    "chars": 4347,
    "preview": "# Human-in-the-Loop: Customize Agent Plan Interactively\n\nThis example demonstrates advanced usage of the smolagents libr"
  },
  {
    "path": "examples/plan_customization/plan_customization.py",
    "chars": 5791,
    "preview": "\"\"\"\nPlan Customization Example\n\nThis example demonstrates how to use step callbacks to interrupt the agent after\nplan cr"
  },
  {
    "path": "examples/rag.py",
    "chars": 2245,
    "preview": "# from huggingface_hub import login\n\n# login()\nimport datasets\nfrom langchain.docstore.document import Document\nfrom lan"
  },
  {
    "path": "examples/rag_using_chromadb.py",
    "chars": 4049,
    "preview": "import os\n\nimport datasets\nfrom langchain.docstore.document import Document\nfrom langchain.text_splitter import Recursiv"
  },
  {
    "path": "examples/sandboxed_execution.py",
    "chars": 1606,
    "preview": "from smolagents import CodeAgent, InferenceClientModel, WebSearchTool\n\n\nmodel = InferenceClientModel()\n\n# Blaxel executo"
  },
  {
    "path": "examples/server/README.md",
    "chars": 2467,
    "preview": "# Smolagents Chat Server Demo\n\nThis is a simple web server that provides a chat interface for interacting with an AI cod"
  },
  {
    "path": "examples/server/main.py",
    "chars": 6514,
    "preview": "from anyio import to_thread\nfrom starlette.applications import Starlette\nfrom starlette.responses import HTMLResponse, J"
  },
  {
    "path": "examples/smolagents_benchmark/run.py",
    "chars": 8363,
    "preview": "import argparse\nimport datetime\nimport json\nimport os\nimport threading\nimport time\nfrom concurrent.futures import Thread"
  },
  {
    "path": "examples/smolagents_benchmark/score.ipynb",
    "chars": 14780,
    "preview": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": "
  },
  {
    "path": "examples/structured_output_tool.py",
    "chars": 2373,
    "preview": "# How to run with uv:\n#   uv run structured_output_tool.py\n#\n# Modify the smolagents dependency to point to the local sm"
  },
  {
    "path": "examples/text_to_sql.py",
    "chars": 2175,
    "preview": "from sqlalchemy import (\n    Column,\n    Float,\n    Integer,\n    MetaData,\n    String,\n    Table,\n    create_engine,\n   "
  },
  {
    "path": "pyproject.toml",
    "chars": 2943,
    "preview": "[build-system]\nrequires = [\"setuptools\"]\nbuild-backend = \"setuptools.build_meta\"\n\n[project]\nname = \"smolagents\"\nversion "
  },
  {
    "path": "src/smolagents/__init__.py",
    "chars": 1107,
    "preview": "#!/usr/bin/env python\n# coding=utf-8\n\n# Copyright 2024 The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed unde"
  },
  {
    "path": "src/smolagents/_function_type_hints_utils.py",
    "chars": 16005,
    "preview": "#!/usr/bin/env python\n# coding=utf-8\n\n# Copyright 2025 The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed unde"
  },
  {
    "path": "src/smolagents/agent_types.py",
    "chars": 9215,
    "preview": "# coding=utf-8\n# Copyright 2024 HuggingFace Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# y"
  },
  {
    "path": "src/smolagents/agents.py",
    "chars": 80856,
    "preview": "#!/usr/bin/env python\n# coding=utf-8\n\n# Copyright 2024 The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed unde"
  },
  {
    "path": "src/smolagents/cli.py",
    "chars": 9646,
    "preview": "#!/usr/bin/env python\n# coding=utf-8\n\n# Copyright 2025 The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed unde"
  },
  {
    "path": "src/smolagents/default_tools.py",
    "chars": 24557,
    "preview": "#!/usr/bin/env python\n# coding=utf-8\n\n# Copyright 2024 The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed unde"
  },
  {
    "path": "src/smolagents/gradio_ui.py",
    "chars": 19076,
    "preview": "#!/usr/bin/env python\n# coding=utf-8\n# Copyright 2024 The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed under"
  },
  {
    "path": "src/smolagents/local_python_executor.py",
    "chars": 68111,
    "preview": "#!/usr/bin/env python\n# coding=utf-8\n\n# Copyright 2024 The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed unde"
  },
  {
    "path": "src/smolagents/mcp_client.py",
    "chars": 7123,
    "preview": "#!/usr/bin/env python\n# coding=utf-8\n\n# Copyright 2025 The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed unde"
  },
  {
    "path": "src/smolagents/memory.py",
    "chars": 12341,
    "preview": "import inspect\nfrom dataclasses import asdict, dataclass\nfrom logging import getLogger\nfrom typing import TYPE_CHECKING,"
  },
  {
    "path": "src/smolagents/models.py",
    "chars": 86051,
    "preview": "# Copyright 2024 The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the"
  },
  {
    "path": "src/smolagents/monitoring.py",
    "chars": 9699,
    "preview": "#!/usr/bin/env python\n# coding=utf-8\n\n# Copyright 2024 The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed unde"
  },
  {
    "path": "src/smolagents/prompts/code_agent.yaml",
    "chars": 17052,
    "preview": "system_prompt: |-\n  You are an expert assistant who can solve any task using code blobs. You will be given a task to sol"
  },
  {
    "path": "src/smolagents/prompts/structured_code_agent.yaml",
    "chars": 15103,
    "preview": "system_prompt: |-\n  You are an expert assistant who can solve any task using code blobs. You will be given a task to sol"
  },
  {
    "path": "src/smolagents/prompts/toolcalling_agent.yaml",
    "chars": 10279,
    "preview": "system_prompt: |-\n  You are an expert assistant who can solve any task using tool calls. You will be given a task to sol"
  },
  {
    "path": "src/smolagents/remote_executors.py",
    "chars": 59247,
    "preview": "#!/usr/bin/env python\n# coding=utf-8\n\n# Copyright 2024 The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed unde"
  },
  {
    "path": "src/smolagents/serialization.py",
    "chars": 21194,
    "preview": "#!/usr/bin/env python\n# coding=utf-8\n\n# Copyright 2024 The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed unde"
  },
  {
    "path": "src/smolagents/tool_validation.py",
    "chars": 10699,
    "preview": "import ast\nimport builtins\nfrom itertools import zip_longest\n\nfrom .utils import BASE_BUILTIN_MODULES, get_source, is_va"
  },
  {
    "path": "src/smolagents/tools.py",
    "chars": 59872,
    "preview": "#!/usr/bin/env python\n# coding=utf-8\n\n# Copyright 2024 The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed unde"
  },
  {
    "path": "src/smolagents/utils.py",
    "chars": 21238,
    "preview": "#!/usr/bin/env python\n# coding=utf-8\n\n# Copyright 2024 The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed unde"
  },
  {
    "path": "src/smolagents/vision_web_browser.py",
    "chars": 8699,
    "preview": "import argparse\nfrom io import BytesIO\nfrom time import sleep\n\nimport helium\nimport PIL.Image\nfrom dotenv import load_do"
  },
  {
    "path": "tests/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "tests/conftest.py",
    "chars": 735,
    "preview": "from unittest.mock import patch\n\nimport pytest\n\nfrom smolagents.agents import MultiStepAgent\nfrom smolagents.monitoring "
  },
  {
    "path": "tests/fixtures/agents.py",
    "chars": 5219,
    "preview": "import pytest\n\n\nAGENT_DICTS = {\n    \"v1.9\": {\n        \"tools\": [],\n        \"model\": {\n            \"class\": \"InferenceCli"
  },
  {
    "path": "tests/fixtures/tools.py",
    "chars": 4355,
    "preview": "import pytest\n\nfrom smolagents.tools import Tool, tool\n\n\n@pytest.fixture\ndef test_tool():\n    class TestTool(Tool):\n    "
  },
  {
    "path": "tests/test_agents.py",
    "chars": 106332,
    "preview": "# coding=utf-8\n# Copyright 2024 HuggingFace Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# y"
  },
  {
    "path": "tests/test_all_docs.py",
    "chars": 6342,
    "preview": "# coding=utf-8\n# Copyright 2024 HuggingFace Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# y"
  },
  {
    "path": "tests/test_cli.py",
    "chars": 5029,
    "preview": "from unittest.mock import patch\n\nimport pytest\n\nfrom smolagents.cli import load_model\nfrom smolagents.local_python_execu"
  },
  {
    "path": "tests/test_default_tools.py",
    "chars": 6049,
    "preview": "# coding=utf-8\n# Copyright 2024 HuggingFace Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# y"
  },
  {
    "path": "tests/test_final_answer.py",
    "chars": 1870,
    "preview": "# coding=utf-8\n# Copyright 2024 HuggingFace Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# y"
  },
  {
    "path": "tests/test_function_type_hints_utils.py",
    "chars": 16686,
    "preview": "# coding=utf-8\n# Copyright 2024 HuggingFace Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# y"
  },
  {
    "path": "tests/test_gradio_ui.py",
    "chars": 16224,
    "preview": "# coding=utf-8\n# Copyright 2024 HuggingFace Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# y"
  },
  {
    "path": "tests/test_import.py",
    "chars": 1052,
    "preview": "import os\nimport subprocess\nimport tempfile\n\n\ndef test_import_smolagents_without_extras(monkeypatch):\n    monkeypatch.de"
  },
  {
    "path": "tests/test_local_python_executor.py",
    "chars": 110030,
    "preview": "# coding=utf-8\n# Copyright 2024 HuggingFace Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# y"
  },
  {
    "path": "tests/test_mcp_client.py",
    "chars": 5121,
    "preview": "import json\nfrom textwrap import dedent\n\nimport pytest\nfrom mcp import StdioServerParameters\n\nfrom smolagents.mcp_client"
  },
  {
    "path": "tests/test_memory.py",
    "chars": 10000,
    "preview": "import json\n\nimport pytest\nfrom PIL import Image\n\nfrom smolagents.agents import ToolCall\nfrom smolagents.memory import ("
  },
  {
    "path": "tests/test_models.py",
    "chars": 46404,
    "preview": "# coding=utf-8\n# Copyright 2024 HuggingFace Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# y"
  },
  {
    "path": "tests/test_monitoring.py",
    "chars": 8314,
    "preview": "# coding=utf-8\n# Copyright 2024 HuggingFace Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# y"
  },
  {
    "path": "tests/test_remote_executors.py",
    "chars": 28512,
    "preview": "import importlib\nimport io\nfrom textwrap import dedent\nfrom unittest.mock import MagicMock, patch\n\nimport docker\nimport "
  },
  {
    "path": "tests/test_search.py",
    "chars": 1108,
    "preview": "# coding=utf-8\n# Copyright 2024 HuggingFace Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# y"
  },
  {
    "path": "tests/test_serialization.py",
    "chars": 31584,
    "preview": "#!/usr/bin/env python\n# coding=utf-8\n\n# Copyright 2024 The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed unde"
  },
  {
    "path": "tests/test_telemetry.py",
    "chars": 3250,
    "preview": "# coding=utf-8\n# Copyright 2025 HuggingFace Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# y"
  },
  {
    "path": "tests/test_tool_validation.py",
    "chars": 5530,
    "preview": "import ast\nfrom textwrap import dedent\n\nimport pytest\n\nfrom smolagents.default_tools import (\n    DuckDuckGoSearchTool,\n"
  },
  {
    "path": "tests/test_tools.py",
    "chars": 41254,
    "preview": "# coding=utf-8\n# Copyright 2024 HuggingFace Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# y"
  },
  {
    "path": "tests/test_types.py",
    "chars": 3745,
    "preview": "# coding=utf-8\n# Copyright 2024 HuggingFace Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# y"
  },
  {
    "path": "tests/test_utils.py",
    "chars": 16057,
    "preview": "# coding=utf-8\n# Copyright 2024 HuggingFace Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# y"
  },
  {
    "path": "tests/test_vision_web_browser.py",
    "chars": 5195,
    "preview": "\"\"\"Test XPath injection vulnerability fix in vision_web_browser.py\"\"\"\n\nfrom unittest.mock import Mock, patch\n\nimport pyt"
  },
  {
    "path": "tests/utils/markers.py",
    "chars": 985,
    "preview": "# coding=utf-8\n# Copyright 2024 HuggingFace Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# y"
  }
]

About this extraction

This page contains the full source code of the huggingface/smolagents GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 183 files (1.8 MB), approximately 444.9k tokens, and a symbol index with 1426 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!