Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix error when storing embeddings in localStorage #96

Merged
merged 4 commits into from
Nov 5, 2024

Conversation

Royal-lobster
Copy link
Owner

@Royal-lobster Royal-lobster commented Nov 5, 2024

Fixes #95

Update getContextVectorStore to use IndexedDB instead of localStorage for storing embeddings.

  • src/lib/getMatchedContent.ts

    • Import getFromIndexedDB and saveToIndexedDB from useStorage.ts.
    • Replace localStorage usage with IndexedDB functions for storing and retrieving embeddings.
  • src/hooks/useStorage.ts

    • Add saveToIndexedDB function to save data to IndexedDB.
    • Add getFromIndexedDB function to retrieve data from IndexedDB.

For more details, open the Copilot Workspace session.

Summary by CodeRabbit

  • New Features
    • Introduced asynchronous functions for data storage and retrieval using IndexedDB, enhancing data management capabilities.
  • Improvements
    • Updated the storage mechanism for vector data from local storage to IndexedDB, allowing for better handling of larger datasets.
  • Bug Fixes
    • Resolved an error related to storing embeddings in local storage, ensuring successful data storage.

Fixes #95

Update `getContextVectorStore` to use `IndexedDB` instead of `localStorage` for storing embeddings.

* **src/lib/getMatchedContent.ts**
  - Import `getFromIndexedDB` and `saveToIndexedDB` from `useStorage.ts`.
  - Replace `localStorage` usage with `IndexedDB` functions for storing and retrieving embeddings.

* **src/hooks/useStorage.ts**
  - Add `saveToIndexedDB` function to save data to `IndexedDB`.
  - Add `getFromIndexedDB` function to retrieve data from `IndexedDB`.

---

