Skip to content

feat: make nlu penalty factor setting configurable in UI #956

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

Open
wants to merge 47 commits into
base: main
Choose a base branch
from

Conversation

MohamedAliBouhaouala
Copy link
Contributor

@MohamedAliBouhaouala MohamedAliBouhaouala commented Apr 24, 2025

Motivation

The following PR PR introduces support for configuring the NLU Penalty Factor via the UI, allowing chatbot builders to control how entity match specificity influences block selection.

Key changes

  • Adds default_nlu_penalty_factor to the chatbot settings section in the UI.
  • Updates the NLP block scoring logic to dynamically reference the configured penalty factor instead of using a hardcoded value.
  • Migration script ensures the setting is added to existing databases, maintaining behavior consistency across upgraded environments.
  • Seed script ensures the setting is included during fresh installations.

Screenshot from 2025-04-24 11-32-31

Fixes # (issue)

Type of change:

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

Checklist:

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • I have added unit tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

Summary by CodeRabbit

  • New Features

    • Introduced a configurable "NLU Penalty Factor" setting in chatbot settings, allowing adjustment of how broadly matching NLU entities are scored.
    • Added English and French labels and help descriptions for the new setting in the chatbot settings interface.
  • Bug Fixes

    • Updated test cases to reflect the new default NLU penalty factor value and expected behavior.
  • Chores

    • Database migration to add the new "NLU Penalty Factor" setting with a default value and constraints.
    • Adjusted the order of chatbot settings for improved organization.

Copy link

coderabbitai bot commented Apr 24, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

A new configurable setting, default_nlu_penalty_factor, has been introduced to control the penalty factor applied to NLP entity matching within the chatbot system. The backend now retrieves this value dynamically from global settings, with validation to ensure it remains between 0 and 1. A migration script and seed data entry have been added to establish the setting in the database. Test logic and expectations were updated to reflect the new default value. Localization files in English and French now include labels and help descriptions for the new setting.

Changes

File(s) Change Summary
api/src/chat/services/block.service.ts Replaced hardcoded NLU penalty factor with dynamic retrieval from settings; added getDefaultNluPenaltyFactor() method with validation.
api/src/chat/services/block.service.spec.ts Updated tests to use new penalty factor value (0.95 instead of 2) and adjusted expected best block accordingly.
api/src/migration/migrations/1745594957327-v-2-2-6.migration.ts Added migration to insert or remove default_nlu_penalty_factor setting in the database, with logging and validation.
api/src/setting/seeds/setting.seed-model.ts Added default_nlu_penalty_factor to DEFAULT_SETTINGS with default value and constraints; incremented weights of subsequent settings in chatbot_settings group.
frontend/public/locales/en/chatbot_settings.json
frontend/public/locales/fr/chatbot_settings.json
Added label and help text for default_nlu_penalty_factor in English and French localization files.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Chatbot
    participant BlockService
    participant SettingsService
    participant Database

    User->>Chatbot: Sends message
    Chatbot->>BlockService: Request block match
    BlockService->>SettingsService: getDefaultNluPenaltyFactor()
    SettingsService->>Database: Fetch setting
    Database-->>SettingsService: Return penalty factor (0.95)
    SettingsService-->>BlockService: Return penalty factor
    BlockService->>BlockService: Apply penalty factor in NLP scoring
    BlockService-->>Chatbot: Return best matching block
    Chatbot-->>User: Respond with matched block
Loading

Poem

A penalty factor, crisp and new,
Now guides the bots in what they do.
From settings fetched, not hard and fast,
It shapes the matches unsurpassed.
In English and French, its meaning clear,
The rabbits cheer: “Precision’s here!”
🐇✨


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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.

@MohamedAliBouhaouala MohamedAliBouhaouala force-pushed the feat/make-default-nlu-penalty-factor-configurable branch from d8be661 to d19874a Compare April 24, 2025 18:12
@medchedli medchedli added this to the v2.2.6 milestone Apr 25, 2025
@medchedli medchedli linked an issue Apr 25, 2025 that may be closed by this pull request
@MohamedAliBouhaouala MohamedAliBouhaouala force-pushed the feat/implement-block-nlp-prioritization-strategy branch 2 times, most recently from 664dbf9 to 909f7c2 Compare April 25, 2025 09:38
@MohamedAliBouhaouala MohamedAliBouhaouala force-pushed the feat/make-default-nlu-penalty-factor-configurable branch 2 times, most recently from 65b443f to 169b767 Compare April 25, 2025 10:43
@IkbelTalebHssan IkbelTalebHssan self-requested a review April 25, 2025 15:54
@medchedli
Copy link
Contributor

