forked from langchain-ai/langchainjs
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Initial implementation of a Google Cloud Storage (GCS) data store.
- Loading branch information
1 parent
0f38158
commit 58d4950
Showing
2 changed files
with
72 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
import { Storage, File } from "@google-cloud/storage"; | ||
|
||
import { Document } from "../document.js"; | ||
import { Docstore } from "./base.js"; | ||
|
||
export interface GoogleCloudStorageDocstoreConfiguration { | ||
/** The identifier for the GCS bucket */ | ||
bucket: string; | ||
|
||
/** | ||
* An optional prefix to prepend to each object name. | ||
* Often used to create a pseudo-hierarchy. | ||
*/ | ||
prefix?: string; | ||
} | ||
|
||
export class GoogleCloudStorageDocstore extends Docstore { | ||
bucket: string; | ||
|
||
prefix = ""; | ||
|
||
storage: Storage; | ||
|
||
constructor(config: GoogleCloudStorageDocstoreConfiguration) { | ||
super(); | ||
|
||
this.bucket = config.bucket; | ||
this.prefix = config.prefix ?? this.prefix; | ||
|
||
this.storage = new Storage(); | ||
} | ||
|
||
async search(search: string): Promise<Document> { | ||
const file = this.getFile(search); | ||
|
||
const [fileMetadata] = await file.getMetadata(); | ||
const metadata = fileMetadata?.metadata; | ||
|
||
const [dataBuffer] = await file.download(); | ||
const pageContent = dataBuffer.toString(); | ||
|
||
const ret = new Document({ | ||
pageContent, | ||
metadata, | ||
}); | ||
|
||
return ret; | ||
} | ||
|
||
async add(texts: Record<string, Document>): Promise<void> { | ||
await Promise.all( | ||
Object.keys(texts).map((key) => this.addDocument(key, texts[key])) | ||
); | ||
} | ||
|
||
async addDocument(name: string, document: Document): Promise<void> { | ||
const file = this.getFile(name); | ||
await file.save(document.pageContent); | ||
await file.setMetadata(document.metadata); | ||
} | ||
|
||
private getFile(name: string): File { | ||
const filename = this.prefix + name; | ||
const file = this.storage.bucket(this.bucket).file(filename); | ||
return file; | ||
} | ||
} |