Léim go dtí an príomhábhar
Gaeilge— Roghnaigh teanga
Roghchlár

Teorainn ráta agus cosc ar mhí-úsáid

Ceacht 8 as 14 Nuashonraithe 28 Iúil 2026 Ardleibhéal
Ar an leathanach seo
  1. Cén fáth teorainn a chur le hiarratais?
  2. Dhá bhealach chun comhaireamh a dhéanamh
  3. Bot a aithint
  4. Smachtbhannaí céimnithe
  5. Tá tábhacht le hord na seiceálacha
  6. Príomhphointí

Cén fáth teorainn a chur le hiarratais?

Is spriocanna idéalacha iad feidhmchláir AI do mhí-úsáid ar chúis nach raibh ann le haipeanna traidisiúnta: costáil airgead gach glaonna ar mhúnla. Nuair a bhíonn tuile iarratas ag cur isteach ar API REST traidisiúnta, moillíonn sé agus briseann sé sa deireadh, ach ní dhraenálann sé cuntas bainc. Feidhmchlár LLM, áfach, leanann sé ag freagairt go foirfe fad is a théann an bille in airde go géar. Gan teorainn ráta, is féidir le hionsaitheoir do bhuiséad API a scriosadh i gceann nóiméad, ionsaithe insteallta pras uathoibrithe a sheoladh, nó d’infreastruchtúr a úsáid chun spam a ghiniúint ar do chostas.

Dhá bhealach chun comhaireamh a dhéanamh

Is é an fhuinneog shleamhnáin an mheicníocht bhunúsach. Taifeadann sé stampa ama gach iarrtais, caiteann sé siad na cinn a thit amach as an bhfuinneog, agus déanann sé comparáid idir an fuílleach agus an t-uasteorainn. Tagann a shárcheannas ar an bhfuinneog sheasta síos go dtí mionsonra a bhfuil tábhacht phraiticiúil leis: le fuinneog sheasta a athshocraíonn gach nóiméad, is féidir le hionsaitheoir a gcuóta a chur ag deireadh nóiméid amháin agus arís ag tús an chinn eile, rud a dhéanann dúbailt éifeachtach ar an tréchur ceadaithe thar cúpla soicind. Ní fhágann an fhuinneog shleamhnáin aon bhearna den sórt sin.

Ina theannta sin, ní thugann an fheidhm booleán simplí ar ais; tugann sí foclóir ar ais a léiríonn na hiarratais atá fágtha agus an t-am go dtí an t-athshocrú. Líonann na luachanna seo na ceanntásc freagartha a úsáidfidh do chliaint dhlisteanacha chun iad féin a rialáil – fanann comhtháthú dea-dheartha seachas an pointe deiridh a bhualadh gan stad.

import time
from collections import defaultdict

class RateLimiter:
    """Sliding window rate limiter."""

    def __init__(self, max_requetes: int, fenetre_secondes: int):
        self.max_requetes = max_requetes
        self.fenetre = fenetre_secondes
        self.requetes: dict[str, list[float]] = defaultdict(list)

    def autoriser(self, identifiant: str) -> tuple[bool, dict]:
        """Checks if a request is allowed for this identifier."""
        maintenant = time.time()
        seuil = maintenant - self.fenetre

        # Clean up old requests
        self.requetes[identifiant] = [
            t for t in self.requetes[identifiant] if t > seuil
        ]

        nb_requetes = len(self.requetes[identifiant])

        if nb_requetes >= self.max_requetes:
            prochain_slot = self.requetes[identifiant][0] + self.fenetre
            return False, {
                "restantes": 0,
                "reset_dans": round(prochain_slot - maintenant, 1),
            }

        self.requetes[identifiant].append(maintenant)
        return True, {
            "restantes": self.max_requetes - nb_requetes - 1,
            "reset_dans": round(self.fenetre - (maintenant - self.requetes[identifiant][0]), 1),
        }

# Configuration by role
limiteurs = {
    "gratuit": RateLimiter(max_requetes=10, fenetre_secondes=60),
    "premium": RateLimiter(max_requetes=60, fenetre_secondes=60),
    "api": RateLimiter(max_requetes=200, fenetre_secondes=60),
}

Ní leor comhaireamh a dhéanamh ar iarratais, áfach, toisc nach bhfuil gach iarratas cothrom. Costálann deich gceist ghairid codán den méid a chostálann iarratas amháin a bhfuil cáipéis caoga leathanach ag gabháil leis. Ligfeadh teorainneoir in aghaidh an iarrtais don cheann deireanach tríd agus chuirfeadh sé bac ar an gceann tosaigh, rud atá díreach contrártha leis an méid a éilíonn eacnamaíocht seirbhíse. Aistríonn buiséad token comhréireacht ar ais, le hathshocrú laethúil agus taifeadadh ar an úsáid iarbhír tar éis na fíricí, ós rud é nach bhfuil a fhios ag an meastachán a rinneadh roimh an nglao ar fhad na freagartha.

