Back to Smolagents

Compare a text-based vs a vision-based browser

examples/open_deep_research/visual_vs_text_browser.ipynb

1.24.06.8 KB
Original Source

Compare a text-based vs a vision-based browser

Warning: this notebook is experimental, it probably won't work out of the box!

python
!pip install "smolagents[litellm,toolkit]" -q
python
import datasets


eval_ds = datasets.load_dataset("gaia-benchmark/GAIA", "2023_all")["validation"]
python
to_keep = [
    "What's the last line of the rhyme under the flavor",
    'Of the authors (First M. Last) that worked on the paper "Pie Menus or Linear Menus',
    "In Series 9, Episode 11 of Doctor Who, the Doctor is trapped inside an ever-shifting maze. What is this location called in the official script for the episode? Give the setting exactly as it appears in the first scene heading.",
    "Which contributor to the version of OpenCV where support was added for the Mask-RCNN model has the same name as a former Chinese head of government when the names are transliterated to the Latin alphabet?",
    "The photograph in the Whitney Museum of American Art's collection with accession number 2022.128 shows a person holding a book. Which military unit did the author of this book join in 1813? Answer without using articles.",
    "I went to Virtue restaurant & bar in Chicago for my birthday on March 22, 2021 and the main course I had was delicious! Unfortunately, when I went back about a month later on April 21, it was no longer on the dinner menu.",
    "In Emily Midkiff's June 2014 article in a journal named for the one of Hreidmar's ",
    "Under DDC 633 on Bielefeld University Library's BASE, as of 2020",
    "In the 2018 VSCode blog post on replit.com, what was the command they clicked on in the last video to remove extra lines?",
    "The Metropolitan Museum of Art has a portrait in its collection with an accession number of 29.100.5. Of the consecrators and co-consecrators",
    "In Nature journal's Scientific Reports conference proceedings from 2012, in the article that did not mention plasmons or plasmonics, what nano-compound is studied?",
    'In the year 2022, and before December, what does "R" stand for in the three core policies of the type of content',
    "Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?",
]
eval_ds = eval_ds.filter(lambda row: any([el in row["Question"] for el in to_keep]))
eval_ds = eval_ds.rename_columns({"Question": "question", "Final answer": "true_answer", "Level": "task"})
python
import os

from dotenv import load_dotenv
from huggingface_hub import login


load_dotenv(override=True)

login(os.getenv("HF_TOKEN"))

Text browser

python
from scripts.run_agents import answer_questions
from scripts.text_inspector_tool import TextInspectorTool
from scripts.text_web_browser import (
    ArchiveSearchTool,
    FinderTool,
    FindNextTool,
    NavigationalSearchTool,
    PageDownTool,
    PageUpTool,
    SearchInformationTool,
    VisitTool,
)
from scripts.visual_qa import VisualQAGPT4Tool

from smolagents import CodeAgent, LiteLLMModel


proprietary_model = LiteLLMModel(model_id="gpt-4o")
python
### BUILD AGENTS & TOOLS

WEB_TOOLS = [
    SearchInformationTool(),
    NavigationalSearchTool(),
    VisitTool(),
    PageUpTool(),
    PageDownTool(),
    FinderTool(),
    FindNextTool(),
    ArchiveSearchTool(),
]


surfer_agent = CodeAgent(
    model=proprietary_model,
    tools=WEB_TOOLS,
    max_steps=20,
    verbosity_level=2,
)

results_text = answer_questions(
    eval_ds,
    surfer_agent,
    "code_gpt4o_27-01_text",
    reformulation_model=proprietary_model,
    output_folder="output_browsers",
    visual_inspection_tool=VisualQAGPT4Tool(),
    text_inspector_tool=TextInspectorTool(proprietary_model, 40000),
)

Vision browser

python
!pip install helium -q
python
from scripts.visual_qa import VisualQAGPT4Tool

from smolagents import CodeAgent, LiteLLMModel, WebSearchTool
from smolagents.vision_web_browser import (
    close_popups,
    go_back,
    helium_instructions,
    initialize_agent,
    save_screenshot,
    search_item_ctrl_f,
)


proprietary_model = LiteLLMModel(model_id="gpt-4o")
vision_browser_agent = initialize_agent(proprietary_model)
### BUILD AGENTS & TOOLS

CodeAgent(
    tools=[WebSearchTool(), go_back, close_popups, search_item_ctrl_f],
    model=proprietary_model,
    additional_authorized_imports=["helium"],
    step_callbacks=[save_screenshot],
    max_steps=20,
    verbosity_level=2,
)

results_vision = answer_questions(
    eval_ds,
    vision_browser_agent,
    "code_gpt4o_27-01_vision",
    reformulation_model=proprietary_model,
    output_folder="output_browsers",
    visual_inspection_tool=VisualQAGPT4Tool(),
    text_inspector_tool=TextInspectorTool(proprietary_model, 40000),
    postprompt=helium_instructions
    + "Any web browser controls won't work on .pdf urls, rather use the tool 'inspect_file_as_text' to read them",
)

Browser-use browser

python
!pip install browser-use lxml_html_clean -q
!playwright install
python
import asyncio

import nest_asyncio


nest_asyncio.apply()

from browser_use import Agent
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI


load_dotenv()


class BrowserUseAgent:
    logs = []

    def write_inner_memory_from_logs(self, summary_mode):
        return self.results

    def run(self, task, **kwargs):
        agent = Agent(
            task=task,
            llm=ChatOpenAI(model="gpt-4o"),
        )
        self.results = asyncio.get_event_loop().run_until_complete(agent.run())
        return self.results.history[-1].result[0].extracted_content


browser_use_agent = BrowserUseAgent()

results_browseruse = answer_questions(
    eval_ds,
    browser_use_agent,
    "gpt-4o_27-01_browseruse",
    reformulation_model=proprietary_model,
    output_folder="output_browsers",
    visual_inspection_tool=VisualQAGPT4Tool(),
    text_inspector_tool=TextInspectorTool(proprietary_model, 40000),
    postprompt="",
    run_simple=True,
)

Get results

python
import pandas as pd
from scripts.gaia_scorer import question_scorer


results_vision, results_text, results_browseruse = (
    pd.DataFrame(results_vision),
    pd.DataFrame(results_text),
    pd.DataFrame(results_browseruse),
)

results_vision["is_correct"] = results_vision.apply(
    lambda x: question_scorer(x["prediction"], x["true_answer"]), axis=1
)
results_text["is_correct"] = results_text.apply(lambda x: question_scorer(x["prediction"], x["true_answer"]), axis=1)
results_browseruse["is_correct"] = results_browseruse.apply(
    lambda x: question_scorer(x["prediction"], x["true_answer"]), axis=1
)
python
results = pd.concat([results_vision, results_text, results_browseruse])
results.groupby("agent_name")["is_correct"].mean()
python
correct_vision_results = results_vision.loc[results_vision["is_correct"]]
correct_vision_results
python
false_text_results = results_text.loc[~results_text["is_correct"]]
false_text_results