How to Give Your AI Agent Access to DefiLlama Data
Tutorials

How to Give Your AI Agent Access to DefiLlama Data

Learn how to give your AI agent reliable access to DefiLlama's public DeFi data using AlterLab's extract and search APIs for structured, anti-bot‑protected pipelines.

3 min read
8 views

AlterLab handles this automaticallyscrape any URL with one API call. No infrastructure required.

Try it free

This guide covers accessing publicly available data. Always review a site's robots.txt and Terms of Service before automated access.

TL;DR

Give your AI agent access to DefiLlama data by calling AlterLab's Extract API with a URL and a JSON schema, or use the Search API to run predefined schedules. The service handles JavaScript rendering, anti-bot measures, and returns structured JSON ready for LLM consumption.

Why AI agents need DefiLlama data

DeFi protocols publish total value locked (TVL), token prices, and yield rates on DefiLlama. Agents can use this data for:

  • Real‑time TVL monitoring to trigger rebalancing in a portfolio pipeline
  • Protocol analytics that feed into risk scoring models for lending strategies
  • Yield intelligence that updates LLM‑generated market briefs with current APYs

Why raw HTTP requests fail for agents

Direct requests to DefiLlama often encounter:

  • Rate limits that block bursts of calls from an agent
  • JavaScript‑rendered content that returns empty HTML without a headless browser
  • Bot detection mechanisms that serve challenges or CAPTCHAs
  • Failed attempts that waste token budget and increase latency, forcing agents to retry or fallback to stale caches

Connecting your agent to DefiLlama via AlterLab

AlterLab's Extract API returns structured data without requiring HTML parsing. You define a schema that matches the fields you need, and the service extracts them after rendering the page.

Python example

Python
import alterlab

client = alterlab.Client("YOUR_API_KEY")

# Request structured TVL data for a specific protocol
result = client.extract(
    url="https://defillama.com/protocol/aave",
    schema={
        "protocol": "string",
        "tvl": "string",
        "chain": "string",
        "description": "string"
    }
)
print(result.data)  # Clean dict ready for LLM context

cURL example

Bash
curl -X POST https://api.alterlab.io/api/v1/extract/templates/{template_id} \
  -H "X-API-Key: YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://defillama.com/protocol/aave",
    "schema": {
        "protocol": "string",
        "tvl": "string",
        "chain": "string"
    }
}'

The response is a JSON object whose keys match the schema, eliminating the need for selectors or regex cleanup.

Using the Search API for DefiLlama queries

If you have recurring queries—such as listing all protocols on a given chain—you can create a schedule in AlterLab's dashboard and trigger it via the Search API.

Python
import alterlab

client = alterlab.Client("YOUR_API_KEY")

# Run a saved schedule that extracts protocol names and TVLs
run = client.search_run(schedule_id="defillama-chains")
for item in run.data:
    print(f"{item['protocol']}: {item['tvl']}")
Bash
curl -X POST https://api.alterlab.io/api/v1/search/schedules/{schedule_id}/run \
  -H "X-API-Key: YOUR_KEY"

The Search API returns the same structured format as Extract, making it easy to plug into downstream agents.

MCP integration

AlterLab provides a Model Context Protocol (MCP) server that exposes its APIs as tools for Claude, GPT, or Cursor agents. By adding the MCP endpoint, your agent can call alterlab_extract or alterlab_search as a native tool. See the AlterLab for AI Agents page for setup instructions.

Building a DeFi TVL monitoring pipeline

Below is an end‑to‑end example where an agent fetches TVL data, passes it to an LLM, and receives a summary.

  1. Agent requests data – The LLM decides it needs the latest TVL for Aave and calls the AlterLab tool.
  2. AlterLab fetches + extracts – The service renders the DefiLlama page, executes any anti‑bot bypass, and returns JSON matching the requested schema.
  3. Agent uses clean data – The LLM receives the dict directly, inserts it into its context window, and generates a brief market note without any parsing steps.
Python
import alterlab
from openai import OpenAI

alterlab_client = alterlab.Client("YOUR_ALTERLAB_KEY")
llm_client = OpenAI(api_key="YOUR_OPENAI_KEY")

def get_aave_tvl():
    result = alterlab_client.extract(
        url="https://defillama.com/protocol/aave",
        schema={"protocol": "string", "tvl": "string", "change_1d": "string"}
    )
    return result.data

def generate_summary(tvl_data):
    prompt = f"""
    You are a DeFi analyst. Summarize the latest TVL information for Aave:
    Protocol: {tvl_data['protocol']}
    TVL: {tvl_data['tvl']}
    24h change: {tvl_data['change_1d']}
    Provide a two‑sentence update suitable for a trader's briefing.
    """
    response = llm_client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": prompt}],
        temperature=0.3
    )
    return response.choices[0].message.content

if __name__ == "__main__":
    data = get_aave_tvl()
Share

Was this article helpful?

Frequently Asked Questions

Accessing publicly available data is generally permitted, but you must review DefiLlama's robots.txt and Terms of Service, respect rate limits, and avoid private or gated information. Users are responsible for compliance.
AlterLab uses automatic anti-bot bypass, rotating proxies, and headless browsers to return successful requests without retries, so agents receive clean data on the first try.
AlterLab charges per successful request; see the pricing page for volume discounts. Agent workloads typically pay only for the data they receive, with no wasted bandwidth on failed attempts.