Tutorials

How to Configure Proxies for LangChain Agents and Document Loaders

By IPMusk TeamUpdated 3 min read

Pass explicit proxies to WebBaseLoader for synchronous loads and either requests_kwargs or trust_env=True for async aiohttp fetches, because WebBaseLoader defaults to trust_env=False and does not forward Requests proxies to asyncio sessions. Use PlaywrightURLLoader with separate server, username, and password fields for JavaScript-rendered pages, and wrap a requests.Session inside a custom @tool so LangChain agents stay decoupled from any single scraper API.

IPMusk LangChain RAG guide diagram showing loader and tool proxy injection, Rotating Residential vs. Static ISP routing, and avoiding scraper vendor lock-in
LangChain proxy routing architecture: inject standard HTTP/SOCKS5 proxies across document loaders and custom agent tools, split Rotating Residential vs. Static ISP traffic, and avoid single-vendor scraper lock-in.

Configure proxies for WebBaseLoader sync, async, and Playwright

When you pull live documentation or web pages into a LangChain Retrieval-Augmented Generation (RAG) index, document loaders behave differently depending on whether they fetch synchronously or asynchronously. Inspecting langchain_community's WebBaseLoader source shows two subtle defaults that catch teams off guard during deployment.

First, passing proxies={"http": ..., "https": ...} configures self.session (a synchronous requests.Session) for load() and lazy_load(), while trust_env defaults to False so process-level HTTP_PROXY and HTTPS_PROXY environment variables are ignored unless you opt in. Second, async alazy_load() opens an aiohttp.ClientSession(trust_env=self.trust_env) and merges requests_kwargs into session.get() instead of reading self.session.proxies.

Keep credentials in environment variables rather than source control, and choose the loader option that matches your execution mode and target page:

  • Set raise_for_status=True on WebBaseLoader so HTTP 4xx and 5xx error pages raise immediately instead of being converted into Document text.
  • For aiohttp async fetches, note that native proxy="http://..." works directly with HTTP gateways; SOCKS5 inside aiohttp requires socks extensions rather than raw session URLs.
  • In PlaywrightURLLoader, supply proxy credentials as explicit keys (server, username, password) rather than relying on browser OS settings.
Python: configure WebBaseLoader (sync + async) and PlaywrightURLLoader (syntax checked)
import os
from langchain_community.document_loaders import PlaywrightURLLoader, WebBaseLoader

proxy_url = os.environ.get(
    "IPMUSK_PROXY_URL",
    "http://USERNAME:PASSWORD@gate.ipmusk.com:31212",
)

# Sync load() / lazy_load(): updates requests.Session.proxies
sync_loader = WebBaseLoader(
    web_paths=("https://example.com/docs",),
    proxies={"http": proxy_url, "https": proxy_url},
    requests_kwargs={"timeout": 15},
    raise_for_status=True,
)

# Async alazy_load(): aiohttp reads requests_kwargs['proxy'] or trust_env=True
async_loader = WebBaseLoader(
    web_paths=("https://example.com/docs",),
    requests_kwargs={"proxy": proxy_url, "timeout": 15},
    raise_for_status=True,
)

# JavaScript-heavy pages: pass server, username, and password separately
browser_loader = PlaywrightURLLoader(
    urls=["https://example.com/app"],
    proxy={
        "server": os.environ.get("IPMUSK_SERVER", "http://gate.ipmusk.com:31212"),
        "username": os.environ.get("IPMUSK_USERNAME", "USERNAME"),
        "password": os.environ.get("IPMUSK_PASSWORD", "PASSWORD"),
    },
    timeout=45000,
    wait_until="domcontentloaded",
)

Build a vendor-neutral agent tool and split proxy lines

Turnkey packages such as langchain-oxylabs combine agent tools and document loaders around one provider's API keys or scraper billing tier. That convenience works if you want a managed parser API, but it also ties your tool interface, retry behavior, and per-request routing to a single closed wrapper.

If you check langchain_community.utilities.requests, the built-in Requests model configures extra="forbid" and defines headers, aiosession, auth, and verify without a top-level proxies field. Defining a small custom @tool over requests.Session gives your LangChain agent explicit proxy routing, strict connect/read timeouts, and predictable error strings without external SDK lock-in:

Choosing IPMusk proxy lines for LangChain document loaders and agent tools
LangChain workloadRecommended IPMusk productKey routing behavior
Public web RAG ingestion, search result reads, and distributed fetchesRotating Residential (from $2.99 for 1 GB Trial; down to $0.80/GB at 1,000 GB)Routes via gate.ipmusk.com:31212 with per-request rotation or 1/3/10/30-min sticky sessions and country/state targeting
Allowlisted portals, regional documentation feeds, or stable cookie sessionsStatic ISP (Native ISP or ISP from $3.99/IP per 30 days)Dedicated assigned IP with host/port per resource, unmetered bandwidth, and 30 or 90 day renewal
Permissive internal mirrors or low-sensitivity hostsDatacenter (from $2.99/IP per 30 days)Lowest-cost unmetered assigned IP when targets accept hosting-provider ASNs
Python: define a proxy-routed LangChain @tool with bounded timeouts (syntax checked)
import os
import requests
from langchain_core.tools import tool

PROXY_URL = os.environ.get(
    "IPMUSK_PROXY_URL",
    "http://USERNAME:PASSWORD@gate.ipmusk.com:31212",
)

@tool
def fetch_public_page(url: str) -> str:
    """Fetch a public web page through the configured proxy pool."""
    with requests.Session() as session:
        session.proxies.update({"http": PROXY_URL, "https": PROXY_URL})
        resp = session.get(url, timeout=(10, 20))
        if resp.status_code == 407:
            raise RuntimeError("Proxy auth failed (407): check host, port, and credentials.")
        if resp.status_code in (403, 429):
            return f"Blocked ({resp.status_code}); retry later with backoff or a matching proxy line."
        resp.raise_for_status()
        return resp.text[:8000]

IPMusk proxies authenticate via username and password only; IP allowlisting is not supported. Generate country or available state credential strings on your workspace Connect screen or via build_proxy_url in MCP.

Stop 407, 403, and 429 error HTML from polluting vector indexes

By default, WebBaseLoader only raises HTTP errors if raise_for_status=True is enabled. Leaving that flag False silently turns 403 challenge interstitials or 429 rate-limit warnings into Document objects that get chunked, embedded, and retrieved as ground truth by your LLM.

Separate proxy authentication checks from target rate-limit handling before running large ingestion jobs:

  • HTTP 407 Proxy Authentication Required: stop the batch immediately rather than retrying inside an agent loop, and test host, port, username, and password with IPMusk's Proxy Checker (/tools/proxy-checker).
  • HTTP 403 Forbidden: review whether the target rejects datacenter ASNs, missing browser headers, or direct fetch patterns (/blog/proxy-403-forbidden) before switching a Static ISP URL to PlaywrightURLLoader or Rotating Residential.
  • HTTP 429 Too Many Requests: cap requests_per_second on WebBaseLoader (the built-in default is 2) and respect Retry-After headers on idempotent GET retries (/blog/proxy-429-too-many-requests).
  • Credential hygiene: keep raw proxy passwords in worker secrets or deployment env files, never inside LangSmith traces or prompt strings returned to the model.

Sources checked

All source files and product documentation verified HTTP 200 on December 2, 2026.