# getUser()

Canonical URL: https://developers.iagenify.com/pt/sdk/ref/iagenify/get-user/
Language: pt

`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.

Status: GET /api/auth/me · free · four fields

## Retorno {#returns}

```javascript
{
  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
}
```

| Name | Type | Requirement | Description |
| --- | --- | --- | --- |
| `id` | string |  | Il conto. Estabile; vale la pena registrar a parîs de tot ce fastuès. |
| `email` | string |  | L'indirizzo con cui il cont era aperto. |
| `credits` | integer |  | A lecttura, non una reserva — vedi [in basso](#balance). |
| `pack` | string |  | 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()](/pt/sdk/ref/auth/update-profile) lo restitue.

## Pacote {#pack}

| Valor | Significado |
| --- | --- |
| libere | Il plan un cont inceput. |
| va | Un piano pagato. |
| Avance | Un piano pagat, con più di tutto. |
| freemium · impresa | Fixat per arrangiment e non per self-service. |
| freemium | An older name that follows `free`. |

Legga il plan per decidere cosa offrire, mai per calcolare un prezzo: un modele costa che [catalogo()](/pt/sdk/ref/iagenify/catalogue) 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}

`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.

| Simptom | Ce è successo |
| --- | --- |
| Non autorizzat gettat | La chiave fu respinta, o fu revocata. |
| Inalcase inalcaseable lançato | Non risponde a baseUrl. Verificare l'indirizzo prima. |
| Tempo de fuga tirado | Algo rispose troppo lento, o no. |
| Null returnò | La richiesta funziona, e non c'era un compte detrás di ella. |

## La verifica di boot {#healthcheck}

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.

```javascript
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;
  }
}
```

## Lectura del balance {#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î.

```javascript
// 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 });
```

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](/pt/sdk/concepts/credits).

## Quante frequent di dicir {#cost}

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.

```javascript
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;
}
```

- [Créditos](/pt/sdk/concepts/credits): Pre-autorizazion, regolamento, e come un déficit è negato.
- [Erros](/pt/sdk/concepts/errors): Le tre classi, e i campi valiu la pena ramificare.
- [updateProfile()](/pt/sdk/ref/auth/update-profile): Cambiando la parte del cont que è scribible.

```python
{
    "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
}
```

```python
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
```

```python
# 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)
```

```python
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
```
