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

added secret and bot_id in config #1644

Merged
merged 1 commit into from
Dec 12, 2024
Merged

Conversation

sfahad1414
Copy link
Collaborator

@sfahad1414 sfahad1414 commented Dec 12, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced API key management for improved security and flexibility.
    • Improved configuration handling for the LLMClassifier during training.
    • Added error handling and logging to the training process for better tracking of training status.
  • Bug Fixes

    • Ensured accurate updates to training status based on outcomes.

Copy link

coderabbitai bot commented Dec 12, 2024

Walkthrough

The pull request introduces changes to the LLMClassifier class in kairon/nlu/classifiers/llm.py, focusing on API key management by replacing the api_key attribute with a secret attribute stored in a dictionary. This affects methods like load_api_key, get_embeddings, and predict, which now utilize the new secret attribute. Additionally, modifications in kairon/train.py enhance the training functions by improving configuration handling for the LLMClassifier and adding error handling and logging to the training process.

Changes

File Change Summary
kairon/nlu/classifiers/llm.py - Updated load_api_key, get_embeddings, and predict methods to use secret attribute instead of api_key.
kairon/train.py - Modified train_model_for_bot to update bot_id in configuration for LLMClassifier.
- Enhanced start_training with error handling and logging, updating training status appropriately.

Possibly related PRs

  • added llm classifier #1613: The changes in the main PR directly modify the LLMClassifier class in kairon/nlu/classifiers/llm.py, which is the same class that was introduced in this retrieved PR. The modifications to API key handling and method signatures in the main PR are related to the functionality of the LLMClassifier added in this PR.

Suggested reviewers

  • hiteshghuge

Poem

In the code where secrets dwell,
A rabbit hops, and all is well.
With keys now tucked in safe embrace,
Our training's strong, we pick up pace.
So let us cheer, with joyful glee,
For changes made, as bright as can be! 🐰✨


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 generate docstrings to generate docstrings for this PR. (Experiment)
  • @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: 4

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ebcdd78 and 8b54a96.

📒 Files selected for processing (2)
  • kairon/nlu/classifiers/llm.py (2 hunks)
  • kairon/train.py (2 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
kairon/nlu/classifiers/llm.py

90-90: f-string without any placeholders

Remove extraneous f prefix

(F541)

🔇 Additional comments (2)
kairon/nlu/classifiers/llm.py (2)

85-87: Verify configuration consistency

Let's ensure the configuration values are used consistently across the codebase.

Also applies to: 94-96, 190-193

✅ Verification successful

Based on the search results, I can now provide a final response:

Configuration values are consistently managed

The hardcoded model names found in the codebase are primarily in test files (tests/) which is expected for test assertions. The actual implementation in kairon/nlu/classifiers/llm.py properly uses configuration values:

  • Model names are retrieved from component config with defaults: component_config.get("prediction_model", "gpt-3.5-turbo")
  • Other parameters like temperature and top_k are also properly configured: component_config.get("temperature", 0.0)
  • Retry mechanism is consistently set to 3 attempts across the codebase
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent use of configuration values

# Look for hardcoded model names that should use config
rg -B 2 -A 2 '"text-embedding-3-small"|"gpt-3.5-turbo"|"gpt-4o-mini"' --type py

# Check for hardcoded retry values
rg -B 2 -A 2 'max_retries\s*=\s*[0-9]+' --type py

# Look for other potential configuration inconsistencies
rg -B 2 -A 2 'component_config\.get' --type py

Length of output: 24683


85-87: Verify secret handling in logs

Let's ensure there's no accidental logging of API keys throughout the codebase.

✅ Verification successful

No security concerns found in secret handling

The codebase shows proper secret handling practices:

  • The encrypt_secrets method in ActionUtility is used to mask sensitive data
  • Only debug logging of the LLM response object is present, which contains the model output, not the API key
  • The API key is passed directly to the LLM client library without being logged
  • No direct logging of self.secret or API keys was found in the codebase
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential API key logging or exposure

# Look for logging statements that might contain API keys
rg -i "log.*secret|log.*api.?key" --type py

# Check for print statements near API key handling
rg -B 3 -A 3 "print.*secret|print.*api.?key" --type py

# Look for debug logging that might expose secrets
rg -i "debug.*secret|debug.*api.?key" --type py

Length of output: 4224


Script:

#!/bin/bash
# Let's check the ActionUtility.encrypt_secrets implementation and its usage

# Check the implementation of encrypt_secrets
ast-grep --pattern 'def encrypt_secrets($$$)'

# Check for any logging of self.secret or api_key in the LLM classifier
rg -B 3 -A 3 "self\.secret|api_key" kairon/nlu/classifiers/llm.py

# Look for any direct logging of secrets in the codebase
rg -i "logger\.(debug|info|warning|error).*self\.secret" --type py

Length of output: 1455


Script:

#!/bin/bash
# Let's check the ActionUtility class implementation and any secret masking logic

# Search for ActionUtility class definition
ast-grep --pattern 'class ActionUtility {
  $$$
}'

# Check for any secret masking or encryption implementation
rg -B 3 -A 3 "mask|encrypt|hide.*secret" --type py

# Look for any logging of response objects that might contain secrets
rg -B 3 -A 3 "logger\.debug.*response" --type py

Length of output: 87432


Script:

#!/bin/bash
# Let's check the ActionUtility class and any secret masking in the actual implementation

# Look for ActionUtility class implementation
rg -B 5 -A 10 "class ActionUtility" --type py

# Check for any secret masking or encryption implementation in the codebase
rg -B 3 -A 3 "def encrypt_secrets|def mask_secret" --type py

