"""Public leaderboards → append-only `benchmark_results` (tier 2). One connector class per leaderboard domain (the SDK binds one `source_key` per connector, and each board has its own rate limit and provenance) — module kept as `leaderboards`. * aider_leaderboard raw polyglot_leaderboard.yml from the aider repository → `aider-polyglot` (pass_rate_2) and the separate `aider-polyglot-well-formed` benchmark (percent_cases_well_formed); run group = run date. * swebench_leaderboard https://www.swebench.com/ embeds `', re.DOTALL) # model-level facts AA copies from the labs (same for every effort variant of a model) → written once per base model as `aa_*` AA_MODEL_CLAIMS = ("aa_release_date", "aa_openness", "aa_context_window", "aa_deprecated") class ArtificialAnalysisConnector(_Leaderboard): name = "artificial_analysis" label = "Artificial Analysis — Intelligence Index and component evaluations" description = "Model leaderboard page (RSC payload): Intelligence Index with version and component evaluations; effort variants fold into their base model." source_key = "artificialanalysis.ai" rate_per_min = 6 expected_min_records = 100 URL = "https://artificialanalysis.ai/leaderboards/models" async def discover(self, ctx: RunContext) -> list[Target]: return [Target(url=self.URL, doc_type="leaderboard", key="aa_models", min_bytes=50000, priority=1)] async def extract(self, ctx: RunContext, target: Target, res: FetchResult, parsed: Parsed) -> Facts: facts = Facts() models, version = parse_rsc_models(res.text) if not models: ctx.log.warning("artificial analysis: no model objects in the RSC payload") return facts index = benchmark_ref("artificial-analysis-intelligence-index") assert index facts.entities.append(index) benches = {k: benchmark_ref(k) for k, *_ in AA_EVALS.values()} trust = trust_level(self.source_key) written: set[tuple[int, str]] = set() def once(ref: EntityRef, prop: str, value: Any, **kw: Any) -> None: """One claim per (base model, property): several effort variants of a model repeat the same model-level facts.""" if value in (None, "", []) or (id(ref), prop) in written: return written.add((id(ref), prop)) facts.claim(ref, prop, value, **kw) for slug, m in models.items(): ref, effort = self._model(facts, slug, m, models) # AA copies release date / openness / context / deprecation from the labs: recorded under `aa_*` so that a second-hand # tier-2 source never supersedes another tier-2 source (hub/OpenRouter) every run; the results are AA's own data. if m.get("releaseDate"): once(ref, "aa_release_date", str(m["releaseDate"])[:10]) if isinstance(m.get("isOpenWeights"), bool): once(ref, "aa_openness", "open-weights" if m["isOpenWeights"] else "proprietary") if m.get("deprecated") is True and not effort: once(ref, "aa_deprecated", True) if isinstance(m.get("contextWindowTokens"), int) and m["contextWindowTokens"] > 0: once(ref, "aa_context_window", m["contextWindowTokens"], unit="tokens") if not effort: if isinstance(m.get("isReasoning"), bool): once(ref, "reasoning", m["isReasoning"]) if isinstance(m.get("medianOutputTokensPerSecond"), (int, float)): once(ref, "metric.aa_median_output_tokens_per_second", round(float(m["medianOutputTokensPerSecond"]), 1)) # the reasoning switch is part of every result's configuration (a base row and its "non-reasoning" sibling differ by it) if isinstance(m.get("isReasoning"), bool) and "reasoning" not in effort and "reasoning_effort" not in effort: effort["reasoning"] = "on" if m["isReasoning"] else "off" ii = m.get("intelligenceIndex") if isinstance(ii, (int, float)): cfg = _clean({"version": version, "estimated": bool(m.get("intelligenceIndexIsEstimated")), "aa_slug": slug, **effort}) facts.result(model=ref, benchmark=index, score=round(float(ii), 2), metric="index", unit="", config=cfg, source_url=self.URL, trust_level=trust, variant="index", run_group=version) for field, (bkey, metric, variant) in AA_EVALS.items(): v = m.get(field) bench = benches.get(bkey) if bench is None or not isinstance(v, (int, float)): continue if bench not in facts.entities: facts.entities.append(bench) cfg = _clean({"evaluator": "Artificial Analysis", "index_version": version, "aa_slug": slug, "variant": variant, **effort}) facts.result(model=ref, benchmark=bench, score=round(float(v) * 100, 2), metric=metric, unit="%", config=cfg, source_url=self.URL, trust_level=trust, variant=variant, run_group=version) facts.document_entity = index facts.document_title = f"Artificial Analysis models — Intelligence Index v{version}" if version else "Artificial Analysis models" return facts def _model(self, facts: Facts, slug: str, m: dict[str, Any], models: dict[str, dict[str, Any]]) -> tuple[EntityRef, dict[str, str]]: """Base-model EntityRef + effort configuration for one AA row. AA's own base label is `shortName` without its parenthetical ("Claude Opus 5 (xhigh)" → "Claude Opus 5"); the slug carries the suffix (`claude-opus-5-xhigh`). The `artificial_analysis` identifier is attached only when AA lists the base slug itself; otherwise the base slug is an alias.""" short = (m.get("shortName") or m.get("name") or slug).strip() label, label_effort = split_effort_label(short) base_slug, slug_effort = strip_effort(slug) effort = {**slug_effort, **label_effort} if slug_effort and not label_effort: label = strip_effort_words(label, only_if=True) variant = bool(effort) and base_slug != slug creator = m.get("creator") or {} creator_name = creator.get("name") or m.get("modelCreatorName") org = org_from_name(facts, creator.get("slug"), creator_name) if org is None and org_key_for_bare_id(base_slug)[1] is None and creator_name: # creator unknown to the registry and no first-party pattern: AA's own creator label becomes a company with AA's identifier existing = next((e for e in facts.entities if e.identifiers.get("artificial_analysis_creator") == (creator.get("slug") or _slug(creator_name))), None) org = existing or facts.entity("company", creator_name, identifiers={"artificial_analysis_creator": creator.get("slug") or _slug(creator_name)}) identifiers: dict[str, str] = {} aliases: list[str] = [] if not variant: identifiers["artificial_analysis"] = slug elif base_slug in models: identifiers["artificial_analysis"] = base_slug else: aliases.append(base_slug) aliases += [a for a in (short if not effort else None, m.get("shortName") if not effort else None) if a] ref, _ = model_ref_from_api_id(facts, base_slug, name=label or base_slug, trusted=False, identity_confidence="medium", organization=org, extra_aliases=aliases) for k, v in identifiers.items(): ref.identifiers.setdefault(k, v) return ref, effort def parse_rsc_models(html: str) -> tuple[dict[str, dict[str, Any]], str | None]: """Concatenate the Next.js flight chunks, parse each `id:json` line and collect every object with `slug` + `intelligenceIndex`.""" chunks = [] for p in PUSH.findall(html): try: chunks.append(json.loads('"' + p + '"')) except json.JSONDecodeError: continue blob = "".join(chunks) version_m = re.search(r"Intelligence Index v(\d+(?:\.\d+)?)", blob) models: dict[str, dict[str, Any]] = {} for line in blob.split("\n"): _, sep, payload = line.partition(":") if not sep or "intelligenceIndex" not in payload: continue try: data = json.loads(payload) except json.JSONDecodeError: continue stack = [data] while stack: o = stack.pop() if isinstance(o, dict): if "intelligenceIndex" in o and isinstance(o.get("slug"), str): models.setdefault(o["slug"], o) else: stack.extend(o.values()) elif isinstance(o, list): stack.extend(o) return models, (version_m.group(1) if version_m else None) _ = org_ref # kept importable for tests/back-compat CONNECTORS = [AiderLeaderboardConnector, SweBenchLeaderboardConnector, LiveBenchLeaderboardConnector, ArtificialAnalysisConnector]