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

Migrated get_embeddings from litellm service to kairon #1844

Conversation

himanshugt16
Copy link
Contributor

@himanshugt16 himanshugt16 commented Mar 6, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced text processing with automatic input truncation to maintain optimal embedding performance.
    • Introduced support for multiple embedding models to improve query accuracy and overall response quality.
    • Added new methods for generating sparse and rerank embeddings.
    • Integrated loading of embedding models during module initialization for improved performance.
  • Tests

    • Refined and expanded tests to verify reliable behavior for both single and multiple text queries.
    • Improved error handling validation to ensure robust performance in varied operational scenarios.
    • Added tests for new embedding retrieval methods and their error handling.
    • Enhanced test coverage for external requests to relevant Hugging Face URLs.
  • Chores

    • Updated dependencies to include fastembed and re-added nltk.

Copy link

coderabbitai bot commented Mar 6, 2025

Walkthrough

This pull request introduces new methods in the LLMProcessor class for loading sparse and rerank embedding models, truncating text inputs, and refining the embedding retrieval process. The get_embedding method has been updated to effectively handle both single and multiple text inputs. Additionally, test cases have been refactored to adopt a collection-based query approach, with updates in method names, mock setups, and error handling.

Changes

File Change Summary
kairon/shared/llm/processor.py - Added methods: truncate_text, load_sparse_embedding_model, load_rerank_embedding_model, get_sparse_embedding, get_rerank_embedding.
- Updated get_embedding for text handling and error management.
tests/unit_test/llm_test.py - Refactored test cases: renamed methods (e.g., test_get_embedding_success_single_texttest_collection_hybrid_query_success).
- Updated mocks to use mock_request.
- Added tests for sparse and rerank embeddings, including various scenarios.
requirements/prod.txt - Added package: fastembed==0.5.1.
- Re-added package: nltk.
kairon/actions/definitions/prompt.py - Invoked load_sparse_embedding_model() and load_rerank_embedding_model() at the module level.
kairon/shared/cognition/processor.py - Added calls to load_sparse_embedding_model() and load_rerank_embedding_model() in upsert_data method.
kairon/shared/vector_embeddings/db/qdrant.py - Added import for LLMProcessor and invoked model loading methods at the module level.
kairon/train.py - Invoked load_sparse_embedding_model() and load_rerank_embedding_model() at the module level.
tests/integration_test/action_service_test.py - Added responses.add_passthru for specific URLs in various test functions to enhance test coverage.

Possibly related PRs

Suggested reviewers

  • sfahad1414

Poem

I'm a little rabbit coding with delight,
Hopping through changes from morning to night.
New embeddings are loaded, text trimmed just right,
Tests hop along, making everything bright.
Celebrate the code—hop on, take flight! 🐰

Happy hops in every byte!

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 generate docstrings to generate docstrings for this 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

@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: 0

🧹 Nitpick comments (5)
kairon/shared/llm/processor.py (3)

188-189: Preserve original traceback when re-raising exceptions.
Use raise Exception(...) from e to keep context of the original error:

-        except Exception as e:
-            raise Exception(f"Failed to fetch embeddings: {str(e)}")
+        except Exception as e:
+            raise Exception(f"Failed to fetch embeddings: {str(e)}") from e
🧰 Tools
🪛 Ruff (0.8.2)

189-189: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


532-532: Preserve original traceback for sparse embedding errors.
Use raise ... from e when re-raising:

-        except Exception as e:
-            raise Exception(f"Error processing sparse embeddings: {str(e)}")
+        except Exception as e:
+            raise Exception(f"Error processing sparse embeddings: {str(e)}") from e
🧰 Tools
🪛 Ruff (0.8.2)

532-532: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


548-548: Preserve original traceback for rerank embedding errors.
Use raise ... from e when re-raising:

-        except Exception as e:
-            raise Exception(f"Error processing rerank embeddings: {str(e)}")
+        except Exception as e:
+            raise Exception(f"Error processing rerank embeddings: {str(e)}") from e
🧰 Tools
🪛 Ruff (0.8.2)

548-548: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

tests/unit_test/llm_test.py (2)

21-22: Remove unused imports.
BotSecretType and BotSecrets are imported but never used. Consider dropping them to maintain a tidy import list.

-from kairon.shared.admin.constants import BotSecretType
-from kairon.shared.admin.data_objects import BotSecrets
🧰 Tools
🪛 Ruff (0.8.2)

21-21: kairon.shared.admin.constants.BotSecretType imported but unused

Remove unused import: kairon.shared.admin.constants.BotSecretType

(F401)


22-22: kairon.shared.admin.data_objects.BotSecrets imported but unused

Remove unused import: kairon.shared.admin.data_objects.BotSecrets

(F401)


2650-2650: Remove assignments to the unused processor variable.
Following static analysis recommendations, remove these unused assignments:

