Syncing
Re-sync an index after adding, updating, or removing files in the source directory.
After you add, update, or remove files in a directory, you need to sync the index to reflect those changes. Syncing re-parses changed files and re-exports updated chunks to the vector store.
The initial sync is triggered automatically when you create an index. Use the sync endpoint for subsequent updates.
Trigger a sync
Section titled “Trigger a sync”await client.indexes.sync("<your-index-id>")await client.indexes.sync("<your-index-id>");_, err := client.Indexes.Sync(ctx, "<your-index-id>", llamacloud.IndexSyncParams{})if err != nil { log.Fatal(err)}client.indexes().sync("<your-index-id>");llp beta:indexes sync --index-id "<your-index-id>"The sync runs asynchronously. Poll the index to know when it completes — see Typical workflow below for a race-safe polling loop.
Cancel a sync
Section titled “Cancel a sync”Request cancellation of a running index sync with POST /api/v1/indexes/{index_id}/sync/cancel:
202 Acceptedmeans the cancellation request was accepted, not that the sync has stopped.409 Conflictmeans there is no running sync to cancel.
Cancellation is asynchronous, so work can continue while the request takes effect. To check whether a sync is running, retrieve the individual index with expand=sync_in_progress. Treat sync_in_progress: null as unknown: the field was not requested or its state is unavailable.
Typical workflow
Section titled “Typical workflow”- Upload new files or remove outdated files from the directory.
- Read the index’s current
last_synced_atandstatus, then call the sync endpoint once. - Poll the index until
statusisreadyandlast_synced_athas advanced past the value from step 2, or untilstatusisfailedafter changing from its step 2 value. Resume retrieval or chat.
Download a one-page metrics report as new-report.pdf to add to the directory:
curl -fL -o new-report.pdf https://raw.githubusercontent.com/run-llama/llama-cloud-py/main/examples/extract/test-files/slide/saas_slide.pdfimport asyncioimport time
# Add a new file to the directorywith open("new-report.pdf", "rb") as f: file_obj = await client.files.create(file=f, purpose="user_data")
await client.beta.directories.files.add( directory_id, file_id=file_obj.id,)
# Note the state of the index before the sync. A freshly triggered sync keeps# reporting the previous status until it starts, so we wait for "ready" with# a newer last_synced_at, and trust "failed" only once the status has changed.prev = await client.indexes.get(index_id)before = prev.last_synced_atbefore_status = prev.metadata["status"] if prev.metadata else "unknown"
# Trigger a sync once, since the endpoint is rate limitedawait client.indexes.sync(index_id)
# Poll until this sync finishes, backing off between attempts and# giving up after a deadline.deadline = time.monotonic() + 600 # 10 minutesdelay = 2started = False # True once the status differs from before the triggerwhile True: idx = await client.indexes.get(index_id) status = idx.metadata["status"] if idx.metadata else "unknown" started = started or status != before_status
if status == "ready" and idx.last_synced_at != before: print("Sync complete!") break if status == "failed" and started: print("Sync failed:", idx.metadata["error_message"]) break if time.monotonic() >= deadline: raise TimeoutError("Sync did not complete within 10 minutes")
await asyncio.sleep(delay) delay = min(delay * 2, 30) # exponential backoff, capped at 30simport fs from "fs";
// Add a new fileconst fileObj = await client.files.create({ file: fs.createReadStream("new-report.pdf"), purpose: "user_data",});
await client.beta.directories.files.add(directoryId, { file_id: fileObj.id,});
// Note the state of the index before the sync. A freshly triggered sync keeps// reporting the previous status until it starts, so we wait for "ready" with// a newer last_synced_at, and trust "failed" only once the status has changed.const prev = await client.indexes.get(indexId);const before = prev.last_synced_at;const beforeStatus = (prev.metadata?.status as string) ?? "unknown";
// Trigger a sync (call this once — the endpoint is rate limited)await client.indexes.sync(indexId);
// Poll until this sync finishes, backing off between attempts and// giving up after a deadline.const deadline = Date.now() + 600_000; // 10 minuteslet delay = 2000;let started = false; // true once the status differs from before the triggerwhile (true) { const idx = await client.indexes.get(indexId); const status = (idx.metadata?.status as string) ?? "unknown"; started = started || status !== beforeStatus;
if (status === "ready" && idx.last_synced_at !== before) { console.log("Sync complete!"); break; } else if (status === "failed" && started) { console.error("Sync failed:", idx.metadata?.error_message); break; } else if (Date.now() >= deadline) { throw new Error("Sync did not complete within 10 minutes"); }
await new Promise((r) => setTimeout(r, delay)); delay = Math.min(delay * 2, 30_000); // exponential backoff, capped at 30s}// Add a new file to the directoryf, err := os.Open("new-report.pdf")if err != nil { log.Fatal(err)}defer f.Close()
fileObj, err := client.Files.New(ctx, llamacloud.FileNewParams{ File: f, Purpose: "user_data",})if err != nil { log.Fatal(err)}
_, err = client.Beta.Directories.Files.Add(ctx, directoryID, llamacloud.BetaDirectoryFileAddParams{ FileID: fileObj.ID,})if err != nil { log.Fatal(err)}
// Note the state of the index before the sync. A freshly triggered sync keeps// reporting the previous status until it starts, so we wait for "ready" with// a newer LastSyncedAt, and trust "failed" only once the status has changed.idxBefore, err := client.Indexes.Get(ctx, indexID, llamacloud.IndexGetParams{})if err != nil { log.Fatal(err)}before := idxBefore.LastSyncedAtbeforeStatus, ok := idxBefore.Metadata["status"].(string)if !ok { beforeStatus = "unknown"}
// Trigger a sync (call this once — the endpoint is rate limited)_, err = client.Indexes.Sync(ctx, indexID, llamacloud.IndexSyncParams{})if err != nil { log.Fatal(err)}
// Poll until this sync finishes, backing off between attempts and// giving up after a deadline.deadline := time.Now().Add(10 * time.Minute)delay := 2 * time.Secondstarted := false // true once the status differs from before the triggerfor { idx, err := client.Indexes.Get(ctx, indexID, llamacloud.IndexGetParams{}) if err != nil { log.Fatal(err) }
status, ok := idx.Metadata["status"].(string) if !ok { status = "unknown" } if status != beforeStatus { started = true }
if status == "ready" && !idx.LastSyncedAt.Equal(before) { fmt.Println("Sync complete!") break } else if status == "failed" && started { fmt.Println("Sync failed:", idx.Metadata["error_message"]) break } else if time.Now().After(deadline) { log.Fatal("Sync did not complete within 10 minutes") }
time.Sleep(delay) if delay < 30*time.Second { delay *= 2 if delay > 30*time.Second { delay = 30 * time.Second } }}import java.nio.file.Paths;import java.time.Duration;import java.time.Instant;import java.time.OffsetDateTime;import java.util.Optional;
import ai.llamaindex.llamacloud.models.beta.directories.files.FileAddParams;import ai.llamaindex.llamacloud.models.indexes.IndexGetResponse;import ai.llamaindex.llamacloud.models.files.FileCreateParams;import ai.llamaindex.llamacloud.models.files.FileCreateResponse;
// Add a new file to the directoryFileCreateResponse fileObj = client.files().create( FileCreateParams.builder() .file(Paths.get("new-report.pdf")) .purpose("user_data") .build());
client.beta().directories().files().add( directoryId, FileAddParams.builder() .fileId(fileObj.id()) .build());
// Note the state of the index before the sync. A freshly triggered sync keeps// reporting the previous status until it starts, so we wait for "ready" with// a newer lastSyncedAt, and trust "failed" only once the status has changed.IndexGetResponse prev = client.indexes().get(indexId);Optional<OffsetDateTime> before = prev.lastSyncedAt();String beforeStatus = prev.metadata() .map(m -> m._additionalProperties().get("status")) .map(v -> v.convert(String.class)) .orElse("unknown");
// Trigger a sync (call this once — the endpoint is rate limited)client.indexes().sync(indexId);
// Poll until this sync finishes, backing off between attempts and// giving up after a deadline.Instant deadline = Instant.now().plus(Duration.ofMinutes(10));long delayMs = 2000;boolean started = false; // true once the status differs from before the triggerwhile (true) { IndexGetResponse idx = client.indexes().get(indexId); String status = idx.metadata() .map(m -> m._additionalProperties().get("status")) .map(v -> v.convert(String.class)) .orElse("unknown"); started = started || !status.equals(beforeStatus);
if (status.equals("ready") && !idx.lastSyncedAt().equals(before)) { System.out.println("Sync complete!"); break; } else if (status.equals("failed") && started) { Optional<String> errOpt = idx.metadata() .map(m -> m._additionalProperties().get("error_message")) .map(v -> v.convert(String.class)); System.out.println("Sync failed: " + errOpt.orElse("")); break; } else if (Instant.now().isAfter(deadline)) { throw new RuntimeException("Sync did not complete within 10 minutes"); }
Thread.sleep(delayMs); delayMs = Math.min(delayMs * 2, 30000); // exponential backoff, capped at 30s}# Add a new file to the directoryFILE_ID=$(llp files create \ --file ./new-report.pdf \ --purpose user_data | jq -r '.id')
llp beta:directories:files add \ --directory-id "$DIRECTORY_ID" \ --file-id "$FILE_ID"
# Note the state of the index before the sync. A freshly triggered sync keeps# reporting the previous status until it starts, so we wait for "ready" with# a newer last_synced_at, and trust "failed" only once the status has changed.PREV=$(llp beta:indexes get --index-id "$INDEX_ID")BEFORE=$(printf '%s\n' "$PREV" | jq -r '.last_synced_at // ""')BEFORE_STATUS=$(printf '%s\n' "$PREV" | jq -r '.metadata.status // "unknown"')
# Trigger a sync once, since the endpoint is rate limitedllp beta:indexes sync --index-id "$INDEX_ID"
# Poll until this sync finishes, backing off between attempts and# giving up after 10 minutes.DEADLINE=$(( $(date +%s) + 600 ))DELAY=2STARTED=while true; do IDX=$(llp beta:indexes get --index-id "$INDEX_ID") || { printf '%s\n' "$IDX" >&2; break; } STATUS=$(printf '%s\n' "$IDX" | jq -r '.metadata.status // "unknown"') SYNCED_AT=$(printf '%s\n' "$IDX" | jq -r '.last_synced_at // ""') if [ "$STATUS" != "$BEFORE_STATUS" ]; then STARTED=1; fi
if [ "$STATUS" = "ready" ] && [ "$SYNCED_AT" != "$BEFORE" ]; then echo 'Sync complete!' break elif [ "$STATUS" = "failed" ] && [ -n "$STARTED" ]; then printf '%s\n' "$IDX" | jq -r '"Sync failed: \(.metadata.error_message // .)"' >&2 break elif [ "$(date +%s)" -ge "$DEADLINE" ]; then echo "Sync did not complete within 10 minutes" >&2 break fi
sleep "$DELAY" DELAY=$(( DELAY * 2 )) [ "$DELAY" -gt 30 ] && DELAY=30doneManaging indexes
Section titled “Managing indexes”Get an index
Section titled “Get an index”# Get an index by IDidx = await client.indexes.get("<your-index-id>")print(f"{idx.id}: status={idx.metadata['status']}")// Get an index by IDconst idx = await client.indexes.get("<your-index-id>");console.log(`${idx.id}: status=${idx.metadata?.status}`);// Get an index by IDidx, err := client.Indexes.Get(ctx, "<your-index-id>", llamacloud.IndexGetParams{})if err != nil { log.Fatal(err)}fmt.Printf("%s: status=%v\n", idx.ID, idx.Metadata["status"])import java.util.Optional;import ai.llamaindex.llamacloud.models.indexes.IndexGetResponse;
// Get an index by IDIndexGetResponse idx = client.indexes().get("<your-index-id>");Optional<String> statusOpt = idx.metadata() .map(m -> m._additionalProperties().get("status")) .map(v -> v.convert(String.class));String status = statusOpt.orElse("unknown");System.out.println(idx.id() + ": status=" + status);# Get an index by IDllp beta:indexes get --index-id "<your-index-id>" \ | jq -r '"\(.id): status=\(.metadata.status)"'Delete an index
Section titled “Delete an index”Deleting an index removes the sync and export configuration. The source directory and its files are not affected.
await client.indexes.delete("<your-index-id>")await client.indexes.delete("<your-index-id>");err := client.Indexes.Delete(ctx, "<your-index-id>", llamacloud.IndexDeleteParams{})if err != nil { log.Fatal(err)}client.indexes().delete("<your-index-id>");llp beta:indexes delete --index-id "<your-index-id>"