class TokenBudgetLimiter:
    """Limits token spending per user."""

    def __init__(self, budget_tokens_jour: int, cout_par_1k_input: float, cout_par_1k_output: float):
        self.budget_jour = budget_tokens_jour
        self.cout_input = cout_par_1k_input
        self.cout_output = cout_par_1k_output
        self.usage: dict[str, dict] = defaultdict(lambda: {"tokens_in": 0, "tokens_out": 0, "date": ""})

    def verifier_budget(self, user_id: str, tokens_estimes: int) -> tuple[bool, dict]:
        """Checks if the user still has budget."""
        from datetime import date
        aujourd_hui = str(date.today())

        # Daily reset
        if self.usage[user_id]["date"] != aujourd_hui:
            self.usage[user_id] = {"tokens_in": 0, "tokens_out": 0, "date": aujourd_hui}

        total_utilise = self.usage[user_id]["tokens_in"] + self.usage[user_id]["tokens_out"]
        restant = self.budget_jour - total_utilise

        if tokens_estimes > restant:
            return False, {"restant": restant, "demande": tokens_estimes}

        return True, {"restant": restant - tokens_estimes}

    def enregistrer_usage(self, user_id: str, tokens_in: int, tokens_out: int):
        """Records actual usage after a call."""
        self.usage[user_id]["tokens_in"] += tokens_in
        self.usage[user_id]["tokens_out"] += tokens_out

# Example: 100K tokens/day for free users
budget = TokenBudgetLimiter(
    budget_tokens_jour=100_000,
    cout_par_1k_input=0.005,
    cout_par_1k_output=0.015,
)

Bot a aithint

Fanann ionsaitheoir modúil faoi do uasteorainneacha: níl le déanamh aige ach moilliú. Dá bhrí sin, éilíonn brath ar mhí-úsáid breathnú ar chruth an tráchta seachas ar a mhéid. Comhlánaíonn na ceithre chomhartha a chuirtear i bhfeidhm thíos a chéile go maith. Nochtann athrá comhionann script atá gafa i lúb. Léiríonn pléasc iarratas laistigh de chúpla soicind luas nach féidir le haon duine a choinneáil ag an méarchlár. Seolann teachtaireacht atá na mílte carachtar ar fad iarracht insteallta toirtí. Is é an ceathrú ceann an ceann is suimiúla: nochtann faid teachtaireachta atá go hiomlán comhionann thar dheich n-iarratas as a chéile fuzzer ag athrú ábhair le struchtúr tairiseach, agus scríobhann úsáideoir fíor abairtí ar faid neamhrialta.

from dataclasses import dataclass, field
from datetime import datetime

@dataclass
class ProfilUtilisateur:
    user_id: str
    requetes_recentes: list[dict] = field(default_factory=list)
    alertes: list[str] = field(default_factory=list)

class DetecteurAbus:
    """Detects automated abuse patterns."""

    def __init__(self):
        self.profils: dict[str, ProfilUtilisateur] = {}

    def analyser(self, user_id: str, message: str) -> list[str]:
        """Analyzes a message to detect abuse patterns."""
        if user_id not in self.profils:
            self.profils[user_id] = ProfilUtilisateur(user_id=user_id)

        profil = self.profils[user_id]
        alertes = []

        # Pattern 1: repeated identical messages
        if profil.requetes_recentes:
            derniers_messages = [r["message"] for r in profil.requetes_recentes[-5:]]
            if derniers_messages.count(message) >= 3:
                alertes.append("SPAM: identical message repeated 3+ times")

        # Pattern 2: abnormal frequency
        maintenant = datetime.now()
        recentes = [
            r for r in profil.requetes_recentes
            if (maintenant - r["timestamp"]).seconds < 10
        ]
        if len(recentes) > 5:
            alertes.append("FLOOD: 5+ requests in 10 seconds")

        # Pattern 3: very long messages (volumetric injection attempt)
        if len(message) > 10000:
            alertes.append(f"VOLUME: message of {len(message)} characters")

        # Pattern 4: systematic variation (automated fuzzing)
        if len(profil.requetes_recentes) >= 10:
            longueurs = [len(r["message"]) for r in profil.requetes_recentes[-10:]]
            if max(longueurs) - min(longueurs) < 5 and len(set(longueurs)) == 1:
                alertes.append("FUZZING: identical message length (bot)")

        # Record
        profil.requetes_recentes.append({
            "message": message,
            "timestamp": maintenant,
            "alertes": alertes,
        })

        return alertes

detecteur = DetecteurAbus()

Smachtbhannaí céimnithe