-    processor = LLMProcessor(bot="test_bot", llm_type="openai")
...
-    processor = LLMProcessor(bot="test_bot", llm_type="openai")
...
-    processor = LLMProcessor(bot="test_bot", llm_type="openai")
...
-    processor = LLMProcessor(bot="test_bot", llm_type="openai")
...
-    processor = LLMProcessor(bot="test_bot", llm_type="openai")
...
-    processor = LLMProcessor(bot="test_bot", llm_type="openai")

Also applies to: 2681-2681, 2713-2713, 2746-2746, 2777-2777, 2809-2809

🧰 Tools
🪛 Ruff (0.8.2)

2650-2650: Local variable processor is assigned to but never used

Remove assignment to unused variable processor

(F841)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9b54712 and aa0ce77.

📒 Files selected for processing (2)
  • kairon/shared/llm/processor.py (4 hunks)
  • tests/unit_test/llm_test.py (10 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
kairon/shared/llm/processor.py

189-189: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


532-532: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


548-548: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

tests/unit_test/llm_test.py

21-21: kairon.shared.admin.constants.BotSecretType imported but unused

Remove unused import: kairon.shared.admin.constants.BotSecretType

(F401)


22-22: kairon.shared.admin.data_objects.BotSecrets imported but unused

Remove unused import: kairon.shared.admin.data_objects.BotSecrets

(F401)


2650-2650: Local variable processor is assigned to but never used

Remove assignment to unused variable processor

(F841)


2681-2681: Local variable processor is assigned to but never used

Remove assignment to unused variable processor

(F841)


2713-2713: Local variable processor is assigned to but never used

Remove assignment to unused variable processor

(F841)


2746-2746: Local variable processor is assigned to but never used

Remove assignment to unused variable processor

(F841)


2777-2777: Local variable processor is assigned to but never used

Remove assignment to unused variable processor

(F841)


2809-2809: Local variable processor is assigned to but never used

Remove assignment to unused variable processor

(F841)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Analyze (python)
  • GitHub Check: Python CI
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (4)
kairon/shared/llm/processor.py (4)

57-58: Initialize embeddings at construction.
These calls to self.load_sparse_embedding_model() and self.load_rerank_embedding_model() ensure that the embeddings are available as soon as the LLMProcessor is instantiated. This is a good design choice for on-demand functionality.


148-159: Token truncation logic looks good.
The truncate_text method correctly slices the token list to EMBEDDING_CTX_LENGTH and re-derives the string. This helps avoid oversize embeddings.


490-491: Surface error messages to guide troubleshooting.
Raising a descriptive exception here is appropriate to help diagnose configuration failures. No further change required.


492-513: Sparse and Re-rank embedding model loading.
These methods implement a robust fallback for caching directories. The design ensures a single initialization. This is a sensible approach.

Copy link

@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: 0

🧹 Nitpick comments (1)
requirements/prod.txt (1)

72-72: Consider pinning the 'nltk' dependency version.
The re-included nltk dependency is currently unversioned. For consistency across environments and to avoid potential compatibility issues with future releases, it is advisable to specify a tested version (e.g., nltk==3.8.0).

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between aa0ce77 and 1207fc8.

📒 Files selected for processing (1)
  • requirements/prod.txt (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Python CI
  • GitHub Check: Analyze (python)
🔇 Additional comments (1)
requirements/prod.txt (1)

73-73: Validate the 'fastembed==0.5.1' dependency for feature consistency.
The new dependency fastembed==0.5.1 appears to support the new embedding functionalities introduced in the LLMProcessor. Please confirm that this version meets the API requirements and does not introduce conflicts with other dependencies in the project.

Copy link

@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: 0

🧹 Nitpick comments (7)
kairon/shared/llm/processor.py (5)

157-186: Improve exception handling with proper chaining.

The method effectively handles both single string and list inputs, properly truncates texts, and collects embeddings from multiple models. However, the exception handling could be improved.

    except Exception as e:
-        raise Exception(f"Failed to fetch embeddings: {str(e)}")
+        raise Exception(f"Failed to fetch embeddings: {str(e)}") from e
🧰 Tools
🪛 Ruff (0.8.2)

186-186: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


487-488: Improve exception handling with proper chaining.

Use exception chaining to preserve the original traceback information.

-            raise Exception(f"Failed to fetch vector configs: {http_response.get('message', 'Unknown error')}")
+            raise Exception(f"Failed to fetch vector configs: {http_response.get('message', 'Unknown error')}") from None

500-510: DRY principle violation - consider refactoring model loading methods.

Both load_sparse_embedding_model and load_rerank_embedding_model have identical cache directory logic. Consider extracting this common functionality.

+ @classmethod
+ def _get_cache_dir(cls):
+     hf_cache_dir = os.path.expanduser("~/.cache/huggingface/hub")
+     kairon_cache_dir = "./kairon/pre-trained-models/"
+     return hf_cache_dir if os.path.exists(hf_cache_dir) else kairon_cache_dir

  @classmethod
  def load_sparse_embedding_model(cls):
-     hf_cache_dir = os.path.expanduser("~/.cache/huggingface/hub")
-     kairon_cache_dir = "./kairon/pre-trained-models/"
-
-     cache_dir = hf_cache_dir if os.path.exists(hf_cache_dir) else kairon_cache_dir
+     cache_dir = cls._get_cache_dir()

      if cls._sparse_embedding is None:
          cls._sparse_embedding = SparseTextEmbedding("Qdrant/bm25", cache_dir=cache_dir)
          logging.info("SPARSE MODEL LOADED")

  @classmethod
  def load_rerank_embedding_model(cls):
-     hf_cache_dir = os.path.expanduser("~/.cache/huggingface/hub")
-     kairon_cache_dir = "./kairon/pre-trained-models/"
-
-     cache_dir = hf_cache_dir if os.path.exists(hf_cache_dir) else kairon_cache_dir
+     cache_dir = cls._get_cache_dir()

      if cls._rerank_embedding is None:
          cls._rerank_embedding = LateInteractionTextEmbedding("colbert-ir/colbertv2.0", cache_dir=cache_dir)
          logging.info("RERANK MODEL LOADED")

511-530: Improve exception handling with proper chaining in get_sparse_embedding.

The method correctly generates sparse embeddings, but could benefit from proper exception chaining.

    try:
        embeddings = list(self._sparse_embedding.passage_embed(sentences))

        return [
            {"values": emb.values.tolist(), "indices": emb.indices.tolist()}
            for emb in embeddings
        ]
    except Exception as e:
-        raise Exception(f"Error processing sparse embeddings: {str(e)}")
+        raise Exception(f"Error processing sparse embeddings: {str(e)}") from e
🧰 Tools
🪛 Ruff (0.8.2)

529-529: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


531-545: Improve exception handling with proper chaining in get_rerank_embedding.

The method correctly generates rerank embeddings, but could benefit from proper exception chaining.

    try:
        embeddings = list(self._rerank_embedding.passage_embed(sentences))
        return [emb.tolist() for emb in embeddings]
    except Exception as e:
-        raise Exception(f"Error processing rerank embeddings: {str(e)}")
+        raise Exception(f"Error processing rerank embeddings: {str(e)}") from e
🧰 Tools
🪛 Ruff (0.8.2)

545-545: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

tests/unit_test/llm_test.py (2)

21-22: Remove unused imports.

These imports are not used in the test file and should be removed.

-from kairon.shared.admin.constants import BotSecretType
-from kairon.shared.admin.data_objects import BotSecrets, LLMSecret
+from kairon.shared.admin.data_objects import LLMSecret
🧰 Tools
🪛 Ruff (0.8.2)

21-21: kairon.shared.admin.constants.BotSecretType imported but unused

Remove unused import: kairon.shared.admin.constants.BotSecretType

(F401)


22-22: kairon.shared.admin.data_objects.BotSecrets imported but unused

Remove unused import: kairon.shared.admin.data_objects.BotSecrets

(F401)


2628-2659: Test for model initialization could be improved.

The test correctly checks that the model doesn't reload if already initialized, but the unused variable processor could be removed.

        logger.add(log_output, format="{message}")

-        processor = LLMProcessor(bot="test_bot", llm_type="openai")
+        # Initialize to verify no additional loading occurs
+        LLMProcessor(bot="test_bot", llm_type="openai")

        logger.remove()
🧰 Tools
🪛 Ruff (0.8.2)

2650-2650: Local variable processor is assigned to but never used

Remove assignment to unused variable processor

(F841)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1207fc8 and 3e85ffa.

📒 Files selected for processing (7)
  • kairon/actions/definitions/prompt.py (1 hunks)
  • kairon/shared/cognition/processor.py (1 hunks)
  • kairon/shared/llm/processor.py (3 hunks)
  • kairon/shared/vector_embeddings/db/qdrant.py (1 hunks)
  • kairon/train.py (1 hunks)
  • tests/integration_test/action_service_test.py (8 hunks)
  • tests/unit_test/llm_test.py (10 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
kairon/shared/llm/processor.py

186-186: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


529-529: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


545-545: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

tests/unit_test/llm_test.py

21-21: kairon.shared.admin.constants.BotSecretType imported but unused

Remove unused import: kairon.shared.admin.constants.BotSecretType

(F401)


22-22: kairon.shared.admin.data_objects.BotSecrets imported but unused

Remove unused import: kairon.shared.admin.data_objects.BotSecrets

(F401)


2650-2650: Local variable processor is assigned to but never used

Remove assignment to unused variable processor

(F841)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Python CI
  • GitHub Check: Analyze (python)
🔇 Additional comments (22)
kairon/train.py (1)

20-21: Model loading added at module level

These two method calls ensure that sparse and rerank embedding models are loaded during module initialization. This aligns with the PR objective of migrating embedding functionality from litellm service to kairon.

kairon/actions/definitions/prompt.py (1)

17-19: Model loading added at module level

Adding these embedding model loading methods ensures that the models are ready when ActionPrompt needs to process user queries. This is consistent with the changes in other files and supports the migration from litellm service.

kairon/shared/vector_embeddings/db/qdrant.py (1)

11-13: Import and model loading added

The LLMProcessor import has been uncommented and the embedding model loading methods have been added. This is particularly important for the Qdrant class which directly interacts with vector embeddings and uses llm.get_embedding() for vector operations.

kairon/shared/cognition/processor.py (1)

588-590: Model loading added in upsert_data method

Unlike the other files where model loading happens at module level, here the models are loaded inside the upsert_data method just before creating the LLMProcessor instance. This ensures the models are available when generating embeddings for data being upserted to Qdrant.

tests/integration_test/action_service_test.py (8)

3808-3810: Good addition of passthru URLs for embedding models

These additions allow the test to access Hugging Face embedding models (BM25 and ColBERT) directly, which is consistent with the migration of embedding functionality from litellm to Kairon. This ensures the tests can properly validate the new internal embedding implementation.


3901-3903: Good addition of passthru URLs for embedding models

Properly added the same Hugging Face model URLs to allow this test to access the embedding models directly. This is consistent with the embedding functionality migration.


3993-3995: Good addition of passthru URLs for embedding models

These passthru URLs correctly allow real HTTP requests to the Hugging Face models (sparse BM25 and reranking ColBERT) needed for the embedding functionality that's been migrated to Kairon.


4088-4090: Good addition of passthru URLs for embedding models

The addition of these Hugging Face model URLs is consistent with the embedding implementation migration. Since this test specifically mocks the get_embedding method, allowing passthru to embedding model URLs ensures the test correctly simulates the integration between components.


4225-4227: Good addition of passthru URLs for embedding models

The addition of passthru URLs for the BM25 and ColBERT models allows proper testing of the payload search functionality using the migrated embedding implementation.


4316-4318: Good addition of passthru URLs for embedding models

These passthru URLs appropriately support testing error handling scenarios with the new embedding implementation, ensuring the tests properly validate error cases with the migrated functionality.


4379-4381: Good addition of passthru URLs for embedding models

Properly added passthru URLs for the embedding models while testing slot-based embedding search. The mock of get_embedding combined with these passthru URLs ensures thorough testing of the migrated functionality.


4519-4521: Good addition of passthru URLs for embedding models

The addition of these passthru URLs completes the testing coverage for the no-response-dispatch scenario with the new embedding implementation. This ensures proper validation of all edge cases with the migrated functionality.

kairon/shared/llm/processor.py (2)

145-155: Well-structured implementation for text truncation.

The truncate_text method correctly handles the tokenization of input texts and ensures they don't exceed the embedding context length limit of 8191 tokens, which is essential for OpenAI's embeddings.


489-499: Good implementation for model loading with fallback mechanism.

The method properly checks for the Hugging Face cache directory and falls back to a local cache directory if needed. The singleton pattern ensures the model is only loaded once.

tests/unit_test/llm_test.py (8)

4-4: Proper imports for testing.

Good use of MagicMock and AsyncMock for testing asynchronous methods.


7-9: New imports for testing logging and stream handling.

Added appropriate imports for capturing log output during tests.


13-13: Import for embedding models.

Good addition of the SparseTextEmbedding and LateInteractionTextEmbedding imports to test the new functionality.


1950-2046: Well-structured test for collection hybrid query.

The test thoroughly verifies the hybrid query functionality, including checking the request payload and validating the response format.


2047-2081: Good test for handling request failures.

Proper testing of error handling when a request fails.


2119-2146: Comprehensive test for sparse embedding with single sentence.

The test properly mocks the sparse embedding model and verifies the output format.


2365-2414: Complete test coverage for single text embedding.

The test thoroughly covers the entire embedding pipeline for a single text input, including dense, sparse, and rerank embeddings.


2417-2478: Thorough test for multiple text embedding.

Good test coverage for processing multiple texts through the embedding pipeline.

@sfahad1414 sfahad1414 self-requested a review March 7, 2025 08:57
Copy link
Collaborator

@sfahad1414 sfahad1414 left a comment

Choose a reason for hiding this comment

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

Approved

@sfahad1414 sfahad1414 merged commit 4760807 into digiteinfotech:master Mar 7, 2025
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants