Kevin Meneses
โ† Back to articles

Build an AI Research Assistant With Python and Decodo

AI AgentsPythonWeb ScrapingLLM
Build an AI Research Assistant With Python and Decodo

LLMs don't know what happened this morning.

Ask one about a law that changed last month, a product launched last week or this quarter's earnings, and you get one of two answers: an apology or a confident guess.

If you're:

  • building AI agents that need current facts,
  • writing newsletters or market briefs,
  • or doing due diligence on companies and competitors,

guessing isn't good enough. You need an AI research assistant that reads the web before it answers and shows you where every claim came from.

This guide builds one in Python in about 100 lines, using Decodo's Web Data API to search and read the web, and an OpenAI model to reason over what it finds.

Disclosure: Decodo sponsored this guide, and the Decodo links are affiliate links. The code, tests and outputs are mine.

TL;DR

  • An AI research assistant is a pipeline, not a smarter model: search โ†’ pick sources โ†’ read โ†’ synthesize โ†’ cite.
  • Decodo's /search endpoint returns parsed Google results. /scrape with "markdown": true turns each page into LLM-ready text.
  • The LLM writes the report and cites every claim as [1], [2], so you can check it.
  • Each question costs 6 Decodo requests (1 search + 5 scrapes). The free plan covers roughly 900 to 1,500 research reports a month.
  • Full script below, ready to run with two API keys.

Why LLMs are bad researchers on their own

Every model has a training cutoff. Anything after it doesn't exist for the model.

Ask anyway and it does what it was trained to do: produce a plausible answer. Plausible is not the same as correct, and without sources you can't tell which one you got.

The usual fix is "give the model web access." In practice that turns into three separate problems:

  • a search API to find pages,
  • a scraper to read them,
  • an HTML cleaner so the model doesn't drown in navigation menus and cookie banners.

Then a third of the pages return a 403 because the site blocks bots.

Most research agents fail at the reading step, not the thinking step.

The real problem is the pipeline

A research assistant doesn't need a bigger model.

It needs a better pipeline: one that finds the right pages, actually gets their content and hands the model clean text with clear source labels.

Get the inputs right and the model's job becomes simple. Summarize what's in front of you, and cite it.

How the AI research assistant works

Here's the full pipeline:

AI research assistant pipeline: Decodo search, pick sources, Decodo scrape as Markdown, LLM synthesis, cited report

Five steps, two APIs:

  1. /search sends the question to Google and returns ranked results. 1 request.
  2. Pick sources keeps the top 5, one per domain, and skips video, forum and login-wall pages. Plain Python.
  3. /scrape reads each page in parallel and returns Markdown instead of HTML. 5 requests.
  4. The LLM (GPT-5.5 here) reads the numbered sources and writes a short report, citing each claim. OpenAI API.
  5. report.md saves the report with its source list.

Decodo handles everything that touches the web: proxies, JavaScript rendering and anti-bot protection, behind one API key. The LLM handles the reasoning.

๐Ÿ‘‰ Get Decodo's free Web Data API plan: up to 10K requests a month, no credit card.

Set up the project

You need two keys:

pip install requests openai
export DECODO_API_KEY="your_decodo_key"
export OPENAI_API_KEY="your_openai_key"

Shared config for the Decodo calls:

import os
import requests

DECODO_URL = "https://data.decodo.com/v1"
DECODO_HEADERS = {
    "Authorization": f"Bearer {os.environ['DECODO_API_KEY']}",
    "Content-Type": "application/json",
    "Accept": "application/json",
}

Step 1: Search Google with /search

/search returns parsed Google results in one call. No HTML parsing, no proxy setup.

def search(question: str) -> list[dict]:
    r = requests.post(f"{DECODO_URL}/search", headers=DECODO_HEADERS,
                      json={"query": question, "geo": "United States"}, timeout=60)
    r.raise_for_status()
    return r.json().get("organic", [])

Each result comes with rank, title, link and description.

Step 2: Pick the sources worth reading

Five results from the same domain give you one perspective five times. Keep one page per domain and skip pages that won't have readable text. LinkedIn is on the list because it serves a sign-in wall instead of the article, which I found the hard way while testing.

