Cliente

getUser()

api.getUser() → Promise<User | null>

A chi appartiene la chiave, e a qual è l'equilibrio, il più corto che prova il funzion della catena intera.

GET /api/auth/mefreefour fields
Using Python?

Switch any code block to Python: the choice applies to every page. Python SDK guide and resource reference.

Retorno

{
  id: "…",                  // the account id
  email: "you@example.com",
  credits: 10869,           // the balance, at the moment of the call
  pack: "go"                // the plan this account is on
}
{
    "id": "…",                  # the account id
    "email": "you@example.com",
    "credits": 10869,           # the balance, at the moment of the call
    "pack": "go",               # the plan this account is on
}
idstring

Il conto. Estabile; vale la pena registrar a parîs de tot ce fastuès.

emailstring

L'indirizzo con cui il cont era aperto.

creditsinteger

A lecttura, non una reserva — vedi in basso.

packstring

Il piano. È il che decide quotas, non il che decide prezzo di un model.

Il servèrve detiene più di questo; il metodo lo restringe a quattro campi un program in realta ramies on. Quando si necessita di recorde più largo, updateProfile() lo restitue.

Pacote

ValorSignificado
libereIl plan un cont inceput.
vaUn piano pagato.
AvanceUn piano pagat, con più di tutto.
freemium · impresaFixat per arrangiment e non per self-service.
freemiumAn older name that follows free.

Legga il plan per decidere cosa offrire, mai per calcolare un prezzo: un modele costa che catalogo() dice. Il plan governa quanta camera un service ha - storages, buxes, hosts - e que i limiti sono legibili dal service che li impone.

Quando è null

null significa che l'appellazion ha succeduto e non ha portato conto. Non è a ce che una chiave errata pare: una chiave errata faults the session interchange, mundo prima de questo.

SimptomCe è successo
Non autorizzat gettatLa chiave fu respinta, o fu revocata.
Inalcase inalcaseable lançatoNon risponde a baseUrl. Verificare l'indirizzo prima.
Tempo de fuga tiradoAlgo rispose troppo lento, o no.
Null returnòLa richiesta funziona, e non c'era un compte detrás di ella.

La verifica di boot

E questo è l'appello a fare al startup. Ejerce la chiave, l'intercambio, la cache di sessione e una richiesta autenticat, non costa nulla, e fa fail in quattro distintible modos.

import { IaGenify, IaGenifyError, Unauthorized } from "iagenify";

export async function checkIaGenify(api) {
  try {
    const user = await api.getUser();
    if (!user) return { ok: false, why: "no account behind this key" };
    return { ok: true, email: user.email, credits: user.credits };
  } catch (err) {
    if (err instanceof Unauthorized) return { ok: false, why: "key refused or revoked" };
    if (err instanceof IaGenifyError && err.code === "unreachable") {
      return { ok: false, why: `no answer at ${api.baseUrl}` };
    }
    throw err;
  }
}
from iagenify import IaGenifyError, Unauthorized

def check_iagenify(api):
    try:
        user = api.get_user()
        if not user:
            return {"ok": False, "why": "no account behind this key"}
        return {"ok": True, "email": user["email"], "credits": user["credits"]}
    except Unauthorized:
        return {"ok": False, "why": "key refused or revoked"}
    except IaGenifyError as error:
        if error.code == "unreachable":
            return {"ok": False, "why": f"no answer at {api.base_url}"}
        raise

Lectura del balance

Il numero è vero quando è let e nulla lo retiene. Un run inceput un second spende contro il medesimo saldo, come lo fa ogni altro processo del conto.

Non porte un run a la balance

Controlare prima e spendere dopo lascia una finestra onde tanto triunfât e la seconda non deve avere. Dar la run un budget in lugar: si aplica onde il gasto accade, non dove tu guardî.

// Fragile: two processes both read 400 and both start a 300-credit run
const { credits } = await api.getUser();
if (credits < 300) throw new Error("not enough");
await agent.run({ message });

// Sound: the ceiling travels with the run, and a shortfall is refused at the debit
const agent = api.agents.create({ runtime: "local", machine: pc, budget: 300 });
await agent.run({ message });
# Fragile: two processes both read 400 and both start a 300-credit run
if api.get_user()["credits"] < 300:
    raise RuntimeError("not enough")
agent.run(message=message)

# Sound: the ceiling travels with the run, and a shortfall is refused at the debit
agent = api.agents.create(runtime="local", machine=pc, model=model, budget=300)
agent.run(message=message)

Un deficit superfície come una NotEnoughCredits exception portando ciò che era necessario e che era là — capture that plutôt que prevedindu-lo. Ved Crédits.

Quante frequent di dicir

Ogni chiamata è un indoven. Legindo una volta al bott, e ancora dopo qualcosa che spende, è suficiente; sondaj per richiesta aggiunge latenza a vos propri endpoints e dice nulla di nuovo entre spendes.

let cached = null;
let readAt = 0;

export async function user(api, maxAgeMs = 60_000) {
  if (!cached || Date.now() - readAt > maxAgeMs) {
    cached = await api.getUser();
    readAt = Date.now();
  }
  return cached;
}
import time

_cached = None
_read_at = 0.0

def user(api, max_age=60):
    global _cached, _read_at
    if _cached is None or time.monotonic() - _read_at > max_age:
        _cached = api.get_user()
        _read_at = time.monotonic()
    return _cached