medchedli commented Apr 28, 2025

@coderabbitai full review

Copy link

coderabbitai bot commented Apr 28, 2025

✅ Actions performed

Full review triggered.

@Hexastack Hexastack deleted a comment from coderabbitai bot Apr 28, 2025
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: 1

🧹 Nitpick comments (6)
api/src/chat/services/block.service.ts (2)

222-224: Improve the error message specificity.

The error message should specify that it's referring to the NLU penalty factor.

-  throw new Error('Penalty Factor must be between 0 and 1.');
+  throw new Error('NLU Penalty Factor must be between 0 and 1.');

483-495: Well-documented method for retrieving the NLU penalty factor.

The method is well-documented with JSDoc that clearly explains the purpose of this factor in NLU-based scoring. Consider moving the validation into this method to ensure it always returns a valid value.

async getDefaultNluPenaltyFactor(): Promise<number> {
  const settings: Settings = await this.settingService.getSettings();
-  return settings.chatbot_settings.default_nlu_penalty_factor;
+  const nluPenaltyFactor = settings.chatbot_settings.default_nlu_penalty_factor;
+  if (nluPenaltyFactor < 0 || nluPenaltyFactor > 1) {
+    throw new Error('NLU Penalty Factor must be between 0 and 1.');
+  }
+  return nluPenaltyFactor;
}
api/src/migration/migrations/1745594957327-v-2-2-6.migration.ts (4)

40-40: Fix typo in success message.

There's a typo in the success message.

-    logger.log('Successfuly added the default NLU penalty factor setting');
+    logger.log('Successfully added the default NLU penalty factor setting');

41-43: Improve error logging.

Include the error object in the log for better debugging.