Bheadh sé ina bhotún costúil cosc a chur ar an gcéad aláram, toisc nach bhfuil aon cheann de na comharthaí seo dosháraithe: spreagann úsáideoir atá ag athnuachan leathanaigh go néarógach an brathadóir pléasctha gan a bheith mailíseach. Carnann cosc céimnithe scór agus spreagann sé freagairtí comhréireacha – rabhadh, ansin luasghéarú laghdaithe, ansin bloc sealadach uair an chloig, agus fiche ceathair uair an chloig sa deireadh. Tugann gach céim deis don úsáideoir dlisteanach teacht den chonair, agus leanann an script uathoibrithe í go dtí an deireadh.

class GestionBannissement:
    """Progressive banning: warning, throttling, blocking."""

    def __init__(self):
        self.compteurs: dict[str, int] = defaultdict(int)
        self.bans: dict[str, float] = {}

    def signaler(self, user_id: str, severite: int = 1) -> str:
        """Reports abuse and applies the appropriate sanction."""
        self.compteurs[user_id] += severite
        score = self.compteurs[user_id]

        if score >= 10:
            self.bans[user_id] = time.time() + 86400  # Ban 24h
            return "BAN_24H"
        elif score >= 5:
            self.bans[user_id] = time.time() + 3600  # Ban 1h
            return "BAN_1H"
        elif score >= 3:
            return "RALENTIR"  # Reduced rate limit
        else:
            return "AVERTIR"

    def est_banni(self, user_id: str) -> bool:
        """Checks if a user is currently banned."""
        if user_id in self.bans:
            if time.time() < self.bans[user_id]:
                return True
            del self.bans[user_id]
        return False

Tá tábhacht le hord na seiceálacha

Déanann an comhtháthú deiridh slabhrú ar na ceithre mheicníocht sula nglaofar ar an múnla, agus géilleann an t-ord seo do riail shimplí: ón gceann is lú costais go dtí an ceann is costasaí. Is cuardach foclóra é an tseiceáil cosc, scanann an teorainn ráta liosta gairid, déanann brath mí-úsáide anailís ar an stair, agus tagann rialú buiséid díreach roimh an nglao a bhfuil táille air. Dá gcuirfí an seicheamh seo ar ceal, chiallódh sé íoc as anailís iompraíochta d’úsáideoir atá faoi chois cheana féin. Is é an chéim dheireanach an ceann is minice a dhéantar dearmad air: úsáid iarbhír a thaifeadadh ón réimse usage den fhreagra, gan a mbeadh do bhuiséad ag imeacht ón meastachán a rinneadh roimh an nglao.

from openai import OpenAI

class APISecurisee:
    """API with integrated rate limiting and abuse detection."""

    def __init__(self):
        self.client = OpenAI()
        self.rate_limiter = RateLimiter(max_requetes=20, fenetre_secondes=60)
        self.budget = TokenBudgetLimiter(100_000, 0.005, 0.015)
        self.detecteur = DetecteurAbus()
        self.bans = GestionBannissement()

    def traiter(self, user_id: str, message: str) -> str:
        # Step 1: check ban status
        if self.bans.est_banni(user_id):
            return "Your access is temporarily suspended."

        # Step 2: rate limiting
        autorise, info = self.rate_limiter.autoriser(user_id)
        if not autorise:
            return f"Too many requests. Try again in {info['reset_dans']}s."

        # Step 3: abuse detection
        alertes = self.detecteur.analyser(user_id, message)
        if alertes:
            action = self.bans.signaler(user_id, severite=len(alertes))
            if action.startswith("BAN"):
                return "Abusive behavior detected. Access suspended."

        # Step 4: check token budget
        tokens_estimes = len(message) // 4 + 500
        ok, budget_info = self.budget.verifier_budget(user_id, tokens_estimes)
        if not ok:
            return "Daily token budget exhausted."

        # Step 5: call the model
        response = self.client.chat.completions.create(
            model="gpt-5.6-sol",
            messages=[{"role": "user", "content": message}],
        )

        # Record actual usage
        usage = response.usage
        self.budget.enregistrer_usage(user_id, usage.prompt_tokens, usage.completion_tokens)

        return response.choices[0].message.content

Príomhphointí

  • Cosnaíonn teorainn ráta do bhuiséad API agus cuireann sé cosc ar ionsaithe uathoibrithe
  • Comhcheangail teorainneacha in aghaidh an iarrtais (fuinneog shleamhnáin) agus teorainneacha in aghaidh an chostais (tokenanna)
  • Aithníonn brath mí-úsáide patrúin: spam, tuile, fuzzing, toirt
  • Seachnaíonn cosc céimnithe (rabhadh, luasghéarú, blocáil) dearbh-dheimhní buana
  • Ba chóir gach freagra a bheith ina bhfuil ceanntásc teorann ráta chun an t-úsáideoir a chur ar an eolas