# Check for any logging of response objects in the LLM classifier
rg -B 3 -A 3 "logger\.(debug|info|warning|error).*response" kairon/nlu/classifiers/llm.py

Length of output: 1991

Comment on lines +41 to +44

index = next((index for (index, d) in enumerate(config['pipeline']) if d["name"] == "kairon.nlu.LLMClassifier"), None)
if index:
config[index]['bot_id']= bot
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for pipeline configuration

The current implementation silently continues if the LLMClassifier is not found in the pipeline. Consider adding validation and logging to handle edge cases.

-        index = next((index for (index, d) in enumerate(config['pipeline']) if d["name"] == "kairon.nlu.LLMClassifier"), None)
-        if index:
-            config[index]['bot_id']= bot
+        try:
+            if not isinstance(config.get('pipeline'), list):
+                raise ValueError("Invalid pipeline configuration: expected a list")
+            
+            index = next((index for (index, d) in enumerate(config['pipeline']) 
+                         if d.get("name") == "kairon.nlu.LLMClassifier"), None)
+            if index is not None:
+                config['pipeline'][index]['bot_id'] = bot
+            else:
+                logging.debug(f"LLMClassifier not found in pipeline configuration for bot {bot}")
+        except Exception as e:
+            logging.error(f"Error updating LLMClassifier configuration: {str(e)}")
+            raise AppException(f"Failed to configure LLMClassifier: {str(e)}")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
index = next((index for (index, d) in enumerate(config['pipeline']) if d["name"] == "kairon.nlu.LLMClassifier"), None)
if index:
config[index]['bot_id']= bot
try:
if not isinstance(config.get('pipeline'), list):
raise ValueError("Invalid pipeline configuration: expected a list")
index = next((index for (index, d) in enumerate(config['pipeline'])
if d.get("name") == "kairon.nlu.LLMClassifier"), None)
if index is not None:
config['pipeline'][index]['bot_id'] = bot
else:
logging.debug(f"LLMClassifier not found in pipeline configuration for bot {bot}")
except Exception as e:
logging.error(f"Error updating LLMClassifier configuration: {str(e)}")
raise AppException(f"Failed to configure LLMClassifier: {str(e)}")

Comment on lines 94 to 96
embeddings = litellm.embedding(
model="text-embedding-3-small", input=text, api_key=self.api_key, max_retries=3
model="text-embedding-3-small", input=text, max_retries=3, **self.secret
)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use configuration value for embedding model

The embedding model name is hardcoded as "text-embedding-3-small" but should use the value from component_config.

         embeddings = litellm.embedding(
-            model="text-embedding-3-small", input=text, max_retries=3, **self.secret
+            model=self.component_config.get("embedding_model", "text-embedding-3-small"),
+            input=text,
+            max_retries=self.component_config.get("retry", 3),
+            **self.secret
         )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
embeddings = litellm.embedding(
model="text-embedding-3-small", input=text, api_key=self.api_key, max_retries=3
model="text-embedding-3-small", input=text, max_retries=3, **self.secret
)
embeddings = litellm.embedding(
model=self.component_config.get("embedding_model", "text-embedding-3-small"),
input=text,
max_retries=self.component_config.get("retry", 3),
**self.secret
)

Comment on lines 190 to 193
presence_penalty=0,
api_key=self.api_key,
max_retries=3
max_retries=3,
**self.secret
)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Ensure consistent retry configuration

The max_retries parameter should use the value from component_config to maintain consistency.

-                max_retries=3,
+                max_retries=self.component_config.get("retry", 3),
                 **self.secret
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
presence_penalty=0,
api_key=self.api_key,
max_retries=3
max_retries=3,
**self.secret
)
presence_penalty=0,
max_retries=self.component_config.get("retry", 3),
**self.secret
)

Comment on lines 84 to 91
llm_secret = Sysadmin.get_llm_secret("openai", bot_id)
self.api_key = llm_secret.get('api_key')
self.secret = llm_secret.get('api_key')
elif os.environ.get("LLM_API_KEY"):
self.api_key = os.environ.get("LLM_API_KEY")
self.secret = {'api_key': os.environ.get("LLM_API_KEY")}
else:
raise KeyError(
f"either set bot_id'in LLMClassifier config or set LLM_API_KEY in environment variables"
)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve security in error handling

The error message reveals sensitive configuration details. Consider using a more generic error message.

         else:
             raise KeyError(
-                f"either set bot_id'in LLMClassifier config or set LLM_API_KEY in environment variables"
+                "API key configuration is missing. Please check the documentation for setup instructions."
             )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
llm_secret = Sysadmin.get_llm_secret("openai", bot_id)
self.api_key = llm_secret.get('api_key')
self.secret = llm_secret.get('api_key')
elif os.environ.get("LLM_API_KEY"):
self.api_key = os.environ.get("LLM_API_KEY")
self.secret = {'api_key': os.environ.get("LLM_API_KEY")}
else:
raise KeyError(
f"either set bot_id'in LLMClassifier config or set LLM_API_KEY in environment variables"
)
llm_secret = Sysadmin.get_llm_secret("openai", bot_id)
self.secret = llm_secret.get('api_key')
elif os.environ.get("LLM_API_KEY"):
self.secret = {'api_key': os.environ.get("LLM_API_KEY")}
else:
raise KeyError(
"API key configuration is missing. Please check the documentation for setup instructions."
)
🧰 Tools
🪛 Ruff (0.8.2)

90-90: f-string without any placeholders

Remove extraneous f prefix

(F541)

Copy link
Collaborator

@hiteshghuge hiteshghuge left a comment

Choose a reason for hiding this comment

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

approved

@hiteshghuge hiteshghuge merged commit 521990a into master Dec 12, 2024
6 of 7 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