-  } catch (err) {
-    logger.error('Unable to add the default NLU penalty factor setting');
+  } catch (err) {
+    logger.error('Unable to add the default NLU penalty factor setting', err);

53-53: Fix typo in success message.

There's a typo in the success message.

-    logger.log('Successfuly removed the default NLU penalty factor setting');
+    logger.log('Successfully removed the default NLU penalty factor setting');

54-56: Improve error logging.

Include the error object in the log for better debugging.

-  } catch (err) {
-    logger.error('Unable to remove the default local storage helper setting');
+  } catch (err) {
+    logger.error('Unable to remove the default NLU penalty factor setting', err);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a46790e and c2f3569.

📒 Files selected for processing (6)
  • api/src/chat/services/block.service.spec.ts (2 hunks)
  • api/src/chat/services/block.service.ts (2 hunks)
  • api/src/migration/migrations/1745594957327-v-2-2-6.migration.ts (1 hunks)
  • api/src/setting/seeds/setting.seed-model.ts (4 hunks)
  • frontend/public/locales/en/chatbot_settings.json (1 hunks)
  • frontend/public/locales/fr/chatbot_settings.json (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
api/src/chat/services/block.service.spec.ts (1)
api/src/utils/test/mocks/block.ts (1)
  • mockNlpBlock (287-312)
api/src/migration/migrations/1745594957327-v-2-2-6.migration.ts (1)
api/src/migration/types.ts (1)
  • MigrationServices (39-43)
api/src/chat/services/block.service.ts (1)
frontend/src/components/settings/index.tsx (1)
  • Settings (72-218)
🔇 Additional comments (10)
frontend/public/locales/fr/chatbot_settings.json (2)

11-12: LGTM! The new label is properly added to the French localization.

The label for the new NLU penalty factor setting has been correctly added to the French localization file.


19-20: Complete and well-explained help text.

The help description provides a thorough explanation of the NLU penalty factor, including its purpose, range (0-1), and how it affects chatbot behavior. The translation accurately conveys the technical concept in French.

api/src/setting/seeds/setting.seed-model.ts (2)

41-52: LGTM! Well-structured new setting with appropriate constraints.

The new default_nlu_penalty_factor setting is properly configured:

  • Appropriate default value (0.95)
  • Correct type (number)
  • Proper constraints (min: 0, max: 1, step: 0.01)
  • Reasonable weight value (3)

65-97: LGTM! Weight values properly updated.

The weight values for subsequent settings have been correctly incremented to maintain proper ordering after inserting the new setting:

  • default_storage_helper: 3 → 4
  • global_fallback: 4 → 5
  • fallback_block: 5 → 6
  • fallback_message: 6 → 7
api/src/chat/services/block.service.spec.ts (2)

357-357: LGTM! Test constant updated to match new default value.

The nlpPenaltyFactor constant has been correctly updated from the previous hardcoded value to 0.95, matching the new default value defined in the settings.


411-411: LGTM! Test expectation updated to reflect new behavior.

The expected block in the test assertion has been updated from mockModifiedNlpBlock to mockNlpBlock, correctly reflecting the change in block selection behavior with the new penalty factor.

frontend/public/locales/en/chatbot_settings.json (2)

11-12: LGTM! New label added to English localization.

The label for the new NLU penalty factor setting has been correctly added to the English localization file.


19-20: Clear and comprehensive help description.

The help text provides an excellent explanation of the NLU penalty factor, clearly describing:

  • The acceptable range (0-1)
  • Its purpose in prioritizing specific entity matches over broad ones
  • How it affects matching without impacting other matching strategies
api/src/chat/services/block.service.ts (1)

218-224: LGTM - Retrieving NLU penalty factor from settings.

This change makes the previously hardcoded NLU penalty factor configurable through global settings, which enhances flexibility and user control.

api/src/migration/migrations/1745594957327-v-2-2-6.migration.ts (1)

16-44: LGTM - Setting up the default NLU penalty factor.

The migration properly adds the new configurable setting with appropriate constraints.

Comment on lines +41 to +52
{
group: 'chatbot_settings',
label: 'default_nlu_penalty_factor',
value: 0.95,
type: SettingType.number,
config: {
min: 0,
max: 1,
step: 0.01,
},
weight: 3,
},
Copy link
Contributor

@abdou6666 abdou6666 Apr 28, 2025

Choose a reason for hiding this comment

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

Do the other chatbot_settings weights need migration?
This might lead to inconsistencies in the UI.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I don't think so. We didn't migrate weights when we added a default storage helper in global settings.

@MohamedAliBouhaouala MohamedAliBouhaouala force-pushed the feat/make-default-nlu-penalty-factor-configurable branch from 5727e1b to 27be2c6 Compare April 28, 2025 16:52
@MohamedAliBouhaouala MohamedAliBouhaouala force-pushed the feat/make-default-nlu-penalty-factor-configurable branch from b7f241c to 1c39413 Compare April 28, 2025 18:24
@MohamedAliBouhaouala MohamedAliBouhaouala force-pushed the feat/implement-block-nlp-prioritization-strategy branch from 6686e3e to a8666ce Compare May 5, 2025 09:32
@MohamedAliBouhaouala MohamedAliBouhaouala force-pushed the feat/make-default-nlu-penalty-factor-configurable branch from 1c39413 to e3ce245 Compare May 5, 2025 09:42
// Log the matched patterns
this.logger.debug(
`Matched patterns: ${JSON.stringify(matchesWithPatterns.map((p) => p.matchedPattern))}`,
);

// Retrieve Nlu Penalty Factor from global settings
const nluPenaltyFactor: number =
Copy link
Contributor

Choose a reason for hiding this comment

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

I think we should remove the typing since it can be inferred by typescript.

@@ -354,7 +354,7 @@ describe('BlockService', () => {
});

describe('matchBestNLP', () => {
const nlpPenaltyFactor = 2;
const nlpPenaltyFactor = 0.95;
Copy link
Contributor

Choose a reason for hiding this comment

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

I think we should re-use the constant declared in nlp.ts

@MohamedAliBouhaouala MohamedAliBouhaouala changed the base branch from feat/implement-block-nlp-prioritization-strategy to feat/implement-block-nlp-prioritization-strategy-v2 May 7, 2025 15:08
@marrouchi marrouchi removed this from the v2.2.6 milestone May 9, 2025
@marrouchi marrouchi force-pushed the feat/implement-block-nlp-prioritization-strategy-v2 branch from 2465ae1 to 9642e82 Compare May 12, 2025 06:30
@yassinedorbozgithub yassinedorbozgithub force-pushed the feat/implement-block-nlp-prioritization-strategy-v2 branch from 9642e82 to 2465ae1 Compare May 12, 2025 10:09
@medchedli medchedli removed the v2.2.6 label May 13, 2025
@medchedli medchedli changed the base branch from feat/implement-block-nlp-prioritization-strategy-v2 to main May 13, 2025 14:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

💡 [REQUEST] - Introduce support for configuring the NLU Penalty Factor 🤔 [ISSUE] - Prioritize Blocks with the Most Matching NLU Entities
5 participants