One more thing I found while testing: a few results come back as Google redirect links (https://www.google.com/goto?url=...) instead of the page URL. In my EU AI Act run, the European Commission's own AI Act page was one of them. resolve_link() follows that one redirect so the report cites the real page and the one-per-domain rule works.

from urllib.parse import urlparse

MAX_SOURCES = 5
SKIP_DOMAINS = {"www.youtube.com", "www.reddit.com", "www.linkedin.com"}  # video, forums, login walls

def resolve_link(link: str) -> str:
    # Some results come back as Google redirect links; follow one hop to get the real URL
    if "google.com/goto" not in link:
        return link
    try:
        r = requests.get(link, allow_redirects=False, timeout=10)
        return r.headers.get("Location", link)
    except requests.RequestException:
        return link

def pick_sources(results: list[dict]) -> list[dict]:
    seen, picked = set(), []
    for item in results:
        item = {**item, "link": resolve_link(item["link"])}
        domain = urlparse(item["link"]).netloc
        if domain in seen or domain in SKIP_DOMAINS:
            continue
        seen.add(domain)
        picked.append(item)
        if len(picked) == MAX_SOURCES:
            break
    return picked

This step is free. It also saves requests, because you only scrape pages you'll actually use.

Step 3: Read each page as Markdown with /scrape

This is where most research agents break. Decodo's /scrape handles proxies and anti-bot protection, and "markdown": true strips the page down to the text an LLM needs.

MAX_CHARS_PER_SOURCE = 20_000

CONFIGS = [  # cheapest first; failed attempts aren't billed
    {"proxy_pool": "standard"},
    {"proxy_pool": "premium"},
    {"proxy_pool": "premium", "headless": "html"},
]

def read_page(url: str) -> str:
    for config in CONFIGS:
        try:
            r = requests.post(f"{DECODO_URL}/scrape", headers=DECODO_HEADERS,
                              json={"url": url, "markdown": True, **config}, timeout=180)
            result = (r.json().get("results") or [{}])[0] if r.ok else {}
        except (requests.RequestException, ValueError):
            continue
        if result.get("status_code") == 200 and result.get("content"):
            return result["content"][:MAX_CHARS_PER_SOURCE]
    return ""

Three details matter here:

  • CONFIGS tries the cheap standard pool first, then premium, then premium with JavaScript rendering. Some sites (Amazon and BBC in my tests) reject standard requests, and failed attempts aren't billed, so you only pay for the config that works.
  • The 20K-character cap keeps the prompt small and the cost predictable.
  • Failures return an empty string, so one blocked page doesn't kill the whole report.

Step 4: Synthesize a cited report with an LLM

Each source goes into the prompt with a number, a title and a URL. The model answers using only those sources and cites them as [1], [2].

from datetime import date
from openai import OpenAI

openai_client = OpenAI()

def synthesize(question: str, sources: list[dict]) -> str:
    context = "\n\n".join(
        f"<source id=\"{i}\" title=\"{s['title']}\" url=\"{s['link']}\">\n{s['content']}\n</source>"
        for i, s in enumerate(sources, start=1)
    )
    prompt = (
        f"Today is {date.today():%B %d, %Y}. Answer the research question using only the sources below.\n"
        "Write a short report in Markdown: a 2-3 sentence summary, then key findings as bullets.\n"
        "Cite every claim with the source number in brackets, like [2]. "
        "If the sources disagree or don't answer something, say so.\n\n"
        f"{context}\n\nResearch question: {question}"
    )
    response = openai_client.responses.create(model="gpt-5.5", input=prompt)
    return response.output_text

Two lines in the prompt do most of the work:

  • "using only the sources below" keeps the model from filling gaps with memory.
  • "If the sources disagree or don't answer something, say so" gives it permission to be uncertain instead of inventing an answer.

The model call itself is one line with OpenAI's Responses API. Any capable model works here: the prompt and the sources do the heavy lifting, so you can swap gpt-5.5 for a cheaper model and compare.

Step 5: Put it together

The last step runs everything, reads the pages in parallel and saves the report with its sources.

import sys
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

def research(question: str) -> Path:
    sources = pick_sources(search(question))
    print(f"Reading {len(sources)} sources...")

    with ThreadPoolExecutor(max_workers=MAX_SOURCES) as pool:
        contents = list(pool.map(read_page, [s["link"] for s in sources]))
    sources = [{**s, "content": c} for s, c in zip(sources, contents) if c]

    report = synthesize(question, sources)
    refs = "\n".join(f"{i}. [{s['title']}]({s['link']})" for i, s in enumerate(sources, start=1))

    out = Path("report.md")
    out.write_text(f"# {question}\n\n{report}\n\n## Sources\n\n{refs}\n", encoding="utf-8")
    print(f"Report saved to {out} ({len(sources)} sources, {1 + len(sources)} Decodo requests)")
    return out

if __name__ == "__main__":
    research(sys.argv[1])

Practical example: research a question that changed this year

Run it with a question no model could answer from training data alone:

python research_assistant.py "What changed in the EU AI Act in 2026?"

Console output:

Reading 5 sources...
Report saved to report.md (5 sources, 6 Decodo requests)

The whole run took 32 seconds on my machine. Google returned a LinkedIn article in the top 5, so pick_sources() skipped it and took the next result.

And the generated report.md:

# What changed in the EU AI Act in 2026?

## Summary

In 2026, the EU AI Act was changed chiefly by the AI Omnibus, which entered into force on 27 July 2026 and simplified implementation while delaying the toughest high-risk AI obligations [2]. At the same time, several parts of the Act started applying in 2026: transparency rules took effect on 2 August 2026, and a new ban on AI systems generating non-consensual intimate or child sexual abuse material became applicable on 2 December 2026 [2][4].

## Key findings

- **High-risk AI deadlines were delayed and fixed:** Rules for high-risk AI systems in certain sensitive areas such as biometrics, critical infrastructure, education, employment, migration, asylum, and border control now apply from **2 December 2027** [2]. Rules for high-risk AI embedded in regulated products such as lifts or toys now apply from **2 August 2028** [2].

- **Transparency rules started applying on 2 August 2026:** The Act's transparency obligations took effect on 2 August 2026 [4]. These rules require, for example, clear labelling of certain AI-generated or manipulated content and informing users when they interact with an AI system such as a chatbot, AI agent, or avatar [4].

- **The number/counting of new prohibited practices is not fully consistent across sources:** The Commission source describes the new rule as "Prohibition 9" and lists nine prohibited practices in total [2]. Source 1 says that in 2026 the Digital Omnibus added "two" prohibited practices, so the sources differ in how they count or describe the additions [1][2].

...

## Sources

1. [EU Artificial Intelligence Act | Up-to-date developments and ...](https://artificialintelligenceact.eu/)
2. [AI Act | Shaping Europe's digital future - European Union](https://digital-strategy.ec.europa.eu/en/policies/regulatory-framework-ai)
3. [A comprehensive EU AI Act Summary [August 2026 update]](https://www.softwareimprovementgroup.com/blog/eu-ai-act-summary/)
4. [Safer and more transparent AI - European Commission](https://commission.europa.eu/news-and-media/news/safer-and-more-transparent-ai-2026-08-02_en)
5. [What is the EU AI Act?](https://www.ibm.com/think/topics/eu-ai-act)

That's 3 of the 10 findings the model wrote. Look at the third one: two sources count the new prohibitions differently, and instead of picking one the model says so. That's the "if the sources disagree, say so" line in the prompt doing its job.

Every bullet points back to a numbered source. Open the link, check the claim, done.

That's the difference between a research assistant and a chatbot.

What one report costs

StepDecodo requestsNotes
/search1Parsed Google results
/scrape ร— 55Standard or premium proxy, Markdown
Total per question6

On Decodo's free plan, that's roughly 900 to 1,500 research reports a month, depending on how many sources need the premium pool, without paying anything for the web data.

On the OpenAI side, five capped sources come to roughly 25K input tokens per report. Lower MAX_CHARS_PER_SOURCE or MAX_SOURCES if you want to cut that further.

How to extend it

Once the basic pipeline works, these upgrades are a few lines each:

  • Run several queries per question. Ask the model to rewrite the question into 2โ€“3 search queries, then merge the results before picking sources.
  • Follow up automatically. /search also returns people_also_ask. Feed those questions back in for a deeper report.
  • Turn it into an agent tool. Wrap research() as a tool so an AI agent can call it whenever it needs fresh facts.
  • Read JavaScript-heavy sites. Add "headless": "html" to the /scrape payload for pages that render content in the browser.

If you're new to the Web Data API, the getting started guide covers all four endpoints, including /map and /crawl.

Key takeaways

  • Research quality depends on the inputs. Clean Markdown from the right pages matters more than model size.
  • Two endpoints cover the web side: /search to find sources and /scrape to read them, with one Decodo key.
  • Numbered sources plus a strict prompt give you a report you can verify, not just one you have to trust.

Build your own AI research assistant

The hard part of web research was never the reasoning. It was getting clean, current content from sites that don't want to be scraped.

๐Ÿ‘‰ Start with Decodo's free Web Data API plan

You get:

  • up to 10K requests every month, renewed automatically,
  • Google search results and page scraping with one key,
  • no credit card to sign up.

FAQs

How do I build an AI research assistant in Python?

Combine a search API, a scraper and an LLM. Search for the question, read the top pages as clean text, and ask the model to answer only from those pages and cite them. The script in this guide does it in about 100 lines.

Can an LLM search the web by itself?

Not on its own. A model only knows its training data. You need to fetch current pages and pass them in, either with a pipeline like this one or with a tool the model can call.

What's the best web search API for LLMs?

One that returns structured results and lets you read the pages behind them. Decodo's /search returns parsed Google results, and /scrape returns the page content as Markdown, which uses fewer tokens than raw HTML.

How do I stop an AI research assistant from hallucinating?

Give it numbered sources, tell it to answer only from them, require a citation for every claim, and allow it to say when the sources don't answer the question.

Is there a free web scraping API for AI projects?

Yes. Decodo's Web Data API has a recurring free plan with up to 10K requests a month and no credit card required.

LLMs will always have a training cutoff.

Your research assistant doesn't have to.

Looking for technical content for your company? I can help โ€” LinkedIn ยท kevinmenesesgonzalez@gmail.com