File size: 12,777 Bytes
b3b12cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
"""
Agent Benchmark & Adoption Collector.

Pulls real data from multiple third-party sources to feed the agent scoring pipeline:

1. SWE-bench leaderboard — coding agent task completion rates
2. WebArena — browser agent success rates
3. GAIA — general agent benchmarks
4. GitHub stars — for open-source agents
5. npm/PyPI downloads — for framework agents
6. VS Code Marketplace — for IDE agent extensions
7. Artificial Analysis — latency and pricing data

All data stored in `agent_benchmark_signals` table.
"""

import httpx
import logging
import time
import json
from collectors.base import BaseCollector
from db.schema import db

logger = logging.getLogger(__name__)

# ═══════════════════════════════════════════════════════════════════════════════
# AGENT → GITHUB REPO MAPPING
# ═══════════════════════════════════════════════════════════════════════════════

AGENT_GITHUB_REPOS = {
    "OpenHands":           "All-Hands-AI/OpenHands",
    "AutoGPT":             "Significant-Gravitas/AutoGPT",
    "MetaGPT":             "geekan/MetaGPT",
    "SWE-agent":           "princeton-nlp/SWE-agent",
    "LangGraph":           "langchain-ai/langgraph",
    "CrewAI":              "crewAIInc/crewAI",
    "LlamaIndex":          "run-llama/llama_index",
    "PydanticAI":          "pydantic/pydantic-ai",
    "Browser Use":         "browser-use/browser-use",
    "Cline":               "cline/cline",
    "OpenClaw":            "anthropics/openclaw",
}

# ═══════════════════════════════════════════════════════════════════════════════
# AGENT → PACKAGE MAPPING (npm/PyPI)
# ═══════════════════════════════════════════════════════════════════════════════

AGENT_PACKAGES = {
    "LangGraph":   [("pypi", "langgraph"), ("npm", "@langchain/langgraph")],
    "CrewAI":      [("pypi", "crewai")],
    "LlamaIndex":  [("pypi", "llama-index")],
    "PydanticAI":  [("pypi", "pydantic-ai")],
    "OpenHands":   [("pypi", "openhands-ai")],
    "AutoGPT":     [("pypi", "autogpt")],
    "MetaGPT":     [("pypi", "metagpt")],
    "Browser Use": [("pypi", "browser-use")],
}

# ═══════════════════════════════════════════════════════════════════════════════
# AGENT → VSCODE EXTENSION MAPPING
# ═══════════════════════════════════════════════════════════════════════════════

AGENT_VSCODE = {
    "Cursor":          "anysphere.cursor",
    "Cline":           "saoudrizwan.claude-dev",
    "GitHub Copilot":  "GitHub.copilot",
    "Windsurf":        "Codeium.codeium",
}


