--- title: "LangChain With Wasabi" slug: "langchain-with-wasabi" updated: 2026-11-17T20:41:15Z published: 2026-11-17T20:41:15Z canonical: "docs.wasabi.com/langchain-with-wasabi" --- > ## Documentation Index > Fetch the complete documentation index at: https://docs.wasabi.com/llms.txt > Use this file to discover all available pages before exploring further. # LangChain With Wasabi [LangChain](https://docs.langchain.com/oss/python/langchain/overview) is an open-source framework for building applications around language models. Many LangChain applications read source documents from object storage and save derived data, such as cached embeddings, so they do not repeat expensive work. Wasabi Hot Cloud Storage can be used for storing LangChain data. This article covers two common patterns: loading documents from a Wasabi bucket and storing cached embeddings in a Wasabi bucket. It also covers a fallback that doesn't depend on the langchain-community package, which LangChain has announced it is sunsetting. ## Requirements This solution was tested with the software versions listed below. Later compatible versions are expected to work, but have not been specifically tested. - Active [Wasabi Hot Cloud Storage](https://wasabi.com/try-free) account. - Wasabi bucket—For more information, review [2—Working With Buckets and Objects](https://docs.wasabi.com/docs/working-with-buckets-and-objects). - Ubuntu Server 24.04.5 LTS. - Python 3.12.3. - langchain-core 1.8.0. - langchain-classic 1.0.8. - langchain-community 0.4.2—Required only by test_langchain_wasabi.py (Appendix A). - unstructured 0.27.37—Required only by test_langchain_wasabi.py (Appendix A). - boto3 1.44.1. Optional embedding providers are: - Hugging Face—langchain-huggingface 1.2.3 and sentence-transformers 6.3.0, using the all-MiniLM-L6-v2 model. - Ollama—Ollama 0.40.16, langchain-ollama 1.1.0, and the ollama Python client 0.6.3, using the nomic-embed-text model. - OpenAI—langchain-openai 1.7.4. **Not tested.** The package installs, but no run was made against OpenAI. ## Wasabi Configuration > Reference commands in this article use the placeholder YOUR_WASABI_BUCKET_NAME—replace it with your own bucket name. Commands and output labeled “Example” are copied directly from the terminal during testing for this article, using a real bucket named mt-langchain. 1. Log in to the [Wasabi Console](https://console.wasabisys.com) as the account root user. 2. Create the following policy. Change YOUR_WASABI_BUCKET_NAME to your own Wasabi bucket name. See [Creating a Policy](https://docs.wasabi.com/docs/creating-a-policy) for instructions on how to create a policy. ```json {  "Version": "2012-10-17",  "Statement": [    {      "Sid": "AccountLevel",      "Effect": "Allow",      "Action": "s3:ListAllMyBuckets",      "Resource": "arn:aws:s3:::*"    },    {      "Sid": "BucketLevel",      "Effect": "Allow",      "Action": "s3:ListBucket",      "Resource": "arn:aws:s3:::YOUR_WASABI_BUCKET_NAME"    },    {      "Sid": "ObjectLevel",      "Effect": "Allow",      "Action": [        "s3:GetObject",        "s3:PutObject",        "s3:PutObjectTagging",        "s3:DeleteObject",        "s3:AbortMultipartUpload",        "s3:ListMultipartUploadParts"      ],      "Resource": "arn:aws:s3:::YOUR_WASABI_BUCKET_NAME/*"    }  ] } ``` 3. Create a “langchain” user and attach the previously created policy to it. Use the following settings for the user. For more information, see [Creating a User](https://docs.wasabi.com/docs/creating-a-user-account-and-access-key#creating-a-user). - Allow programmatic-only access, not console access. - Do not require Multi-Factor Authentication (MFA). - It is not necessary to assign the user to a group. - Save the access and secret keys in a secure location. ## Preparing the Server These steps prepare an Ubuntu Server 24.04 LTS machine to run the test scripts. The server requires outbound HTTPS access to your Wasabi storage region. The steps assume Python 3.12 with the `venv` module available. On Ubuntu Server 24.04 LTS, the `venv` module comes from the `python3-venv` package. 1. Create and activate a virtual environment. ```bash python3 -m venv ~/lc-wasabi source ~/lc-wasabi/bin/activate ``` 2. Install the Python packages for the main script. ```bash pip install langchain-core langchain-classic langchain-community boto3 unstructured ``` > The code snippets in the sections that follow come from the test scripts in [Appendix A](/v1/docs/langchain-with-wasabi#appendix-a-testlangchainwasabipy) and [Appendix B](/v1/docs/langchain-with-wasabi#appendix-b-testlangchainwasabistandalonepy). ## Connecting to Wasabi LangChain reaches Wasabi through the S3 API, so the first step is an S3 client that points at your storage bucket. The test script reads your keys, bucket name, and service URL from environment variables, and builds a boto3 client from them. Names that appear in later snippets, such as s3, BUCKET, and DOCS_PREFIX, are defined in this first snippet. ```python import os import time import boto3 from botocore.config import Config ACCESS_KEY = os.environ["WASABI_ACCESS_KEY"] SECRET_KEY = os.environ["WASABI_SECRET_KEY"] BUCKET = os.environ["WASABI_BUCKET"] REGION = os.environ.get("WASABI_REGION", "us-east-1") ENDPOINT = os.environ.get("WASABI_ENDPOINT_URL") or f"https://s3.{REGION}.wasabisys.com" _prefix = os.environ.get("WASABI_PREFIX", "").strip("/") ROOT = f"{_prefix}/" if _prefix else f"langchain-test/{int(time.time())}/" DOCS_PREFIX = ROOT + "docs/" CACHE_PREFIX = ROOT + "embedding-cache/" s3 = boto3.client(    "s3",    endpoint_url=ENDPOINT,    region_name=REGION,    aws_access_key_id=ACCESS_KEY,    aws_secret_access_key=SECRET_KEY,    config=Config(retries={"max_attempts": 3, "mode": "standard"}), ) ``` The WASABI_PREFIX variable sets the folder for the test objects. If you do not set it, the script uses a new folder named with a timestamp for each run. To check the connection, the script calls `head_bucket`, which checks that the bucket exists and that your keys can reach it. It then writes its sample files into the bucket with `put_object`. SAMPLE_DOCS is a dictionary of file names and text defined in the script. ```python s3.head_bucket(Bucket=BUCKET) for name, text in SAMPLE_DOCS.items():    s3.put_object(Bucket=BUCKET, Key=DOCS_PREFIX + name, Body=text.encode()) ``` ## Loading Documents From Wasabi The main test script (Appendix A) loads documents with LangChain's S3DirectoryLoader, which reads every object under a bucket prefix and returns each one as a LangChain document. To use it with Wasabi, the script sets endpoint_url to the service URL for your storage region and region_name to the matching region, and passes your access and secret keys. ```python from langchain_community.document_loaders import S3DirectoryLoader loader = S3DirectoryLoader(    BUCKET,    prefix=DOCS_PREFIX,    endpoint_url=ENDPOINT,    region_name=REGION,    aws_access_key_id=ACCESS_KEY,    aws_secret_access_key=SECRET_KEY, ) loaded = loader.load() ``` The loader uses the unstructured package to read each file. Only plain text files were tested for this article. Other file types were not tested and may need additional system packages. > The examples in this article use Wasabi’s us-east-2 storage region. To use another region, use the matching URL in [Service URLs for Wasabi’s Storage Regions](https://docs.wasabi.com/docs/service-urls-for-wasabis-storage-regions), and use the URL for the region in which your bucket is located. ## Storing Cached Embeddings in Wasabi Creating an embedding for a piece of text takes time, and with a hosted model it also costs money. LangChain's CacheBackedEmbeddings saves each embedding the first time it is created and returns the saved copy on later requests. LangChain has no built-in store for S3-compatible storage, so both test scripts include a small store, WasabiByteStore, of about 30 lines. It keeps each cached value as one object in your Wasabi bucket. ### Creating the Store WasabiByteStore implements LangChain's ByteStore interface with four methods: read, write, delete, and list. Each cached value becomes one object under the prefix you give it. ```python from langchain_core.stores import ByteStore class WasabiByteStore(ByteStore):    """Minimal ByteStore that keeps each value as one object in a Wasabi bucket."""    def __init__(self, client, bucket, prefix):        self.client, self.bucket, self.prefix = client, bucket, prefix    def mget(self, keys):        out = []        for k in keys:            try:                obj = self.client.get_object(Bucket=self.bucket, Key=self.prefix + k)                out.append(obj["Body"].read())            except self.client.exceptions.NoSuchKey:                out.append(None)        return out    def mset(self, key_value_pairs):        for k, v in key_value_pairs:            self.client.put_object(Bucket=self.bucket, Key=self.prefix + k, Body=v)    def mdelete(self, keys):        for k in keys:            self.client.delete_object(Bucket=self.bucket, Key=self.prefix + k)    def yield_keys(self, *, prefix=None):        full = self.prefix + (prefix or "")        for page in self.client.get_paginator("list_objects_v2").paginate(            Bucket=self.bucket, Prefix=full        ):            for item in page.get("Contents", []):                yield item["Key"][len(self.prefix):] ``` ### Use a Namespace That Names the Embedding Model The namespace value becomes the start of every cached object name. Make it specific to the embedding model. If two models share a namespace, switching models returns the old model's saved vectors instead of creating new ones, and nothing reports an error. The test scripts build the namespace from the model name automatically with this function. ```python import re def cache_namespace(model_name):    """Cache keys must be specific to the embedding model.    Without this, switching models while reusing a prefix would silently return    the old model's vectors from the cache.    """    return re.sub(r"[^A-Za-z0-9._-]+", "-", model_name).strip("-") + "-" ``` ### Use SHA-256 for Cache Keys By default, CacheBackedEmbeddings hashes each text with SHA-1 to create its cache key, and LangChain warns that SHA-1 can't guarantee two different texts get different keys. Setting key_encoder="sha256" avoids the warning. Changing the key encoder later starts a new cache, because the old object names no longer match. ### Wrap the Embedding Model With the Cache The script wraps the model in CountingEmbeddings, a small class that counts how many texts the model actually embeds. The count shows you the cache working. ```python from langchain_core.embeddings import DeterministicFakeEmbedding, Embeddings class CountingEmbeddings(Embeddings):    """Wraps any embedding model and counts how many texts it actually embeds."""    def __init__(self, base):        self.base, self.count = base, 0    def embed_documents(self, texts):        self.count += len(texts)        return self.base.embed_documents(texts)    def embed_query(self, text):        return self.base.embed_query(text) ``` Next, the script creates the store, wraps the model, and embeds the same texts twice. On the first pass, the model embeds each text and the store saves the result in Wasabi. On the second pass, every vector comes from the bucket, so the count stays at 0. In this excerpt, emb is the embedding model and emb_name is its name. Both come from get_base_embeddings() in the script, which selects the model from the EMBEDDING_PROVIDER variable. ```python try:    from langchain.embeddings import CacheBackedEmbeddings except ImportError:  # LangChain 1.x moved this to langchain-classic    from langchain_classic.embeddings import CacheBackedEmbeddings base = CountingEmbeddings(emb) byte_store = WasabiByteStore(s3, BUCKET, CACHE_PREFIX) cached = CacheBackedEmbeddings.from_bytes_store(    base, byte_store, namespace=cache_namespace(emb_name), key_encoder="sha256" ) texts = list(SAMPLE_DOCS.values()) cached.embed_documents(texts) first_calls = base.count stored = len(list(byte_store.yield_keys(prefix=cache_namespace(emb_name)))) base.count = 0 cached.embed_documents(texts)  # should be served from Wasabi second_calls = base.count ``` ## Running the Test Scripts This article includes two test scripts. Both check that LangChain can reach your bucket with your keys, endpoint, and permissions. The full text of each script is in the appendices at the end of this article. Copy each one into a file with the name shown. - test_langchain_wasabi.py ([Appendix A](/v1/docs/langchain-with-wasabi#appendix-a-testlangchainwasabipy))—Loads documents with S3DirectoryLoader, then runs the embedding cache test. - test_langchain_wasabi_standalone.py ([Appendix B](/v1/docs/langchain-with-wasabi#appendix-b-testlangchainwasabistandalonepy))—Does the same without langchain-community. See [Running Without langchain-community](/v1/docs/langchain-with-wasabi#running-without-langchaincommunity). Each script first copies five small text files into your bucket, so you don't need to supply any documents. ### Set the Environment Variables | **Variable** | **Description** | | --- | --- | | WASABI_ACCESS_KEY | Required. The access key for the user you created. | | WASABI_SECRET_KEY | Required. The secret key for the user you created. | | WASABI_BUCKET | Required. The name of an existing bucket. | | WASABI_ENDPOINT_URL | The service URL for your storage region, such as https://s3.us-east-2.wasabisys.com. If you don't set it, the script builds it from WASABI_REGION. | | WASABI_REGION | The region your bucket is in. The default is us-east-1. It must match the service URL. | | WASABI_PREFIX | A fixed folder for the test objects, such as rag/. If you don't set it, each run writes to a new folder named with a timestamp. | | CLEANUP | Set to 1 to delete this run's objects when the run finishes. By default, the script keeps them. | | EMBEDDING_PROVIDER | fake (the default), huggingface, ollama, or openai. See [Using a Different Embedding Model](/v1/docs/langchain-with-wasabi#using-a-different-embedding-model) . | | EMBEDDING_MODEL | Optional. The model name. Each provider has a default. | To keep the variables set every time you log in, add them to the `.bashrc` file in your home directory. Open `~/.bashrc` in a text editor (for example, vi, nano) and add these lines at the end. Replace YOUR_WASABI_ACCESS_KEY, YOUR_WASABI_SECRET_KEY, and YOUR_WASABI_BUCKET_NAME with your own access key, secret key, and bucket name, respectively. Use the URL and region in which your bucket is located. ```plaintext export WASABI_ACCESS_KEY=YOUR_WASABI_ACCESS_KEY export WASABI_SECRET_KEY=YOUR_WASABI_SECRET_KEY export WASABI_BUCKET=YOUR_WASABI_BUCKET_NAME export WASABI_ENDPOINT_URL=https://s3.us-east-2.wasabisys.com export WASABI_REGION=us-east-2 export WASABI_PREFIX=rag/ ``` The file now holds your secret key as plain text, so restrict it to your own account. ```bash chmod 600 ~/.bashrc ``` Then load the new values into your current session. Terminal sessions you open later load them automatically. ```bash source ~/.bashrc ``` > On the test server, the default permissions on `.bashrc (-rw-r--r--)` let other users read the file. The `chmod` command changes that. Use a Wasabi user whose policy is limited to the test bucket, as described in [Wasabi Configuration](/v1/docs/langchain-with-wasabi#wasabi-configuration), so a leaked key can reach only that bucket. ### Run the Main Script ```bash source ~/lc-wasabi/bin/activate python test_langchain_wasabi.py ``` By default the script uses fake embeddings, so it needs no language model and no API key. An example run is below. ```plaintext (lc-wasabi) user@server:~$ python test_langchain_wasabi.py /home/user/test_langchain_wasabi.py:57: DeprecationWarning: `langchain-community` is being sunset and is no longer actively maintained. See https://github.com/langchain-ai/langchain-community/issues/674 for details and migration guidance toward standalone integration packages.  from langchain_community.document_loaders import S3DirectoryLoader Embedding model: fake (deterministic) [PASS] 0. Connect and seed sample files (0.62s) endpoint=https://s3.us-east-2.wasabisys.com [PASS] 1. S3DirectoryLoader reads docs from Wasabi (4.36s) loaded 5 documents [PASS] 2. Embedding cache stored in Wasabi (0.79s) namespace=fake-deterministic- pass 1 embedded 5, pass 2 embedded 0, 5 objects in cache Objects kept under s3://mt-langchain/rag/  docs:            rag/docs/  embedding cache: rag/embedding-cache/ Summary  PASS  0. Connect and seed sample files  0.62s  PASS  1. S3DirectoryLoader reads docs from Wasabi  4.36s  PASS  2. Embedding cache stored in Wasabi  0.79s ``` The results mean the following. - Step 0 confirms the script can reach your bucket and write to it. - Step 1 confirms LangChain can read the files back from Wasabi. - Step 2 confirms the embedding cache works. The script asks the cached embedding model to embed the same 5 texts twice. In the output, “embedded” is the number of texts the model actually processed. The cache is stored in your Wasabi bucket, not on the server. Each saved embedding is one object in the embedding-cache folder. - Pass 1: None of the texts is in the cache yet, so the model processes all 5 and the script saves each embedding as an object in Wasabi. The output shows “pass 1 embedded 5.” - Pass 2: The script looks up each text in the bucket, finds the object saved on pass 1, and reads the embedding from Wasabi instead of calling the model. The output shows “pass 2 embedded 0.” The DeprecationWarning is expected. It is LangChain's notice that langchain-community is being sunset. > If you run the script again with the same WASABI_PREFIX and the same embedding model, the cache is already populated. The script reports “cache already warm” and pass 1 embeds 0 texts. This is expected, and it shows the cached vectors persist in Wasabi between runs. ## Using a Different Embedding Model The storage code does not change with the embedding model. Set EMBEDDING_PROVIDER to switch models. Each model gets its own cache namespace, so switching models under the same prefix creates new cached objects. | **Provider** | **Install** | **Default model** | **Tested** | | --- | --- | --- | --- | | fake (default) | Nothing extra. | Deterministic fake embeddings | Yes | | huggingface | `pip install langchain-huggingface sentence-transformers` | sentence-transformers/all-MiniLM-L6-v2 | Yes | | ollama | Install Ollama (see [Run with Ollama](/v1/docs/langchain-with-wasabi#run-with-ollama)), then `pip install langchain-ollama` | nomic-embed-text | Yes | | openai | `pip install langchain-openai` and `set OPENAI_API_KEY` | text-embedding-3-small | No | > Set EMBEDDING_PROVIDER for a single run, as in the Ollama example below, instead of adding it to `.bashrc`. A value in `.bashrc` applies to every run. If you added it there, remove the line and run `unset EMBEDDING_PROVIDER EMBEDDING_MODEL` in your current session. Running `source ~/.bashrc` after you remove the line does not clear a variable that is already set. The first Hugging Face run downloads the model, which is about 90 MB. The download needs internet access to [huggingface.co](http://huggingface.co). ### Run With Ollama The Ollama install script needs sudo, creates a system service, and downloads the model, which is about 274 MB. The test server had no GPU, and Ollama ran in CPU-only mode. ```bash curl -fsSL https://ollama.com/install.sh | sh ollama pull nomic-embed-text pip install langchain-ollama EMBEDDING_PROVIDER=ollama python test_langchain_wasabi.py ``` A successful run shows a model-specific namespace and the same pass 1 and pass 2 behavior as the example above.* ```plaintext Embedding model: ollama:nomic-embed-text [PASS] 0. Connect and seed sample files (0.53s) endpoint=https://s3.us-east-2.wasabisys.com [PASS] 1. S3DirectoryLoader reads docs from Wasabi (4.45s) loaded 5 documents [PASS] 2. Embedding cache stored in Wasabi (1.18s) namespace=ollama-nomic-embed-text- pass 1 embedded 5, pass 2 embedded 0, 5 objects in cache ``` ## Running Without langchain-community LangChain has announced that `langchain-community` is being sunset and is no longer actively maintained, so the S3DirectoryLoader import path may change or disappear. The second script, `test_langchain_wasabi_standalone.py`, does not use `langchain-community` or `unstructured`. It needs only three packages. ```bash pip install langchain-core langchain-classic boto3 ``` In place of S3DirectoryLoader, the script ([Appendix B](/v1/docs/langchain-with-wasabi#appendix-b-testlangchainwasabistandalonepy)) uses Boto3TextLoader, a short loader built on boto3 that follows LangChain's BaseLoader interface, so it returns normal LangChain documents. ```python from langchain_core.document_loaders import BaseLoader from langchain_core.documents import Document class Boto3TextLoader(BaseLoader):    """Fallback loader: reads every text object under a prefix with plain boto3.    Implements LangChain's BaseLoader interface, so it can be used anywhere a    LangChain loader is expected. Handles UTF-8 text files only (no PDF/Word).    """    def __init__(self, client, bucket, prefix=""):        self.client, self.bucket, self.prefix = client, bucket, prefix    def lazy_load(self):        paginator = self.client.get_paginator("list_objects_v2")        for page in paginator.paginate(Bucket=self.bucket, Prefix=self.prefix):            for obj in page.get("Contents", []):                key = obj["Key"]                if key.endswith("/"):                    continue                body = self.client.get_object(Bucket=self.bucket, Key=key)["Body"].read()                yield Document(                    page_content=body.decode("utf-8", errors="replace"),                    metadata={"source": f"s3://{self.bucket}/{key}"},                ) ``` This loader reads UTF-8 text files only. It doesn't read PDF or Word files. The script uses the same environment variables as the main script, and the embedding cache works the same way. For example: ```plaintext (lc-wasabi) user@server:~$ env -u WASABI_PREFIX python test_langchain_wasabi_standalone.py Embedding model: fake (deterministic) [PASS] 0. Connect and seed sample files (0.46s) endpoint=https://s3.us-east-2.wasabisys.com [PASS] 1. Boto3TextLoader reads docs from Wasabi (0.19s) loaded 5 documents [PASS] 2. Embedding cache stored in Wasabi (0.68s) namespace=fake-deterministic- pass 1 embedded 5, pass 2 embedded 0, 5 objects in cache Objects kept under s3://mt-langchain/langchain-test-standalone/1794462828/  docs:            langchain-test-standalone/1794462828/docs/  embedding cache: langchain-test-standalone/1794462828/embedding-cache/ ``` ## Verifying Data in Your Wasabi Bucket After a run, you can confirm the objects are in your bucket by browsing it in the Wasabi Console. 1. Log in to the [Wasabi Console](https://console.wasabisys.com). 2. Click **Buckets** in the left navigation. 3. Select the name of your bucket. ![](https://cdn.document360.io/bef0a1ea-7768-4d5a-b520-c4fe2f7fafad/Images/Documentation/2026-11-12_17-29-12(1).png) 4. Open the folder that matches your WASABI_PREFIX value (rag, in the examples above). It contains two subfolders: docs, which holds the five sample files, and embedding-cache, which holds one object for each embedded text. The object names in embedding-cache start with the model-specific namespace. ![](https://cdn.document360.io/bef0a1ea-7768-4d5a-b520-c4fe2f7fafad/Images/Documentation/2026-11-12_17-30-20.png) The embedding-cache folder after a run with the Ollama model. Each object name starts with the model-specific namespace, ollama-nomic-embed-text-. > The Current Size value in the bucket details updates once a day, so it can show 0 for a while after the first run. ## Cleaning Up By default, the scripts keep the objects they create. To delete a run's objects when it finishes, set CLEANUP=1. Use it with a prefix you set only for testing. > CLEANUP=1 deletes everything under the prefix. Never use it with a prefix that holds data you want to keep. The scripts delete a run's objects with a function that lists every object under the run's prefix and deletes them in batches. ```python def cleanup():    for page in s3.get_paginator("list_objects_v2").paginate(Bucket=BUCKET, Prefix=ROOT):        keys = [{"Key": o["Key"]} for o in page.get("Contents", [])]        if keys:            s3.delete_objects(Bucket=BUCKET, Delete={"Objects": keys}) if os.environ.get("CLEANUP") == "1":    cleanup()    print(f"\nCleaned up s3://{BUCKET}/{ROOT}") ``` ## Appendix A: test_langchain_wasabi.py Save this script as `test_langchain_wasabi.py`. It is the script used for the examples in this article. ```python #!/usr/bin/env python3 """ LangChain + Wasabi storage test. Scenarios  1. Load documents from a Wasabi bucket (S3DirectoryLoader)  2. Store cached embeddings in Wasabi (custom ByteStore + CacheBackedEmbeddings) By default no LLM or API key is needed: embeddings are deterministic fakes. Set EMBEDDING_PROVIDER to use a real embedding model (see below). If langchain-community is no longer available, use the companion script test_langchain_wasabi_standalone.py, which does not depend on it. Environment variables  WASABI_ACCESS_KEY   (required)  WASABI_SECRET_KEY   (required)  WASABI_BUCKET       (required, an existing test bucket)  WASABI_ENDPOINT_URL (required in practice, e.g. https://s3.us-east-1.wasabisys.com;                       if unset, it is built from WASABI_REGION)  WASABI_REGION       (optional, default us-east-1; used for request signing)  WASABI_PREFIX       (optional, a fixed location such as rag/ ; if unset, each run                       writes under langchain-test//)  CLEANUP=1           (optional, delete this run's objects when finished;                       by default everything is kept in the bucket)  EMBEDDING_PROVIDER  (optional: fake [default], openai, ollama, huggingface)  EMBEDDING_MODEL     (optional model name; sensible default per provider) Embedding providers need their own package (and key, where applicable):  openai       pip install langchain-openai        export OPENAI_API_KEY=...  ollama       pip install langchain-ollama        (Ollama running locally)  huggingface  pip install langchain-huggingface sentence-transformers With a fixed WASABI_PREFIX, repeat runs reuse the same embedding cache, which is what most real deployments do. Scenario 2 then reports a warm cache. """ import os # Hide the Unstructured promotional banner (must be set before it is imported) os.environ.setdefault("UNSTRUCTURED_DISABLE_NOTICE", "1") import re import sys import time import boto3 from botocore.config import Config from langchain_core.documents import Document from langchain_core.embeddings import DeterministicFakeEmbedding, Embeddings from langchain_core.stores import ByteStore try:    from langchain.embeddings import CacheBackedEmbeddings except ImportError:  # LangChain 1.x moved this to langchain-classic    from langchain_classic.embeddings import CacheBackedEmbeddings from langchain_community.document_loaders import S3DirectoryLoader ACCESS_KEY = os.environ["WASABI_ACCESS_KEY"] SECRET_KEY = os.environ["WASABI_SECRET_KEY"] BUCKET = os.environ["WASABI_BUCKET"] REGION = os.environ.get("WASABI_REGION", "us-east-1") ENDPOINT = os.environ.get("WASABI_ENDPOINT_URL") or f"https://s3.{REGION}.wasabisys.com" _prefix = os.environ.get("WASABI_PREFIX", "").strip("/") ROOT = f"{_prefix}/" if _prefix else f"langchain-test/{int(time.time())}/" DOCS_PREFIX = ROOT + "docs/" CACHE_PREFIX = ROOT + "embedding-cache/" s3 = boto3.client(    "s3",    endpoint_url=ENDPOINT,    region_name=REGION,    aws_access_key_id=ACCESS_KEY,    aws_secret_access_key=SECRET_KEY,    config=Config(retries={"max_attempts": 3, "mode": "standard"}), ) SAMPLE_DOCS = {    "wasabi-overview.txt": "Wasabi is hot cloud object storage with an S3-compatible API.",    "langchain-overview.txt": "LangChain is a framework for building applications around language models.",    "kb-article.txt": "A knowledge base article explains how to configure a product step by step.",    "backup.txt": "Backups should be stored in a separate region and tested with periodic restores.",    "retention.txt": "Object lock and retention policies protect data from accidental deletion.", } results = [] def record(name, ok, seconds, detail=""):    results.append((name, ok, seconds, detail))    print(f"[{'PASS' if ok else 'FAIL'}] {name} ({seconds:.2f}s) {detail}") # ---------------------------------------------------------------- Scenario 2 helper class WasabiByteStore(ByteStore):    """Minimal ByteStore that keeps each value as one object in a Wasabi bucket."""    def __init__(self, client, bucket, prefix):        self.client, self.bucket, self.prefix = client, bucket, prefix    def mget(self, keys):        out = []        for k in keys:            try:                obj = self.client.get_object(Bucket=self.bucket, Key=self.prefix + k)                out.append(obj["Body"].read())            except self.client.exceptions.NoSuchKey:                out.append(None)        return out    def mset(self, key_value_pairs):        for k, v in key_value_pairs:            self.client.put_object(Bucket=self.bucket, Key=self.prefix + k, Body=v)    def mdelete(self, keys):        for k in keys:            self.client.delete_object(Bucket=self.bucket, Key=self.prefix + k)    def yield_keys(self, *, prefix=None):        full = self.prefix + (prefix or "")        for page in self.client.get_paginator("list_objects_v2").paginate(            Bucket=self.bucket, Prefix=full        ):            for item in page.get("Contents", []):                yield item["Key"][len(self.prefix):] def get_base_embeddings():    """Return the embedding model selected by EMBEDDING_PROVIDER."""    provider = os.environ.get("EMBEDDING_PROVIDER", "fake").lower()    model = os.environ.get("EMBEDDING_MODEL")    if provider == "fake":        return DeterministicFakeEmbedding(size=256), "fake (deterministic)"    # provider -> (module, class, pip command, default model, constructor argument)    providers = {        "openai": ("langchain_openai", "OpenAIEmbeddings",                   "pip install langchain-openai (and export OPENAI_API_KEY)",                   "text-embedding-3-small", "model"),        "ollama": ("langchain_ollama", "OllamaEmbeddings",                   "pip install langchain-ollama (and have Ollama running)",                   "nomic-embed-text", "model"),        "huggingface": ("langchain_huggingface", "HuggingFaceEmbeddings",                        "pip install langchain-huggingface sentence-transformers",                        "sentence-transformers/all-MiniLM-L6-v2", "model_name"),    }    if provider not in providers:        raise SystemExit(            f"Unknown EMBEDDING_PROVIDER '{provider}'. "            f"Use one of: fake, {', '.join(providers)}."        )    module, cls_name, pip_cmd, default_model, arg = providers[provider]    try:        cls = getattr(__import__(module, fromlist=[cls_name]), cls_name)    except ImportError:        raise SystemExit(            f"EMBEDDING_PROVIDER is set to '{provider}', but its package is not "            f"installed.\n  Install it with: {pip_cmd}\n"            f"  Or run with the default fake embeddings: unset EMBEDDING_PROVIDER"        )    model = model or default_model    return cls(**{arg: model}), f"{provider}:{model}" def cache_namespace(model_name):    """Cache keys must be specific to the embedding model.    Without this, switching models while reusing a prefix would silently return    the old model's vectors from the cache.    """    return re.sub(r"[^A-Za-z0-9._-]+", "-", model_name).strip("-") + "-" class CountingEmbeddings(Embeddings):    """Wraps any embedding model and counts how many texts it actually embeds."""    def __init__(self, base):        self.base, self.count = base, 0    def embed_documents(self, texts):        self.count += len(texts)        return self.base.embed_documents(texts)    def embed_query(self, text):        return self.base.embed_query(text) def cleanup():    for page in s3.get_paginator("list_objects_v2").paginate(Bucket=BUCKET, Prefix=ROOT):        keys = [{"Key": o["Key"]} for o in page.get("Contents", [])]        if keys:            s3.delete_objects(Bucket=BUCKET, Delete={"Objects": keys}) def main():    # ---- Embedding model (fake by default; checked first so a bad setting fails before any upload)    emb, emb_name = get_base_embeddings()    print(f"Embedding model: {emb_name}")    # ---- Step 0: connectivity and seed data    t = time.time()    try:        s3.head_bucket(Bucket=BUCKET)        for name, text in SAMPLE_DOCS.items():            s3.put_object(Bucket=BUCKET, Key=DOCS_PREFIX + name, Body=text.encode())        record("0. Connect and seed sample files", True, time.time() - t,               f"endpoint={ENDPOINT}")    except Exception as e:        record("0. Connect and seed sample files", False, time.time() - t, repr(e))        sys.exit(1)    # ---- Scenario 1: load documents from Wasabi    docs = [Document(page_content=v, metadata={"source": k}) for k, v in SAMPLE_DOCS.items()]    t = time.time()    try:        loader = S3DirectoryLoader(            BUCKET,            prefix=DOCS_PREFIX,            endpoint_url=ENDPOINT,            region_name=REGION,            aws_access_key_id=ACCESS_KEY,            aws_secret_access_key=SECRET_KEY,        )        loaded = loader.load()        ok = len(loaded) >= len(SAMPLE_DOCS)        record("1. S3DirectoryLoader reads docs from Wasabi", ok, time.time() - t,               f"loaded {len(loaded)} documents")        if ok:            docs = loaded    except Exception as e:        record("1. S3DirectoryLoader reads docs from Wasabi", False, time.time() - t,               f"{e!r} (S3 loaders need the 'unstructured' package; see setup notes)")    # ---- Scenario 2: embedding cache stored in Wasabi    t = time.time()    try:        base = CountingEmbeddings(emb)        byte_store = WasabiByteStore(s3, BUCKET, CACHE_PREFIX)        cached = CacheBackedEmbeddings.from_bytes_store(            base, byte_store, namespace=cache_namespace(emb_name), key_encoder="sha256"        )        texts = list(SAMPLE_DOCS.values())        cached.embed_documents(texts)        first_calls = base.count        stored = len(list(byte_store.yield_keys(prefix=cache_namespace(emb_name))))        base.count = 0        cached.embed_documents(texts)  # should be served from Wasabi        second_calls = base.count        # First run embeds everything; with a fixed prefix a later run finds it warm.        warm = first_calls == 0        ok = (second_calls == 0 and stored >= len(texts)              and first_calls in (0, len(texts)))        record("2. Embedding cache stored in Wasabi", ok, time.time() - t,               f"namespace={cache_namespace(emb_name)} "               f"{'(cache already warm); ' if warm else ''}"               f"pass 1 embedded {first_calls}, pass 2 embedded {second_calls}, "               f"{stored} objects in cache")    except Exception as e:        record("2. Embedding cache stored in Wasabi", False, time.time() - t, repr(e))    # ---- Cleanup and summary    if os.environ.get("CLEANUP") == "1":        cleanup()        print(f"\nCleaned up s3://{BUCKET}/{ROOT}")    else:        print(f"\nObjects kept under s3://{BUCKET}/{ROOT}")        print(f"  docs:            {DOCS_PREFIX}")        print(f"  embedding cache: {CACHE_PREFIX}")    print("\nSummary")    for name, ok, secs, _ in results:        print(f"  {'PASS' if ok else 'FAIL'}  {name}  {secs:.2f}s")    sys.exit(0 if all(r[1] for r in results) else 1) if __name__ == "__main__":    main() ``` ## Appendix B: test_langchain_wasabi_standalone.py Save this script as `test_langchain_wasabi_standalone.py`. It does not use `langchain-community` or `unstructured`. ```python #!/usr/bin/env python3 """ LangChain + Wasabi storage test, standalone edition (no langchain-community). Use this if langchain-community (and its S3 loaders) is no longer available. It needs only langchain-core, langchain-classic and boto3. No 'unstructured' package is involved. Scenarios  1. Load text documents from a Wasabi bucket (small boto3-based LangChain loader)  2. Store cached embeddings in Wasabi (custom ByteStore + CacheBackedEmbeddings) Limits: scenario 1 reads UTF-8 text files only (no PDF or Word). By default no LLM or API key is needed: embeddings are deterministic fakes. Install  pip install langchain-core langchain-classic boto3  (plus a provider package if you set EMBEDDING_PROVIDER, see below) Environment variables  WASABI_ACCESS_KEY   (required)  WASABI_SECRET_KEY   (required)  WASABI_BUCKET       (required, an existing test bucket)  WASABI_ENDPOINT_URL (required in practice, e.g. https://s3.us-east-1.wasabisys.com;                       if unset, it is built from WASABI_REGION)  WASABI_REGION       (optional, default us-east-1; used for request signing)  WASABI_PREFIX       (optional, a fixed location such as rag/ ; if unset, each run                       writes under langchain-test-standalone//)  CLEANUP=1           (optional, delete this run's objects when finished;                       by default everything is kept in the bucket)  EMBEDDING_PROVIDER  (optional: fake [default], openai, ollama, huggingface)  EMBEDDING_MODEL     (optional model name; sensible default per provider) Embedding providers need their own package (and key, where applicable):  openai       pip install langchain-openai        export OPENAI_API_KEY=...  ollama       pip install langchain-ollama        (Ollama running locally)  huggingface  pip install langchain-huggingface sentence-transformers """ import os import re import sys import time import boto3 from botocore.config import Config from langchain_core.document_loaders import BaseLoader from langchain_core.documents import Document from langchain_core.embeddings import DeterministicFakeEmbedding, Embeddings from langchain_core.stores import ByteStore try:    from langchain.embeddings import CacheBackedEmbeddings except ImportError:  # LangChain 1.x moved this to langchain-classic    from langchain_classic.embeddings import CacheBackedEmbeddings ACCESS_KEY = os.environ["WASABI_ACCESS_KEY"] SECRET_KEY = os.environ["WASABI_SECRET_KEY"] BUCKET = os.environ["WASABI_BUCKET"] REGION = os.environ.get("WASABI_REGION", "us-east-1") ENDPOINT = os.environ.get("WASABI_ENDPOINT_URL") or f"https://s3.{REGION}.wasabisys.com" _prefix = os.environ.get("WASABI_PREFIX", "").strip("/") ROOT = f"{_prefix}/" if _prefix else f"langchain-test-standalone/{int(time.time())}/" DOCS_PREFIX = ROOT + "docs/" CACHE_PREFIX = ROOT + "embedding-cache/" s3 = boto3.client(    "s3",    endpoint_url=ENDPOINT,    region_name=REGION,    aws_access_key_id=ACCESS_KEY,    aws_secret_access_key=SECRET_KEY,    config=Config(retries={"max_attempts": 3, "mode": "standard"}), ) SAMPLE_DOCS = {    "wasabi-overview.txt": "Wasabi is hot cloud object storage with an S3-compatible API.",    "langchain-overview.txt": "LangChain is a framework for building applications around language models.",    "kb-article.txt": "A knowledge base article explains how to configure a product step by step.",    "backup.txt": "Backups should be stored in a separate region and tested with periodic restores.",    "retention.txt": "Object lock and retention policies protect data from accidental deletion.", } results = [] def record(name, ok, seconds, detail=""):    results.append((name, ok, seconds, detail))    print(f"[{'PASS' if ok else 'FAIL'}] {name} ({seconds:.2f}s) {detail}") # ---------------------------------------------------------------- Scenario 2 helper class WasabiByteStore(ByteStore):    """Minimal ByteStore that keeps each value as one object in a Wasabi bucket."""    def __init__(self, client, bucket, prefix):        self.client, self.bucket, self.prefix = client, bucket, prefix    def mget(self, keys):        out = []        for k in keys:            try:                obj = self.client.get_object(Bucket=self.bucket, Key=self.prefix + k)                out.append(obj["Body"].read())            except self.client.exceptions.NoSuchKey:                out.append(None)        return out    def mset(self, key_value_pairs):        for k, v in key_value_pairs:            self.client.put_object(Bucket=self.bucket, Key=self.prefix + k, Body=v)    def mdelete(self, keys):        for k in keys:            self.client.delete_object(Bucket=self.bucket, Key=self.prefix + k)    def yield_keys(self, *, prefix=None):        full = self.prefix + (prefix or "")        for page in self.client.get_paginator("list_objects_v2").paginate(            Bucket=self.bucket, Prefix=full        ):            for item in page.get("Contents", []):                yield item["Key"][len(self.prefix):] class Boto3TextLoader(BaseLoader):    """Fallback loader: reads every text object under a prefix with plain boto3.    Implements LangChain's BaseLoader interface, so it can be used anywhere a    LangChain loader is expected. Handles UTF-8 text files only (no PDF/Word).    """    def __init__(self, client, bucket, prefix=""):        self.client, self.bucket, self.prefix = client, bucket, prefix    def lazy_load(self):        paginator = self.client.get_paginator("list_objects_v2")        for page in paginator.paginate(Bucket=self.bucket, Prefix=self.prefix):            for obj in page.get("Contents", []):                key = obj["Key"]                if key.endswith("/"):                    continue                body = self.client.get_object(Bucket=self.bucket, Key=key)["Body"].read()                yield Document(                    page_content=body.decode("utf-8", errors="replace"),                    metadata={"source": f"s3://{self.bucket}/{key}"},                ) def get_base_embeddings():    """Return the embedding model selected by EMBEDDING_PROVIDER."""    provider = os.environ.get("EMBEDDING_PROVIDER", "fake").lower()    model = os.environ.get("EMBEDDING_MODEL")    if provider == "fake":        return DeterministicFakeEmbedding(size=256), "fake (deterministic)"    # provider -> (module, class, pip command, default model, constructor argument)    providers = {        "openai": ("langchain_openai", "OpenAIEmbeddings",                   "pip install langchain-openai (and export OPENAI_API_KEY)",                   "text-embedding-3-small", "model"),        "ollama": ("langchain_ollama", "OllamaEmbeddings",                   "pip install langchain-ollama (and have Ollama running)",                   "nomic-embed-text", "model"),        "huggingface": ("langchain_huggingface", "HuggingFaceEmbeddings",                        "pip install langchain-huggingface sentence-transformers",                        "sentence-transformers/all-MiniLM-L6-v2", "model_name"),    }    if provider not in providers:        raise SystemExit(            f"Unknown EMBEDDING_PROVIDER '{provider}'. "            f"Use one of: fake, {', '.join(providers)}."        )    module, cls_name, pip_cmd, default_model, arg = providers[provider]    try:        cls = getattr(__import__(module, fromlist=[cls_name]), cls_name)    except ImportError:        raise SystemExit(            f"EMBEDDING_PROVIDER is set to '{provider}', but its package is not "            f"installed.\n  Install it with: {pip_cmd}\n"            f"  Or run with the default fake embeddings: unset EMBEDDING_PROVIDER"        )    model = model or default_model    return cls(**{arg: model}), f"{provider}:{model}" def cache_namespace(model_name):    """Cache keys must be specific to the embedding model.    Without this, switching models while reusing a prefix would silently return    the old model's vectors from the cache.    """    return re.sub(r"[^A-Za-z0-9._-]+", "-", model_name).strip("-") + "-" class CountingEmbeddings(Embeddings):    """Wraps any embedding model and counts how many texts it actually embeds."""    def __init__(self, base):        self.base, self.count = base, 0    def embed_documents(self, texts):        self.count += len(texts)        return self.base.embed_documents(texts)    def embed_query(self, text):        return self.base.embed_query(text) def cleanup():    for page in s3.get_paginator("list_objects_v2").paginate(Bucket=BUCKET, Prefix=ROOT):        keys = [{"Key": o["Key"]} for o in page.get("Contents", [])]        if keys:            s3.delete_objects(Bucket=BUCKET, Delete={"Objects": keys}) def main():    # ---- Embedding model (fake by default; checked first so a bad setting fails before any upload)    emb, emb_name = get_base_embeddings()    print(f"Embedding model: {emb_name}")    # ---- Step 0: connectivity and seed data    t = time.time()    try:        s3.head_bucket(Bucket=BUCKET)        for name, text in SAMPLE_DOCS.items():            s3.put_object(Bucket=BUCKET, Key=DOCS_PREFIX + name, Body=text.encode())        record("0. Connect and seed sample files", True, time.time() - t,               f"endpoint={ENDPOINT}")    except Exception as e:        record("0. Connect and seed sample files", False, time.time() - t, repr(e))        sys.exit(1)    # ---- Scenario 1: load documents with the boto3-based loader    docs = [Document(page_content=v, metadata={"source": k}) for k, v in SAMPLE_DOCS.items()]    t = time.time()    try:        loaded = Boto3TextLoader(s3, BUCKET, DOCS_PREFIX).load()        ok = len(loaded) >= len(SAMPLE_DOCS)        record("1. Boto3TextLoader reads docs from Wasabi", ok, time.time() - t,               f"loaded {len(loaded)} documents")        if ok:            docs = loaded    except Exception as e:        record("1. Boto3TextLoader reads docs from Wasabi", False, time.time() - t, repr(e))    # ---- Scenario 2: embedding cache stored in Wasabi    t = time.time()    try:        base = CountingEmbeddings(emb)        byte_store = WasabiByteStore(s3, BUCKET, CACHE_PREFIX)        cached = CacheBackedEmbeddings.from_bytes_store(            base, byte_store, namespace=cache_namespace(emb_name), key_encoder="sha256"        )        texts = list(SAMPLE_DOCS.values())        cached.embed_documents(texts)        first_calls = base.count        stored = len(list(byte_store.yield_keys(prefix=cache_namespace(emb_name))))        base.count = 0        cached.embed_documents(texts)  # should be served from Wasabi        second_calls = base.count        # First run embeds everything; with a fixed prefix a later run finds it warm.        warm = first_calls == 0        ok = (second_calls == 0 and stored >= len(texts)              and first_calls in (0, len(texts)))        record("2. Embedding cache stored in Wasabi", ok, time.time() - t,               f"namespace={cache_namespace(emb_name)} "               f"{'(cache already warm); ' if warm else ''}"               f"pass 1 embedded {first_calls}, pass 2 embedded {second_calls}, "               f"{stored} objects in cache")    except Exception as e:        record("2. Embedding cache stored in Wasabi", False, time.time() - t, repr(e))    # ---- Cleanup and summary    if os.environ.get("CLEANUP") == "1":        cleanup()        print(f"\nCleaned up s3://{BUCKET}/{ROOT}")    else:        print(f"\nObjects kept under s3://{BUCKET}/{ROOT}")        print(f"  docs:            {DOCS_PREFIX}")        print(f"  embedding cache: {CACHE_PREFIX}")    print("\nSummary")    for name, ok, secs, _ in results:        print(f"  {'PASS' if ok else 'FAIL'}  {name}  {secs:.2f}s")    sys.exit(0 if all(r[1] for r in results) else 1) if __name__ == "__main__":    main() ```