
Adélia Cruz
Neural Network Developer
LangChain agents can browse the web, extract data, and execute multi-step workflows autonomously. But when these agents encounter CAPTCHA challenges — reCAPTCHA, Cloudflare Turnstile, or image verification — the entire chain stalls. CapSolver provides a native LangChain integration through the capsolver-agent package that registers CAPTCHA solving as a standard BaseTool, letting your ReAct agent call "solve" the same way it calls "search" or "click." This tutorial shows you how to set it up from scratch.
BaseTool implementations via capsolver-agentget_langchain_tools()LangChain powers thousands of production AI agents that interact with websites, APIs, and databases. When these agents perform web-based tasks — lead enrichment, data collection, form submission, or automated testing — they inevitably encounter human-verification challenges. A reCAPTCHA on a login page, a Cloudflare Turnstile on a data portal, or an image CAPTCHA on a government site will halt the agent's execution entirely.
The fundamental problem is that LangChain's tool ecosystem covers browsing, searching, and data extraction, but provides no built-in mechanism for clearing verification challenges. Without a CAPTCHA solving tool, agents require human intervention at every verification wall, defeating the purpose of autonomous operation.
CapSolver's capsolver-agent package solves this by exposing CAPTCHA solving as standard LangChain tools. The agent's reasoning loop naturally decides when to invoke solving — just as it decides when to search or navigate — making CAPTCHA handling a first-class capability in your agent stack. According to CapSolver's production testing, approximately 30% or more of agent tasks stall on verification challenges, making this integration essential for production deployments.
Prepare these components for the integration:
Install all required packages:
# Core engine (required — both other packages depend on it)
pip install git+https://github.com/capsolver-ai/capsolver-core.git
# Agent tools with LangChain support
pip install "capsolver-agent[langchain] @ git+https://github.com/capsolver-ai/capsolver-agent.git"
# LangChain and LLM provider
pip install langchain-openai langgraph
Set your environment variables:
export CAPSOLVER_API_KEY="your-capsolver-api-key"
export OPENAI_API_KEY="your-openai-api-key"
Before writing code, understand how CapSolver's three-layer architecture maps onto LangChain's tool system:
LangChain Agent (decides what to do)
│ emits a tool call, e.g. solve_captcha(...)
▼
capsolver-agent (tool-adapter layer)
│ executor relays to ↓
▼
capsolver-core (engine: detect → solve → fill back)
│
▼
CapSolver AI Service (cloud solving)
The capsolver-agent package provides ready-made BaseTool implementations that plug directly into LangChain's agent framework. Each tool maps to a core method:
| LangChain Tool | Core Method | Browser Required? |
|---|---|---|
solve_captcha |
cap.solve(info) |
No |
detect_captchas |
cap.detect(page) |
Yes |
solve_on_page |
cap.solve_on_page(page) |
Yes |
get_balance |
cap.get_balance() |
No |
get_supported_captchas |
cap.get_supported_captchas() |
No |
For most LangChain use cases, solve_captcha (Token mode) is the primary tool. You provide the CAPTCHA type, website URL, and site key — the tool returns a token you can submit to the target site. No browser is needed.
Understanding the architecture helps you choose the right integration approach. Token mode is simpler and faster — ideal when your agent already knows the site key. Browser mode is more powerful — it auto-detects CAPTCHAs on any page and fills the solution back into the DOM automatically.
capsolver-agent without capsolver-core: The agent package depends on core at runtime. Always install core first.Import and register CapSolver's LangChain tools with a single function call:
import asyncio
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent
from capsolver_agent.langchain import get_langchain_tools
# Get all CapSolver tools as LangChain BaseTool instances
capsolver_tools = get_langchain_tools(api_key="YOUR_CAPSOLVER_API_KEY")
# Create a ReAct agent with CAPTCHA solving capability
llm = ChatOpenAI(model="gpt-4o", temperature=0)
agent = create_react_agent(llm, tools=capsolver_tools)
# Run the agent
async def main():
result = await agent.ainvoke({
"messages": [
("user", "Solve the reCAPTCHA v2 on https://example.com — the site key is 6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI")
]
})
print(result["messages"][-1].content)
asyncio.run(main())
That's the complete integration. get_langchain_tools() returns a list of BaseTool instances that the agent can invoke through its standard reasoning loop. The agent decides when to call solve_captcha based on the task context — no hardcoded CAPTCHA detection logic required.
This approach follows LangChain's design philosophy: tools are declarative capabilities the agent can reason about. The agent sees "solve_captcha" in its tool list, understands what it does from the description, and calls it when the task requires clearing a verification challenge. This is fundamentally different from hardcoding CAPTCHA handling into your scraping logic.
ainvoke() rather than invoke() for proper async execution.When you know the CAPTCHA type and site key (the most common scenario for targeted automation), use Token mode directly:
from capsolver_agent.schema import create_executor
executor = create_executor(api_key="YOUR_CAPSOLVER_API_KEY")
# Solve reCAPTCHA v2
result = await executor.execute("solve_captcha", {
"captcha_type": "reCaptchaV2",
"website_url": "https://example.com/login",
"website_key": "6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"
})
if result["success"]:
token = result["solution"]["token"]
# Submit token as g-recaptcha-response with your form data
print(f"Token obtained: {token[:50]}...")
For reCAPTCHA v3, add the page_action and min_score parameters:
result = await executor.execute("solve_captcha", {
"captcha_type": "reCaptchaV3",
"website_url": "https://example.com/api",
"website_key": "6LdKlZEpAAAAAN...",
"page_action": "login",
"min_score": 0.7
})
For Cloudflare Turnstile:
result = await executor.execute("solve_captcha", {
"captcha_type": "cloudflare",
"website_url": "https://example.com",
"website_key": "0x4AAAAAAABS..."
})
# Submit token as cf-turnstile-response
The CapSolver documentation covers additional parameters for Enterprise variants and edge cases.
Token mode is the fastest path — no browser overhead, no page rendering, just parameters in and a token out. For LangChain agents that already have the site key from prior analysis or configuration, this is the most efficient approach.
Combine CapSolver tools with other LangChain tools to build a production agent that handles CAPTCHAs as part of a larger workflow:
import asyncio
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent
from capsolver_agent.langchain import get_langchain_tools
from langchain_community.tools import DuckDuckGoSearchRun
# Combine CAPTCHA solving with other tools
search_tool = DuckDuckGoSearchRun()
capsolver_tools = get_langchain_tools(api_key="YOUR_CAPSOLVER_API_KEY")
all_tools = [search_tool] + capsolver_tools
# Create agent with full capability set
llm = ChatOpenAI(model="gpt-4o", temperature=0)
agent = create_react_agent(llm, tools=all_tools)
async def run_agent(task: str):
"""Run the agent with a task that may require CAPTCHA solving."""
result = await agent.ainvoke({
"messages": [("user", task)]
})
return result["messages"][-1].content
# Example: agent that solves CAPTCHA as part of data collection
async def main():
response = await run_agent(
"I need to access data behind a reCAPTCHA v2 on https://example.com/data. "
"The site key is 6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI. "
"Solve the CAPTCHA and give me the token I can use to access the page."
)
print(response)
asyncio.run(main())
The agent's reasoning loop handles the workflow naturally: it identifies that CAPTCHA solving is needed, calls the appropriate tool, receives the token, and continues with the task. This is the same pattern used in the CapSolver AI agent documentation for production deployments.
Production agents rarely solve CAPTCHAs in isolation. They solve CAPTCHAs as one step in a larger workflow — data collection, form submission, or multi-site navigation. Combining CapSolver tools with other LangChain tools creates agents that handle the full workflow autonomously.
For agents that drive a browser and encounter CAPTCHAs dynamically (without knowing parameters in advance), use Browser mode with Playwright:
# Install browser support
pip install "capsolver-core[playwright] @ git+https://github.com/capsolver-ai/capsolver-core.git"
playwright install chromium
import asyncio
from capsolver_core import create_capsolver
from playwright.async_api import async_playwright
async def solve_page_captchas(url: str):
"""Detect and solve all CAPTCHAs on a page automatically."""
cap = create_capsolver(api_key="YOUR_CAPSOLVER_API_KEY")
async with async_playwright() as p:
browser = await p.chromium.launch()
page = await browser.new_page()
await page.goto(url)
# One call: detect → solve → fill back
results = await cap.solve_on_page(page)
for r in results:
print(f"Type: {r.info.type}")
print(f"Token: {r.solution.token[:50] if r.solution else 'Failed'}...")
print(f"Filled: {r.filled}")
print(f"Error: {r.error}")
await browser.close()
await cap.aclose()
asyncio.run(solve_page_captchas("https://example.com/login"))
The solve_on_page() method handles the entire pipeline: it detects which CAPTCHAs are present, reads their parameters from the live DOM, solves each one through CapSolver's AI service, and fills the tokens back into the page — all in a single call.
Claim Your Bonus Code: Use code WEBS at CapSolver Dashboard to get an extra 5% bonus on every recharge. Perfect for developers building LangChain agents with CAPTCHA solving capability.
For LangChain agents that use the Browser Use framework for autonomous browsing, CapSolver registers as an action that recovers the session whenever verification appears mid-task:
from browser_use import Agent
from langchain_openai import ChatOpenAI
from capsolver_core import create_capsolver
# The agent browses autonomously and calls solving when it hits a CAPTCHA
# Agent browses → hits CAPTCHA → calls solve action → gets token → continues task
This pattern is closest to real-world automation: the agent navigates freely, and when it encounters a verification wall, it calls the solve action within the same browser session, then continues the original task without breaking stride.
The CapSolver extension can also help identify CAPTCHA parameters during development, before you deploy your LangChain agent to production.
Integrating CAPTCHA solving into LangChain agents requires installing capsolver-agent with the LangChain extra, calling get_langchain_tools() to get ready-made BaseTool instances, and passing them to your agent. The agent's ReAct loop handles the rest — deciding when to solve, calling the appropriate tool, and continuing the workflow with the token. CapSolver provides the AI-powered solving infrastructure that makes this possible, supporting reCAPTCHA v2/v3 and Cloudflare Turnstile through a unified interface.
Start with Token mode for known CAPTCHA parameters, then add Browser mode when your agent needs to handle CAPTCHAs dynamically on any page. The integration takes under 10 lines of code and transforms your LangChain agent from one that stalls at verification walls to one that clears them autonomously.
Yes. The entire CapSolver SDK is built on async/await. The LangChain tools returned by get_langchain_tools() support both sync and async invocation. For best performance with LangChain's async agent runtime, use ainvoke() and the async variants of all methods.
The SDK currently supports reCAPTCHA v2 (including invisible), reCAPTCHA v3 (including Enterprise), and Cloudflare Turnstile. These cover the vast majority of verification challenges encountered by web-browsing agents. The underlying CapSolver service supports additional types through the REST API.
The LangChain ReAct agent uses the tool's name and description to reason about when to invoke it. When the task involves accessing a CAPTCHA-protected resource, the agent recognizes that solving is needed and calls the tool with the appropriate parameters. You can also explicitly instruct the agent in the task prompt.
Yes. CapSolver tools work with LangGraph's create_react_agent and custom graph-based workflows. Register the tools as you would with any LangChain agent, and the graph nodes can invoke CAPTCHA solving as part of conditional or sequential execution paths.
The executor returns a structured result with {"success": False, "error": "..."} on failure. The agent receives this feedback and can retry, try alternative parameters, or report the failure to the user. Common failure causes include incorrect site keys, insufficient balance, or unsupported CAPTCHA types.
Step-by-step tutorial for solving reCAPTCHA v2 in LangChain agents using CapSolver capsolver-agent tools, covering Token mode and Browser mode with code examples.

Learn how enterprise AI agent teams can implement scalable, reliable CAPTCHA solving infrastructure to keep automation workflows running without interruption.
