Tool

Load GCS Files and Buckets

LlamaIndex reader that loads files or entire buckets from Google Cloud Storage.

Works with google cloud storage

75
Spark score
out of 100
Updated 2 days ago
Version 0.14.23
Models

Add to Favorites

Why it matters

Effortlessly ingest data from Google Cloud Storage into your AI applications. This asset can load individual files or entire buckets, providing a robust bridge for your data pipelines.

Outcomes

What it gets done

01

Load single files from GCS

02

Load entire GCS buckets with prefix filtering

03

List and retrieve information about GCS resources

04

Support for various GCS authentication methods

Install

Add it to your toolbox

Run in your project directory:

curl -fsSL https://spark.entire.vc/get/li-reader-readers-gcs | bash

Overview

GCS File or Directory Loader

The GCS Loader parses files or entire buckets from Google Cloud Storage into LlamaIndex documents, with resource listing, per-object inspection, custom file-type extractors, and robust error handling and logging. Use it when you need GCS content loaded into LlamaIndex -- a single file, a filtered subset, or a whole bucket. It authenticates via a service account key or falls back to default credentials.

What it does

The GCS Loader parses any file stored on Google Cloud Storage, or an entire bucket (optionally filtered by a prefix) if no specific file is given. It implements LlamaIndex's ResourcesReaderMixin and FileSystemReaderMixin, which add methods beyond simple loading: listing resources in a bucket, retrieving detailed information about a GCS object, loading a specific resource, and reading a file's content directly. It also includes comprehensive logging and robust error handling.

When to use - and when NOT to

Use it when you need to load one file, a filtered subset, or an entire GCS bucket into LlamaIndex documents -- or when you need finer-grained operations like listing bucket resources or inspecting a specific object before loading it. Authentication accepts a GCP service account key as a file path, a JSON string, or a dictionary, or falls back to default credentials if none are given, so it is not usable without GCS access configured one way or another.

Inputs and outputs

Initialize with a bucket name, and optionally a single file key or a prefix to filter multiple files:

from llama_index.readers.gcs import GCSReader
import logging

logging.basicConfig(level=logging.INFO)

reader = GCSReader(
    bucket="scrabble-dictionary",
    key="dictionary.txt",  # Optional: specify a single file
    # prefix="subdirectory/",  # Optional: specify a prefix to filter files
    service_account_key_json="[SERVICE_ACCOUNT_KEY_JSON]",
)

documents = reader.load_data()
resources = reader.list_resources()
resource_info = reader.get_resource_info("dictionary.txt")
specific_doc = reader.load_resource("dictionary.txt")
file_content = reader.read_file_content("dictionary.txt")

Each call returns something inspectable: load_data() returns the parsed documents, list_resources() returns the bucket's resource keys, get_resource_info() returns metadata about one object, load_resource() returns a single loaded document, and read_file_content() returns the raw bytes of a file.

Nested files need their subdirectory in the key, e.g. subdirectory/input.txt. All files are parsed with SimpleDirectoryReader, and you can pass a custom file_extractor dict to route specific file extensions to other LlamaIndex loaders (or your own) -- for example mapping .mongo to SimpleMongoReader(). Authentication failures raise google.auth.exceptions.DefaultCredentialsError, which you can catch specifically (for example to print "Authentication failed. Please check your credentials.") alongside a general Exception handler for anything else -- letting an application respond gracefully rather than crash on a config mistake. For advanced usage beyond what's covered here -- custom file extractors, metadata extraction, and working with specific file types -- the LlamaIndex documentation goes into further depth.

Who it's for

Developers building LlamaIndex pipelines on Google Cloud Storage content, who need anything from a single-file load to full-bucket ingestion with custom per-file-type parsing.

Source README

GCS File or Directory Loader

This loader parses any file stored on Google Cloud Storage (GCS), or the entire Bucket (with an optional prefix filter) if no particular file is specified. It now supports more advanced operations through the implementation of ResourcesReaderMixin and FileSystemReaderMixin.

Features

  • Parse single files or entire buckets from GCS
  • List resources in GCS buckets
  • Retrieve detailed information about GCS objects
  • Load specific resources from GCS
  • Read file content directly
  • Supports various authentication methods
  • Comprehensive logging for easier debugging
  • Robust error handling for improved reliability

Authentication

When initializing GCSReader, you may pass in your GCP Service Account Key in several ways:

  1. As a file path (service_account_key_path)
  2. As a JSON string (service_account_key_json)
  3. As a dictionary (service_account_key)

If no credentials are provided, the loader will attempt to use default credentials.

Usage

To use this loader, you need to pass in the name of your GCS Bucket. You can then either parse a single file by passing its key, or parse multiple files using a prefix.

from llama_index.readers.gcs import GCSReader
import logging

### Set up logging (optional, but recommended)
logging.basicConfig(level=logging.INFO)

### Initialize the reader
reader = GCSReader(
    bucket="scrabble-dictionary",
    key="dictionary.txt",  # Optional: specify a single file
    # prefix="subdirectory/",  # Optional: specify a prefix to filter files
    service_account_key_json="[SERVICE_ACCOUNT_KEY_JSON]",
)

### Load data
documents = reader.load_data()

### List resources in the bucket
resources = reader.list_resources()

### Get information about a specific resource
resource_info = reader.get_resource_info("dictionary.txt")

### Load a specific resource
specific_doc = reader.load_resource("dictionary.txt")

### Read file content directly
file_content = reader.read_file_content("dictionary.txt")

print(f"Loaded {len(documents)} documents")
print(f"Found {len(resources)} resources")
print(f"Resource info: {resource_info}")
print(f"Specific document: {specific_doc}")
print(f"File content length: {len(file_content)} bytes")

Note: If the file is nested in a subdirectory, the key should contain that, e.g., subdirectory/input.txt.

Advanced Usage

All files are parsed with SimpleDirectoryReader. You may specify a custom file_extractor, relying on any of the loaders in the LlamaIndex library (or your own)!

from llama_index.readers.gcs import GCSReader
from llama_index.readers.mongodb import SimpleMongoReader

reader = GCSReader(
    bucket="my-bucket",
    file_extractor={
        ".mongo": SimpleMongoReader(),
        # Add more custom extractors as needed
    },
)

Error Handling

The GCSReader now includes comprehensive error handling. You can catch exceptions to handle specific error cases:

from google.auth.exceptions import DefaultCredentialsError

try:
    reader = GCSReader(bucket="your-bucket-name")
    documents = reader.load_data()
except DefaultCredentialsError:
    print("Authentication failed. Please check your credentials.")
except Exception as e:
    print(f"An error occurred: {str(e)}")

Logging

To get insights into the GCSReader's operations, configure logging in your application:

import logging

logging.basicConfig(level=logging.INFO)

This loader is designed to be used as a way to load data into LlamaIndex. For more advanced usage, including custom file extractors, metadata extraction, and working with specific file types, please refer to the LlamaIndex documentation.

FAQ

Common questions

Discussion

Questions & comments · 0

Sign In Sign in to leave a comment.