Skip to content

The platform for continuously improving AI agents.

7.2 KB
Raw Blame
import os
import re
from copy import deepcopy
from datetime import timedelta
from typing import Literal

from pydantic import Field, model_validator

from agent_runtime.contracts import Contract
from overbae.core.errors import InputValidationError
from overbae.services import context_graph, model_catalog

FIELDS = {
    "provider": {"label": "provider", "operators": ["is"], "type": "string"},
    "id": {"label": "model ID", "operators": ["is", "starts_with"], "type": "string"},
    "family": {"label": "model family", "operators": ["starts_with"], "type": "string"},
    "context_length": {"label": "context length", "operators": ["at_least"], "type": "number"},
    "prompt_price": {
        "label": "input price / million tokens",
        "operators": ["at_most"],
        "type": "number",
    },
    "completion_price": {
        "label": "output price / million tokens",
        "operators": ["at_most"],
        "type": "number",
    },
    "supported_parameters": {
        "label": "supported feature",
        "operators": ["includes"],
        "type": "string",
    },
}
PARTNERS = {
    "openrouter": {
        "label": "OpenRouter",
        "events": [{"id": "model_added", "label": "adds a new model", "fields": FIELDS}],
    }
}


class IntegrationCondition(Contract):
    field: str = Field(min_length=1, max_length=64)
    operator: str = Field(min_length=1, max_length=32)
    value: str | float


class IntegrationRule(Contract):
    partner: Literal["openrouter"]
    event: Literal["model_added"]
    conditions: list[IntegrationCondition] = Field(default_factory=list, max_length=20)
    include_existing: bool = False

    @model_validator(mode="after")
    def validate_conditions(self):
        fields = PARTNERS[self.partner]["events"][0]["fields"]
        for condition in self.conditions:
            field = fields.get(condition.field)
            if not field or condition.operator not in field["operators"]:
                raise ValueError("Choose a condition supported by this integration event")
            if field["type"] == "number":
                if not isinstance(condition.value, float) or not 0 <= condition.value < float(
                    "inf"
                ):
                    raise ValueError("Numeric conditions require a finite non-negative value")
            elif not isinstance(condition.value, str) or not condition.value.strip():
                raise ValueError("Text conditions require a value")
        return self


def catalogue():
    connected = bool(os.environ.get("OPENROUTER_API_KEY"))
    partners = deepcopy(PARTNERS)
    rows, available = model_catalog.fetch_model_catalog() if connected else ([], False)
    if available:
        fields = partners["openrouter"]["events"][0]["fields"]
        providers = sorted({row["provider"] for row in rows})
        fields["provider"]["options"] = [
            {"value": provider, "label": provider} for provider in providers
        ]
        # Family conditions match slug prefixes; OpenRouter has no separate family field.
        families = set()
        for row in rows:
            slug = row["id"].split("/", 1)[-1]
            prefix = re.match(r"[a-zA-Z]+", slug)
            if prefix:
                families.add((row["provider"], prefix.group()))
        fields["family"]["options"] = [
            {"value": family, "label": family, "provider": provider}
            for provider, family in sorted(families)
        ]
    return [{"id": key, **value, "connected": connected} for key, value in partners.items()]


def models():
    if not os.environ.get("OPENROUTER_API_KEY"):
        raise InputValidationError("The OpenRouter connection is unavailable")
    rows, available = model_catalog.fetch_model_catalog()
    if not available or not rows:
        # An empty or failed response cannot become the initial catalogue baseline.
        raise RuntimeError("OpenRouter catalogue is unavailable")
    return rows


def matches(rule, model):
    for condition in rule.conditions:
        value = model.get(condition.field)
        if condition.field == "family":
            value = model["id"].split("/", 1)[-1]
        expected = condition.value
        if value is None:
            return False
        if condition.operator == "is" and value != expected:
            return False
        if condition.operator == "starts_with" and not value.startswith(expected):
            return False
        if condition.operator == "includes" and expected not in value:
            return False
        if condition.operator == "at_least" and value < expected:
            return False
        if condition.operator == "at_most" and value > expected:
            return False
    return True


def preview(rule):
    rows = models()
    matched = [row for row in rows if matches(rule, row)]
    return {"total": len(rows), "matched": len(matched), "models": matched[:20]}


def initial_state(rule, previous=None):
    if previous and "seen_models" in previous:
        return previous
    try:
        rows = models()
    except RuntimeError as exc:
        raise InputValidationError(
            "OpenRouter catalogue unavailable. Try again before enabling the trigger."
        ) from exc
    return {"seen_models": [] if rule.include_existing else sorted(row["id"] for row in rows)}


def scan(trigger, *, limit, now):
    # The owning trigger service holds the experiment/trigger locks through materialization.
    from overbae.services import research_triggers

    rule = IntegrationRule.model_validate(trigger.configuration["integration"])
    rows = models()
    seen = set(trigger.source_state.get("seen_models", []))
    if "seen_models" not in trigger.source_state:
        trigger.source_state["seen_models"] = sorted(row["id"] for row in rows)
        trigger.next_at = now + timedelta(hours=trigger.every_hours)
        trigger.save(update_fields=["source_state", "next_at"])
        return 0
    count = 0
    for row in rows:
        if row["id"] in seen:
            continue
        if matches(rule, row):
            if count >= limit:
                break
            occurrence = context_graph.fingerprint([rule.partner, rule.event, row["id"]])
            if not trigger.fires.filter(occurrence_key=occurrence).exists():
                research_triggers.materialize(
                    trigger,
                    occurrence,
                    {
                        "partner": rule.partner,
                        "event": rule.event,
                        "model": row,
                        "discovery": "backfill"
                        if rule.include_existing and not trigger.source_state.get("scan_completed")
                        else "catalogue_addition",
                        "bindings": {"model": {"kind": "value", "value": row["id"]}},
                    },
                )
                count += 1
        seen.add(row["id"])
    pending = any(row["id"] not in seen for row in rows)
    trigger.source_state.update(seen_models=sorted(seen), last_scan_at=now.isoformat())
    if not pending:
        trigger.source_state["scan_completed"] = True
    trigger.next_at = now if pending else now + timedelta(hours=trigger.every_hours)
    trigger.note = ""
    trigger.save(update_fields=["source_state", "next_at", "note"])
    return count