api.files

file.save()

file.save({ storageId, path, localOnly }) → Promise<Result>

Escribe el archivo — a la cuenta, al disco local o a ambos. La que aquí se llama que cuesta un crédito.

POST /api/files/save1 creditrefunded if the write fails
Using Python?

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

Parámetros

storageIdstring

Sin ella, la cuenta es por defecto.

pathstring

Sólo nodo. También escriba los bytes a esta ruta local, creando las carpetas.

localOnlyboolean

Con path: escribir localmente y alto. Nada está cargado, nada está cargado.

Las tres maneras de usarlo

// 1. To the account — the usual one
await file.save();

// 2. To the account AND to this machine, in one call
await file.save({ path: "./out/report.md" });

// 3. To this machine only — no request, no credit
await file.save({ path: "./out/report.md", localOnly: true });
// { ok: true, status: "saved_local", path: "./out/report.md" }
# 1. To the account — the usual one
file.save()

# 2. To the account AND to this machine, in one call
file.save(path="./out/report.md")

# 3. To this machine only — no request, no credit
file.save(path="./out/report.md", local_only=True)
# {"ok": True, "status": "saved_local", "path": "./out/report.md"}
Una escritura local fallida no falla la llamada

Si el camino no puede ser escrito, el SDK advierte en la consola y continúa con la carga. Compruebe el archivo usted mismo cuando la copia local es la que importa — una carpeta de sólo lectura no se levantará.

Valor devuelto

{
  ok: true,
  status: "saved",
  sourceId: "…",            // how you find it again
  name: "report.md",
  category: "document",
  mimeType: "text/markdown",
  location: "object",       // the kind of storage it landed in
  metadata: {
    size: 2048,
    storageId: "…",
    remainingBytes: null,   // what is left, when the storage tracks it
    durationMs: 260
  },
  creditsUsed: 1
}
{
    "ok": True,
    "status": "saved",
    "sourceId": "…",            # how you find it again
    "name": "report.md",
    "category": "document",
    "mimeType": "text/markdown",
    "location": "object",       # the kind of storage it landed in
    "metadata": {
        "size": 2048,
        "storageId": "…",
        "remainingBytes": None,   # what is left, when the storage tracks it
        "durationMs": 260,
    },
    "creditsUsed": 1,
}

El objeto aprende de él: file.sourceId, file.location y file.metadata se establecen, que es lo que hace update() - Es posible después.

Elegir a dónde va

// The account's default
await file.save();

// A storage you named
const all = await api.storage.list();
const archive = all.find((s) => s.label === "Archive");
await file.save({ storageId: archive.id });
# The account's default
file.save()

# A storage you named
archive = next(s for s in api.storage.list() if s.label == "Archive")
file.save(storage_id=archive.id)
Tipo de almacenamientoGuardarlo
objeto · base de datossí — los bytes se mantienen en la cuenta
sistema de archivos (un ordenador)se deniega: storage_is_local
teléfono · navegadorse deniega: storage_is_local

La negativa llega antes el crédito se gasta. No es un fracaso para volver a intentar: esos dispositivos guardan sus propios archivos, y la forma de escribirlos es desde el dispositivo.

El crédito, y cuando vuelva

  • Un crédito se toma antes de la escritura.
  • Si la escritura entonces falla, es reembolsado íntegramente y te 502 storage_failed.
  • Una negativa que ocurre primero —sin almacenamiento, uno local, sin contenido— no cuesta nada en absoluto.

Un documento sigue siendo trabajado después de obtener su respuesta

Cuando la categoría es document, el texto se indexa para la búsqueda semántica una vez que la respuesta ha sido enviada. Así que un archivo es inmediatamente legible y localizable-por-significado un momento después.

No busques algo que acabas de salvar, en el mismo aliento

La indización no se espera deliberadamente — mantiene el ahorro rápido. Una búsqueda inmediatamente después puede no verlo todavía.

Errores

CódigoEstadoCuándoCrédito
— (error lanzado localmente)—el contenido es indefinido o nulo.No se tomó
missing_file_content400Ni un archivo ni contenido de texto llegaron al servidor.No se tomó
storage_not_found404La cuenta no tiene almacenamiento en absoluto.No se tomó
storage_is_local400El objetivo es un ordenador o un teléfono.No se tomó
not_enough_credits402El saldo no lo cubrirá.No se tomó
storage_failed502La escritura misma falló.reembolsado
import { IaGenifyError } from "iagenify";

try {
  await file.save({ storageId });
} catch (err) {
  if (err instanceof IaGenifyError && err.code === "storage_is_local") {
    // That storage is a device. Write it there instead.
    const device = await api.storage.get({ id: storageId });
    await device.files.write("report.md", file.content);
  } else throw err;
}
from iagenify import IaGenifyError

try:
    file.save(storage_id=storage_id)
except IaGenifyError as error:
    if error.code != "storage_is_local":
        raise
    # That storage is a device. Write it there instead.
    device = api.storage.get(id=storage_id)
    device.files.write("report.md", file.content)