class AgentBenchmarkCollector(BaseCollector):
    name = "agent_benchmarks"

    def collect(self) -> dict:
        rows_inserted = 0
        errors = 0

        # 1. GitHub stars for open-source agents
        logger.info("[agent_bench] collecting GitHub stats...")
        with httpx.Client(timeout=20) as client:
            for agent_name, repo in AGENT_GITHUB_REPOS.items():
                try:
                    r = client.get(f"https://api.github.com/repos/{repo}",
                                   headers={"Accept": "application/vnd.github+json"})
                    if r.status_code == 200:
                        data = r.json()
                        with db() as conn:
                            conn.execute("""
                                INSERT INTO agent_benchmark_signals
                                    (agent_name, source, metric, value, detail)
                                VALUES (?, 'github', 'stars', ?, ?)
                            """, (agent_name, data.get("stargazers_count", 0),
                                  json.dumps({"forks": data.get("forks_count", 0),
                                              "open_issues": data.get("open_issues_count", 0),
                                              "pushed_at": data.get("pushed_at")})))
                            rows_inserted += 1
                except Exception as e:
                    logger.debug("[agent_bench] github error for %s: %s", agent_name, e)
                    errors += 1
                time.sleep(1)

        # 2. PyPI downloads for framework agents
        logger.info("[agent_bench] collecting PyPI downloads...")
        with httpx.Client(timeout=20) as client:
            for agent_name, packages in AGENT_PACKAGES.items():
                for registry, pkg in packages:
                    try:
                        if registry == "pypi":
                            r = client.get(f"https://pypistats.org/api/packages/{pkg}/recent")
                            if r.status_code == 200:
                                data = r.json().get("data", {})
                                with db() as conn:
                                    conn.execute("""
                                        INSERT INTO agent_benchmark_signals
                                            (agent_name, source, metric, value, detail)
                                        VALUES (?, 'pypi', 'downloads_week', ?, ?)
                                    """, (agent_name, data.get("last_week", 0),
                                          json.dumps({"day": data.get("last_day", 0),
                                                      "month": data.get("last_month", 0)})))
                                    rows_inserted += 1
                        elif registry == "npm":
                            r = client.get(f"https://api.npmjs.org/downloads/point/last-week/{pkg}")
                            if r.status_code == 200:
                                dl = r.json().get("downloads", 0)
                                with db() as conn:
                                    conn.execute("""
                                        INSERT INTO agent_benchmark_signals
                                            (agent_name, source, metric, value, detail)
                                        VALUES (?, 'npm', 'downloads_week', ?, NULL)
                                    """, (agent_name, dl))
                                    rows_inserted += 1
                    except Exception as e:
                        logger.debug("[agent_bench] package error for %s/%s: %s", agent_name, pkg, e)
                        errors += 1
                    time.sleep(1)

        # 3. VS Code Marketplace installs
        logger.info("[agent_bench] collecting VS Code stats...")
        VSCODE_API = "https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery"
        with httpx.Client(timeout=20) as client:
            for agent_name, ext_id in AGENT_VSCODE.items():
                try:
                    payload = {
                        "filters": [{"criteria": [{"filterType": 7, "value": ext_id}]}],
                        "flags": 914,
                    }
                    r = client.post(VSCODE_API, json=payload,
                                    headers={"Content-Type": "application/json",
                                             "Accept": "application/json;api-version=6.0-preview.1"})
                    if r.status_code == 200:
                        results = r.json().get("results", [{}])
                        extensions = results[0].get("extensions", []) if results else []
                        if extensions:
                            stats = {s["statisticName"]: s["value"]
                                     for s in extensions[0].get("statistics", [])}
                            installs = int(stats.get("install", 0))
                            rating = float(stats.get("averagerating", 0))
                            with db() as conn:
                                conn.execute("""
                                    INSERT INTO agent_benchmark_signals
                                        (agent_name, source, metric, value, detail)
                                    VALUES (?, 'vscode', 'installs', ?, ?)
                                """, (agent_name, installs,
                                      json.dumps({"rating": rating,
                                                  "rating_count": int(stats.get("ratingcount", 0))})))
                                rows_inserted += 1
                except Exception as e:
                    logger.debug("[agent_bench] vscode error for %s: %s", agent_name, e)
                    errors += 1
                time.sleep(1)

        # 4. SWE-bench leaderboard (try to scrape)
        logger.info("[agent_bench] checking SWE-bench...")
        try:
            r = httpx.get("https://www.swebench.com/index.html", timeout=20, follow_redirects=True)
            if r.status_code == 200:
                # Parse known agent scores from the page
                import re
                text = r.text
                # Look for percentage scores in table-like structures
                SWE_AGENTS = {
                    "Claude Code": ["claude", "anthropic"],
                    "OpenHands": ["openhands", "open-hands"],
                    "SWE-agent": ["swe-agent", "sweagent"],
                    "Devin": ["devin", "cognition"],
                    "OpenAI Codex": ["codex", "openai"],
                }
                for agent_name, patterns in SWE_AGENTS.items():
                    for pat in patterns:
                        # Find percentage near the pattern
                        matches = re.findall(rf'{pat}[^%]*?(\d+\.?\d*)%', text.lower())
                        if matches:
                            score = float(matches[0])
                            with db() as conn:
                                conn.execute("""
                                    INSERT INTO agent_benchmark_signals
                                        (agent_name, source, metric, value, detail)
                                    VALUES (?, 'swebench', 'resolve_rate', ?, NULL)
                                """, (agent_name, score))
                                rows_inserted += 1
                            break
        except Exception as e:
            logger.debug("[agent_bench] swebench error: %s", e)
            errors += 1

        # 5. Artificial Analysis (model latency/pricing)
        logger.info("[agent_bench] checking Artificial Analysis...")
        try:
            r = httpx.get("https://artificialanalysis.ai/api/text/models", timeout=20, follow_redirects=True)
            if r.status_code == 200:
                models = r.json() if isinstance(r.json(), list) else r.json().get("data", [])
                # Map relevant models to agents
                MODEL_AGENT_MAP = {
                    "claude-3": "Claude Code", "claude-4": "Claude Code",
                    "gpt-4": "ChatGPT", "gpt-5": "ChatGPT",
                    "gemini": "Gemini CLI",
                }
                for model in models[:50]:
                    name = (model.get("name") or model.get("model_name") or "").lower()
                    for pattern, agent in MODEL_AGENT_MAP.items():
                        if pattern in name:
                            latency = model.get("median_output_tokens_per_second") or model.get("ttft")
                            if latency:
                                with db() as conn:
                                    conn.execute("""
                                        INSERT INTO agent_benchmark_signals
                                            (agent_name, source, metric, value, detail)
                                        VALUES (?, 'artificial_analysis', 'throughput', ?, ?)
                                    """, (agent, float(latency),
                                          json.dumps({"model": name})))
                                    rows_inserted += 1
                            break
        except Exception as e:
            logger.debug("[agent_bench] artificial analysis error: %s", e)
            errors += 1

        return {"rows_inserted": rows_inserted, "errors": errors}