For more details, open the [Copilot Workspace session](https://copilot-workspace.githubnext.com/Royal-lobster/Syncia/issues/95?shareId=XXXX-XXXX-XXXX-XXXX).
Copy link

stackblitz bot commented Nov 5, 2024

Review PR in StackBlitz Codeflow Run & review this pull request in StackBlitz Codeflow.

Copy link

changeset-bot bot commented Nov 5, 2024

🦋 Changeset detected

Latest commit: e3e1e87

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
syncia Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link
Contributor

coderabbitai bot commented Nov 5, 2024

Warning

Rate limit exceeded

@Royal-lobster has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 7 minutes and 24 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between de5a74c and e3e1e87.

Walkthrough

The changes introduce two asynchronous functions, saveToIndexedDB and getFromIndexedDB, in the src/hooks/useStorage.ts file for managing data storage and retrieval using IndexedDB. These functions replace the previous local storage mechanism in the getMatchedContent.ts file, which now utilizes the new functions for caching and retrieving vector store data. The modifications enhance the application's ability to handle larger datasets more effectively by leveraging IndexedDB.

Changes

File Change Summary
src/hooks/useStorage.ts Added functions: saveToIndexedDB(key, data) and getFromIndexedDB(key) for IndexedDB operations.
src/lib/getMatchedContent.ts Updated to use getFromIndexedDB and saveToIndexedDB instead of local storage for vector store caching.
.changeset/tasty-ravens-tickle.md Addressed an error related to storing embeddings in localStorage, ensuring successful storage.

Assessment against linked issues

Objective Addressed Explanation
Address the issue of exceeding local storage quota (#95)

Poem

In a burrow deep, where data flows,
IndexedDB now stores what we chose.
No more quota woes, just smooth, swift saves,
In Syncia's realm, our memory braves.
Hopping through bytes, with joy we cheer,
For every new function brings us near! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (4)
src/lib/getMatchedContent.ts (2)

Line range hint 11-20: Consider adding error handling for storage operations.

Since the function now depends on IndexedDB operations which can fail (e.g., quota exceeded, browser compatibility issues), consider implementing error handling to gracefully handle storage failures.

 export const getMatchedContent = async (
   query: string,
   context: string,
   apiKey: string,
   baseURL: string,
 ) => {
+  try {
     const vectorStore = await getContextVectorStore(context, apiKey, baseURL)
     const retriever = vectorStore.asRetriever()
     const relevantDocs = await retriever.getRelevantDocuments(query)
     return relevantDocs.map((doc) => doc.pageContent).join('\n')
+  } catch (error) {
+    console.error('Failed to process content:', error)
+    throw new Error('Failed to process content. Please try again.')
+  }
 }

Line range hint 23-54: Consider implementing a cache expiration strategy.

Since IndexedDB has higher storage limits than localStorage, consider implementing a cache expiration strategy to prevent unlimited growth over time. This could include:

  1. Timestamp-based expiration
  2. Size-based cleanup
  3. LRU (Least Recently Used) eviction policy

Would you like me to provide an implementation example for any of these strategies?

src/hooks/useStorage.ts (2)

111-139: Consider implementing database version management and data cleanup.

The current implementation lacks:

  1. A strategy for database version management
  2. Cleanup of old/unused embeddings

Consider:

  1. Implementing a version management system to handle schema changes
  2. Adding a cleanup mechanism to prevent unlimited storage growth
  3. Moving database configuration to a separate module

Example configuration module:

// db-config.ts
export const DB_CONFIG = {
  name: 'SynciaDB',
  version: 1,
  stores: {
    embeddings: 'embeddings'
  }
} as const;

export interface DBSchema {
  embeddings: {
    key: string;
    value: unknown;
    timestamp: number;
  };
}

111-172: Refactor database operations into a reusable service.

The current implementation has duplicate code and could benefit from a more structured approach.

Consider creating a database service class:

class IndexedDBService {
  private readonly dbName = 'SynciaDB';
  private readonly version = 1;
  private readonly storeName = 'embeddings';
  private db: IDBDatabase | null = null;

  private async getConnection(): Promise<IDBDatabase> {
    if (this.db) return this.db;
    
    return new Promise((resolve, reject) => {
      const request = indexedDB.open(this.dbName, this.version);
      
      request.onupgradeneeded = (event) => {
        const db = (event.target as IDBOpenDBRequest).result;
        if (!db.objectStoreNames.contains(this.storeName)) {
          db.createObjectStore(this.storeName);
        }
      };
      
      request.onsuccess = () => {
        this.db = request.result;
        resolve(request.result);
      };
      
      request.onerror = () => reject(request.error);
    });
  }

  async save<T>(key: string, data: T): Promise<void> {
    const db = await this.getConnection();
    const transaction = db.transaction(this.storeName, 'readwrite');
    const store = transaction.objectStore(this.storeName);
    
    return new Promise((resolve, reject) => {
      const request = store.put(data, key);
      request.onsuccess = () => resolve();
      request.onerror = () => reject(request.error);
    });
  }

  async get<T>(key: string): Promise<T | null> {
    const db = await this.getConnection();
    const transaction = db.transaction(this.storeName, 'readonly');
    const store = transaction.objectStore(this.storeName);
    
    return new Promise((resolve, reject) => {
      const request = store.get(key);
      request.onsuccess = () => resolve(request.result ?? null);
      request.onerror = () => reject(request.error);
    });
  }

  close(): void {
    if (this.db) {
      this.db.close();
      this.db = null;
    }
  }
}

const dbService = new IndexedDBService();

export const saveToIndexedDB = <T>(key: string, data: T) => 
  dbService.save(key, data);

export const getFromIndexedDB = <T>(key: string) => 
  dbService.get<T>(key);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f0a0a71 and 7378631.

📒 Files selected for processing (2)
  • src/hooks/useStorage.ts (1 hunks)
  • src/lib/getMatchedContent.ts (3 hunks)
🔇 Additional comments (2)
src/lib/getMatchedContent.ts (1)

5-5: LGTM: Clean import of storage utilities.

The import statement correctly brings in the new IndexedDB utility functions.

src/hooks/useStorage.ts (1)

111-172: Verify the impact of IndexedDB migration.

The transition from localStorage to IndexedDB might affect existing users.

Let's verify the migration impact:

src/lib/getMatchedContent.ts Outdated Show resolved Hide resolved
src/lib/getMatchedContent.ts Outdated Show resolved Hide resolved
src/hooks/useStorage.ts Outdated Show resolved Hide resolved
src/hooks/useStorage.ts Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7378631 and de5a74c.

📒 Files selected for processing (1)
  • .changeset/tasty-ravens-tickle.md (1 hunks)

.changeset/tasty-ravens-tickle.md Outdated Show resolved Hide resolved
Royal-lobster and others added 2 commits November 5, 2024 10:51
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@Royal-lobster Royal-lobster merged commit 073d961 into main Nov 5, 2024
3 checks passed
@Royal-lobster Royal-lobster deleted the fix-embeddings-error branch November 5, 2024 05:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Development

Successfully merging this pull request may close these issues.

Error trying to do the embeddings
1 participant