Repository: potpie-ai/potpie
Pull request #295: prompt enhancing functionality
Author: login: kinshuksinghbist
Created: 2025-03-04T00:25:43Z | Merged: 2025-03-10T08:18:48Z



<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit

- **New Features**
	- Introduced enhanced prompt handling that leverages recent conversation history and agent options.
	- Added a dedicated endpoint with updated request and response structures for prompt enhancement.
- **Documentation**
	- Improved the UI setup instructions with standardized formatting for better clarity.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->


Diff:
diff --git a/README.md b/README.md
index 1ed7cc9fc..2f50a9ede 100644
--- a/README.md
+++ b/README.md
@@ -119,44 +119,44 @@ Potpie provides a set of tools that agents can use to interact with the knowledg
 ### Potpie UI
   An easy to use interface to interact with your Agents
   ## Initialize the UI Submodule
-        To initialize the submodule:
+  To initialize the submodule:
 
-        ```bash
-        git submodule update --init
-        ```
+  ```bash
+  git submodule update --init
+  ```
 
-      ### 1. Navigate to the `potpie-ui` Directory
+  ### 1. Navigate to the `potpie-ui` Directory
 
-      ```bash
-      cd potpie-ui
-      ```
+  ```bash
+  cd potpie-ui
+  ```
 
-      ### 2. Update the Main Branch and Checkout
+  ### 2. Update the Main Branch and Checkout
 
-      ```bash
-      git checkout main
-      git pull origin main
-      ```
+  ```bash
+  git checkout main
+  git pull origin main
+  ```
 
-      ### 3. Set Up the Environment
+  ### 3. Set Up the Environment
 
-      Create a `.env` file in the `potpie-ui` directory and copy the required configuration from `.env.template`.
+  Create a `.env` file in the `potpie-ui` directory and copy the required configuration from `.env.template`.
 
-      ```bash
-      cp .env.template .env
-      ```
+  ```bash
+  cp .env.template .env
+  ```
 
-      ### 4. Build the Frontend
+  ### 4. Build the Frontend
 
-      ```bash
-      pnpm build
-      ```
+  ```bash
+  pnpm build
+  ```
 
-      ### 5. Start the Application
+  ### 5. Start the Application
 
-      ```bash
-      pnpm start
-      ```
+  ```bash
+  pnpm start
+  ```
 
 
 ### Setup Steps
diff --git a/app/modules/intelligence/prompts/prompt_controller.py b/app/modules/intelligence/prompts/prompt_controller.py
index c99f65960..28f8dc9ea 100644
--- a/app/modules/intelligence/prompts/prompt_controller.py
+++ b/app/modules/intelligence/prompts/prompt_controller.py
@@ -1,6 +1,7 @@
 from typing import Optional
 
 from fastapi import HTTPException
+from sqlalchemy.orm import Session
 
 from app.modules.intelligence.prompts.prompt_schema import (
     PromptCreate,
@@ -13,6 +14,15 @@
     PromptService,
     PromptServiceError,
 )
+from app.modules.intelligence.agents.agents_service import AgentsService
+from app.modules.intelligence.prompts.prompt_schema import RequestModel
+from app.modules.conversations.conversation.conversation_model import Conversation
+from app.modules.intelligence.agents.custom_agents.custom_agent_model import CustomAgent
+from app.modules.conversations.message.message_model import (
+    Message,
+    MessageStatus,
+)
+from app.modules.conversations.message.message_schema import MessageResponse
 
 
 class PromptController:
@@ -74,3 +84,64 @@ async def list_prompts(
             return await prompt_service.list_prompts(query, skip, limit, user_id)
         except PromptServiceError as e:
             raise HTTPException(status_code=500, detail=str(e))
+
+    @staticmethod
+    async def enhance_prompt(
+        request_body: RequestModel,
+        db: Session,
+        user: dict,
+    ) -> str:
+
+        messages = (
+            db.query(Message)
+            .filter_by(conversation_id=request_body.conversation_id)
+            .filter_by(status=MessageStatus.ACTIVE)
+            .order_by(Message.created_at.desc())
+            .limit(2)
+            .all()
+        )
+
+        # to get them in chronological order
+        messages.reverse()
+
+        last_messages = [
+            MessageResponse(
+                id=message.id,
+                conversation_id=message.conversation_id,
+                content=message.content,
+                sender_id=message.sender_id,
+                type=message.type,
+                status=message.status,
+                created_at=message.created_at,
+                citations=(message.citations.split(",") if message.citations else None),
+            )
+            for message in messages
+        ]
+
+        agents_service = AgentsService(db)
+        available_agents = await agents_service.list_available_agents(
+            user, list_system_agents=True
+        )
+
+        agent_ids = (
+            db.query(Conversation.agent_ids)
+            .filter_by(id=request_body.conversation_id)
+            .scalar()
+        ) or []
+
+        is_custom_agent = (
+            db.query(CustomAgent).filter(CustomAgent.id.in_(agent_ids)).first()
+            is not None
+        )
+
+        if not is_custom_agent:
+            enhanced_prompt = await PromptService(db).enhance_prompt(
+                request_body.prompt, last_messages, user, agent_ids, available_agents
+            )
+        else:
+            enhanced_prompt = await PromptService(db).enhance_prompt(
+                request_body.prompt,
+                last_messages,
+                user,
+            )
+        return enhanced_prompt
diff --git a/app/modules/intelligence/prompts/prompt_router.py b/app/modules/intelligence/prompts/prompt_router.py
index 9465586e8..ce4c8dbce 100644
--- a/app/modules/intelligence/prompts/prompt_router.py
+++ b/app/modules/intelligence/prompts/prompt_router.py
@@ -3,6 +3,7 @@
 from fastapi import APIRouter, Depends, Query
 from sqlalchemy.orm import Session
 
+
 from app.core.database import get_db
 from app.modules.auth.auth_service import AuthService
 from app.modules.intelligence.prompts.prompt_controller import PromptController
@@ -13,6 +14,8 @@
     PromptUpdate,
 )
 from app.modules.intelligence.prompts.prompt_service import PromptService
+from app.modules.intelligence.prompts.prompt_schema import RequestModel
+
 
 router = APIRouter()
 
@@ -80,3 +83,13 @@ async def list_prompts(
         return await PromptController.list_prompts(
             query, skip, limit, prompt_service, user["user_id"]
         )
+
+    @staticmethod
+    @router.post("/prompts/enhancer", response_model=str)
+    async def enhance_prompt(
+        request_body: RequestModel,
+        db: Session = Depends(get_db),
+        user=Depends(AuthService.check_auth),
+    ):
+
+        return await PromptController.enhance_prompt(request_body, db, user)
diff --git a/app/modules/intelligence/prompts/prompt_schema.py b/app/modules/intelligence/prompts/prompt_schema.py
index ba2644c35..77985295c 100644
--- a/app/modules/intelligence/prompts/prompt_schema.py
+++ b/app/modules/intelligence/prompts/prompt_schema.py
@@ -86,3 +86,12 @@ class AgentPromptMappingResponse(BaseModel):
 
     class Config:
         from_attributes = True
+
+
+class RequestModel(BaseModel):
+    conversation_id: str
+    prompt: str
+
+
+class EnhancedPromptResponse(BaseModel):
+    enhancedprompt: str
diff --git a/app/modules/intelligence/prompts/prompt_service.py b/app/modules/intelligence/prompts/prompt_service.py
index 6674546a1..6b88f345a 100644
--- a/app/modules/intelligence/prompts/prompt_service.py
+++ b/app/modules/intelligence/prompts/prompt_service.py
@@ -21,6 +21,10 @@
     PromptUpdate,
 )
 
+from app.modules.conversations.message.message_schema import MessageResponse
+from app.modules.intelligence.prompts.prompt_schema import EnhancedPromptResponse
+from app.modules.intelligence.provider.provider_service import ProviderService
+
 logger = logging.getLogger(__name__)
 
 
@@ -338,3 +342,130 @@ async def get_prompts_by_agent_id_and_types(
             raise PromptServiceError(
                 "Failed to get prompts by agent ID and types"
             ) from e
+
+    async def enhance_prompt(
+        self,
+        prompt: str,
+        last_messages: List[MessageResponse],
+        user: dict,
+        agent_ids=None,
+        available_agents=None,
+    ) -> str:
+
+        if agent_ids and available_agents:
+            inputs = {
+                "query": prompt,
+                "history": [msg.content for msg in last_messages],
+                "agent_id": agent_ids,
+                "available_agents": available_agents,
+            }
+
+            messages = [
+                {
+                    "role": "system",
+                    "content": get_prompt("Enhancer_Prompt_With_Classification"),
+                },
+                {
+                    "role": "user",
+                    "content": f"Query: {inputs['query']}\nHistory: {inputs['history']}\nCurent Agent Id: {inputs['agent_id']}\nAvailable Agents: {inputs['available_agents']}\n\n",
+                },
+            ]
+
+        else:
+            inputs = {
+                "query": prompt,
+                "history": [msg.content for msg in last_messages],
+            }
+
+            messages = [
+                {"role": "system", "content": get_prompt("Enhancer_Prompt")},
+                {
+                    "role": "user",
+                    "content": f"Query: {inputs['query']}\nHistory: {inputs['history']}\n\n",
+                },
+            ]
+
+        try:
+            provider_service = ProviderService(self.db, user["user_id"])
+            result = await provider_service.call_llm_with_structured_output(
+                messages=messages, output_schema=EnhancedPromptResponse, size="large"
+            )
+            return result.enhancedprompt
+        except Exception as e:
+            logger.error(f"Enhancing failed: {e}")
+            raise
+
+
+def get_prompt(prompt_key: str) -> str:
+    return PROMPTS.get(prompt_key, "Prompt not found.")
+
+
+PROMPTS = {
+    "Enhancer_Prompt_With_Classification": """You are a prompt enhancer. Your primary purpose is to improve user queries by adding context and clarity.
+    Process:
+    1. INTERNAL STEP ONLY: Classify the most appropriate agent based on the query and agent descriptions. This classification is only to help you understand which expertise domain to enhance the prompt for.
+    2. Enhance the original query using conversation history and the relevant expertise domain identified in step 1.
+
+    Input:
+    - Query: {query}
+    - Current Agent ID: {agent_id}
+    - Conversation History: {history}
+    - Available Agents: {agent_descriptions}
+
+    Agent Selection Process:
+    1. Identify key topics, technical terms, and user intent from the query
+    2. Compare query elements against each agent's specialty description
+    3. Apply contextual weighting:
+       - Current agent advantage: +0.15 for direct expertise, +0.1 for related knowledge
+       - For new topics outside current agent's domain, evaluate all agents equally
+    4. Use confidence scoring (0.9-1.0: ideal match, 0.7-0.9: strong match, 0.5-0.7: partial match, <0.5: weak match)
+
+    Query Enhancement Guidelines:
+    1. Resolve ambiguous references using conversation history
+    2. Incorporate relevant context from previous exchanges
+    3. Maintain factual integrity (no invented information)
+    4. Restructure ambiguous queries by clarifying:
+       - Problem statement
+       - Contextual details
+       - Expected outcome
+
+    Examples:
+    1. History: "I've been working on a React app that fetches data from an API. The data loads slowly when there are many records."
+       Query: "How can I make it faster?"
+       Enhanced: "What techniques could I use to improve performance in my React app when fetching large datasets from an API? I'm specifically looking for ways to optimize loading times."
+
+    2. History: "I'm building a Django GET API to fetch order details."
+       Query: "My API isn't working. What's wrong?"
+       Enhanced: "My Django GET API for fetching order details isn't working. I'm getting errors when attempting to retrieve the data."
+
+    Output Format:
+    Return ONLY the enhanced query text with no additional commentary or explanation.""",
+    "Enhancer_Prompt": """You are a prompt enhancer. Your primary purpose is to improve user queries by adding context and clarity.
+    Process:
+    1. Enhance the original query using conversation history.
+
+    Input:
+    - Query: {query}
+    - Conversation History: {history}
+
+    Query Enhancement Guidelines:
+    1. Resolve ambiguous references using conversation history
+    2. Incorporate relevant context from previous exchanges
+    3. Maintain factual integrity (no invented information)
+    4. Restructure ambiguous queries by clarifying:
+       - Problem statement
+       - Contextual details
+       - Expected outcome
+
+    Examples:
+    1. History: "I've been working on a React app that fetches data from an API. The data loads slowly when there are many records."
+       Query: "How can I make it faster?"
+       Enhanced: "What techniques could I use to improve performance in my React app when fetching large datasets from an API? I'm specifically looking for ways to optimize loading times."
+
+    2. History: "I'm building a Django GET API to fetch order details."
+       Query: "My API isn't working. What's wrong?"
+       Enhanced: "My Django GET API for fetching order details isn't working. I'm getting errors when attempting to retrieve the data."
+
+    Output Format:
+    Return ONLY the enhanced query text with no additional commentary or explanation.""",
+}


Reviews:
user: login: coderabbitai[bot]
body: **Actionable comments posted: 0**

<details>
<summary>🧹 Nitpick comments (5)</summary><blockquote>

<details>
<summary>app/modules/intelligence/prompts/prompt_schema.py (2)</summary><blockquote>

`91-93`: **Consider adding validation or descriptions to the fields.**

`conversation_id` and `prompt` look correct. However, you could enhance the schema by including `Field` descriptors or minimum length validations to ensure data quality.

---

`96-97`: **Adopt consistent snake_case naming for the response field.**

Currently, `EnhancedPromptResponse` defines the field `enhancedprompt` instead of a typical snake_case name. Consider using `enhanced_prompt` for better readability and consistency with other fields.

```diff
-    enhancedprompt: str
+    enhanced_prompt: str
```

</blockquote></details>
<details>
<summary>app/modules/intelligence/prompts/prompt_router.py (1)</summary><blockquote>

`87-95`: **Consider returning the structured response model instead of raw string.**

You are returning `response_model=str` here, while the service produces `EnhancedPromptResponse`. If you need to preserve a unified schema (e.g., for client usage consistency), returning `EnhancedPromptResponse` instead of a raw string can help with future extensibility.

```diff
 @router.post("/prompts/enhancer", response_model=str)
 async def enhance_prompt(
     request_body: RequestModel,
     db: Session = Depends(get_db),
     user=Depends(AuthService.check_auth),
 ):
-    return await PromptController.enhance_prompt(request_body, db, user)
+    enhanced_prompt_str = await PromptController.enhance_prompt(request_body, db, user)
+    return {"enhancedprompt": enhanced_prompt_str}
```

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 Ruff (0.8.2)</summary>

91-91: Do not perform function call `Depends` in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable

(B008)

---

92-92: Do not perform function call `Depends` in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable

(B008)

</details>

</details>

</blockquote></details>
<details>
<summary>app/modules/intelligence/prompts/prompt_controller.py (1)</summary><blockquote>

`88-148`: **Handle empty or insufficient messages, and consider partial custom-agent scenarios.**

1. If no messages exist or only one is found, the logic gracefully works, but the final enhanced prompt might lack expected context. Consider whether you need a guard clause or fallback behavior when fewer than two messages are retrieved.  
2. The code sets `is_custom_agent` to `True` if *any* agent in `agent_ids` is found in `CustomAgent`. This treats an entire conversation as “custom” if at least one agent ID is custom. If multiple agent IDs exist (both custom and non-custom), you might want to handle them more precisely.

</blockquote></details>
<details>
<summary>app/modules/intelligence/prompts/prompt_service.py (1)</summary><blockquote>

`369-370`: **Fix minor typo in "Curent Agent Id".**

There is a spelling error in the user-message content. Consider applying this fix to maintain clarity:

```diff
-"Curent Agent Id: {inputs['agent_id']}"
+"Current Agent Id: {inputs['agent_id']}"
```

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

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

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between 497d91435e93684ce9962329e4822be8406ed340 and 9779b427d21b9a1dbdd10ee2bda95f3498d9036c.

</details>

<details>
<summary>📒 Files selected for processing (4)</summary>

* `app/modules/intelligence/prompts/prompt_controller.py` (3 hunks)
* `app/modules/intelligence/prompts/prompt_router.py` (3 hunks)
* `app/modules/intelligence/prompts/prompt_schema.py` (1 hunks)
* `app/modules/intelligence/prompts/prompt_service.py` (2 hunks)

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>🪛 Ruff (0.8.2)</summary>

<details>
<summary>app/modules/intelligence/prompts/prompt_router.py</summary>

91-91: Do not perform function call `Depends` in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable

(B008)

---

92-92: Do not perform function call `Depends` in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable

(B008)

</details>

</details>

</details>

<details>
<summary>🔇 Additional comments (5)</summary><blockquote>

<details>
<summary>app/modules/intelligence/prompts/prompt_router.py (2)</summary>

`17-18`: **No issues with the added import.**

The new import for `RequestModel` is clear and purposeful.

---

`91-92`: **Ignore the B008 static analysis warning for FastAPI dependency injection.**

Ruff’s B008 check warns against calling `Depends` in argument defaults, but that is standard and recommended usage in FastAPI.

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 Ruff (0.8.2)</summary>

91-91: Do not perform function call `Depends` in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable

(B008)

---

92-92: Do not perform function call `Depends` in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable

(B008)

</details>

</details>

</details>
<details>
<summary>app/modules/intelligence/prompts/prompt_service.py (3)</summary>

`24-26`: **Additional imports look good.**

These imports for `MessageResponse`, `EnhancedPromptResponse`, and `ProviderService` correctly complement the new functionality.

---

`346-353`: **Overall logic is on point.**

The new `enhance_prompt` signature is clean, with optional `agent_ids` and `available_agents`. Good approach for modular usage.

---

`399-401`: **Fallback behavior is acceptable.**

`get_prompt` returning `"Prompt not found."` if the key is missing is a reasonable fallback.

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-04T00:29:48Z
user: login: dhirenmathur
state: CHANGES_REQUESTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-08T04:43:02Z
user: login: coderabbitai[bot]
body: **Actionable comments posted: 2**

<details>
<summary>🧹 Nitpick comments (4)</summary><blockquote>

<details>
<summary>app/modules/intelligence/prompts/prompt_service.py (4)</summary><blockquote>

`346-353`: **Add type hints to optional parameters for better code clarity.**

The method signature has appropriate parameters, but the optional parameters would benefit from explicit type annotations.


```diff
    async def enhance_prompt(
        self,
        prompt: str,
        last_messages: List[MessageResponse],
        user: dict,
-        agent_ids=None,
-        available_agents=None,
+        agent_ids: Optional[List[str]]=None,
+        available_agents: Optional[List[dict]]=None,
    ) -> str:
```

---

`374-387`: **Consider a more structured approach to message content formatting.**

The f-string construction puts all context in a single string which may affect how the LLM parses the inputs. Consider using a more structured format.


```diff
            messages = [
                {"role": "system", "content": get_prompt("Enhancer_Prompt")},
                {
                    "role": "user",
-                    "content": f"Query: {inputs['query']}\nHistory: {inputs['history']}\n\n",
+                    "content": (
+                        f"Query: {inputs['query']}\n\n"
+                        f"History: {', '.join(inputs['history']) if inputs['history'] else 'No previous conversation'}\n\n"
+                    ),
                },
            ]
```

---

`399-400`: **Improve error handling in the `get_prompt` helper function.**

This helper function returns a generic message when a key isn't found, which could mask errors when using incorrectly specified prompt templates.


```diff
def get_prompt(prompt_key: str) -> str:
-    return PROMPTS.get(prompt_key, "Prompt not found.")
+    if prompt_key not in PROMPTS:
+        logger.warning(f"Prompt template '{prompt_key}' not found in PROMPTS dictionary")
+        return "Prompt not found."
+    return PROMPTS[prompt_key]
```

---

`403-471`: **Well-structured prompt templates but consider modularization.**

The prompt templates are well-designed with clear instructions, but their size makes them harder to maintain. Consider extracting them to separate configuration files.


The prompt templates contain placeholder variables like `{query}` and `{agent_id}`. Ensure these are consistently replaced when used in `enhance_prompt` method. Also, line 406 mentions "INTERNAL STEP ONLY" - make sure the output instructions reinforce that classification results should not be included in the response.

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

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

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between 9779b427d21b9a1dbdd10ee2bda95f3498d9036c and 09bcdcb8e102db76562da4e9cd9c3891789ae065.

</details>

<details>
<summary>📒 Files selected for processing (2)</summary>

* `app/modules/intelligence/prompts/prompt_service.py` (2 hunks)
* `potpie-ui` (1 hunks)

</details>

<details>
<summary>✅ Files skipped from review due to trivial changes (1)</summary>

* potpie-ui

</details>

<details>
<summary>🔇 Additional comments (2)</summary><blockquote>

<details>
<summary>app/modules/intelligence/prompts/prompt_service.py (2)</summary>

`24-26`: **Clean, focused imports for the new functionality.**

The added imports clearly reflect the new dependencies needed for the prompt enhancement feature.

---

`404-423`: **Verify agent selection process doesn't mislead the LLM.**

The agent selection process described in lines 416-422 includes specific numerical weights and confidence scoring. Make sure this doesn't lead the LLM to fabricate data or classifications that aren't actually performed in the code.



This relates to a previous comment about "misleading the LLM to assume stuff that is not in the history." Be cautious that detailed instructions about numerical scoring and weighting can cause the LLM to invent classifications that don't match how your system actually works.

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-08T11:29:44Z
user: login: coderabbitai[bot]
body: **Actionable comments posted: 0**

<details>
<summary>🧹 Nitpick comments (5)</summary><blockquote>

<details>
<summary>app/modules/intelligence/prompts/prompt_service.py (5)</summary><blockquote>

`355-373`: **Improve message formatting for better readability and maintainability.**

The f-string construction in the user content is hard to read and might be error-prone. Consider using a more structured approach with template formatting or multi-line strings.


```diff
-                    "content": f"Query: {inputs['query']}\nHistory: {inputs['history']}\nCurent Agent Id: {inputs['agent_id']}\nAvailable Agents: {inputs['available_agents']}\n\n",
+                    "content": f"""
+Query: {inputs['query']}
+History: {inputs['history']}
+Current Agent Id: {inputs['agent_id']}
+Available Agents: {inputs['available_agents']}
+""",
```

Also note the typo "Curent" which should be "Current".

---

`370-370`: **Fix typo in message template.**

There's a spelling error in "Curent Agent Id" that should be corrected to "Current Agent Id".


```diff
-                    "content": f"Query: {inputs['query']}\nHistory: {inputs['history']}\nCurent Agent Id: {inputs['agent_id']}\nAvailable Agents: {inputs['available_agents']}\n\n",
+                    "content": f"Query: {inputs['query']}\nHistory: {inputs['history']}\nCurrent Agent Id: {inputs['agent_id']}\nAvailable Agents: {inputs['available_agents']}\n\n",
```

---

`374-387`: **Apply the same formatting improvements to the second message template.**

Similar to the previous comment, the message construction in this branch could also benefit from improved formatting.


```diff
-                    "content": f"Query: {inputs['query']}\nHistory: {inputs['history']}\n\n",
+                    "content": f"""
+Query: {inputs['query']}
+History: {inputs['history']}
+""",
```

---

`399-401`: **Improve error handling in get_prompt function.**

The current implementation returns a generic "Prompt not found." message if the key doesn't exist, which could mask issues. Consider raising an exception or logging a warning when a prompt key is not found.


```diff
def get_prompt(prompt_key: str) -> str:
-    return PROMPTS.get(prompt_key, "Prompt not found.")
+    if prompt_key not in PROMPTS:
+        logger.warning(f"Prompt key '{prompt_key}' not found.")
+        return f"Prompt '{prompt_key}' not found."
+    return PROMPTS[prompt_key]
```

---

`415-422`: **Consider adding comments to explain the agent selection process.**

The agent selection process includes confidence scoring and contextual weighting, but there are no comments explaining how these values were determined or should be interpreted.


Add comments to explain:
1. Why specific weights (0.15, 0.1) were chosen for current agent advantage
2. What the confidence scoring thresholds (0.9-1.0, 0.7-0.9, etc.) represent
3. How these values should be adjusted over time if needed

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

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

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between 09bcdcb8e102db76562da4e9cd9c3891789ae065 and e1b311f3d5630ed16824baf079354cb02d66bd35.

</details>

<details>
<summary>📒 Files selected for processing (2)</summary>

* `app/modules/intelligence/prompts/prompt_service.py` (2 hunks)
* `potpie-ui` (1 hunks)

</details>

<details>
<summary>🚧 Files skipped from review as they are similar to previous changes (1)</summary>

* potpie-ui

</details>

<details>
<summary>🔇 Additional comments (3)</summary><blockquote>

<details>
<summary>app/modules/intelligence/prompts/prompt_service.py (3)</summary>

`346-354`: **Add input validation for enhanced security and reliability.**

The method lacks validation for input parameters, which could lead to unexpected behavior or errors. 



Following the recommendation from a previous review, input validation should be added to ensure that the prompt is not empty and to handle cases where no message history is provided.

---

`388-397`: **Add error type specificity and proper error propagation.**

The current exception handling is generic and could benefit from more specific error handling to aid debugging and client error reporting.



As suggested in a previous review, improve the error handling with proper logging and error propagation:

```diff
        try:
            provider_service = ProviderService(self.db, user["user_id"])
            result = await provider_service.call_llm_with_structured_output(
                messages=messages, output_schema=EnhancedPromptResponse, size="large"
            )
            return result.enhancedprompt
        except Exception as e:
-            logger.error(f"Enhancing failed: {e}")
-            raise
+            logger.error(f"Prompt enhancement failed: {e}", exc_info=True)
+            raise PromptServiceError(f"Failed to enhance prompt: {str(e)}") from e
```

---

`404-443`: **Review and remove misleading information in the prompt template.**

A previous review comment pointed out that there are misleading details about "data indexing" in the prompt that don't match the actual context provided to the LLM.


Review the prompt template carefully and ensure that all references (like "data indexing") actually correspond to information that will be provided in the input context. Remove or modify any parts that could mislead the LLM.

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-10T07:52:36Z
user: login: coderabbitai[bot]
body: **Actionable comments posted: 0**

<details>
<summary>🧹 Nitpick comments (6)</summary><blockquote>

<details>
<summary>README.md (6)</summary><blockquote>

`122-127`: **Enhance Submodule Initialization Instructions**  
The new instructions for initializing the UI submodule are clear and concise. However, please adjust the markdown header so that it starts flush left (i.e. without extra indentation) to address markdownlint MD023 warnings.

---

`128-133`: **Improve "Navigate to the `potpie-ui` Directory" Section Formatting**  
This section is much more readable now. To improve consistency and satisfy the markdown heading guidelines, ensure that the heading starts at the very beginning of the line with no preceding spaces.

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 markdownlint-cli2 (0.17.2)</summary>

128-128: Headings must start at the beginning of the line
null

(MD023, heading-start-left)

</details>

</details>

---

`134-140`: **Standardize "Update the Main Branch and Checkout" Heading**  
The instructions in this block are clear. For consistency with markdown best practices (MD023), remove any leading spaces so that the heading begins at the left margin.

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 markdownlint-cli2 (0.17.2)</summary>

134-134: Headings must start at the beginning of the line
null

(MD023, heading-start-left)

</details>

</details>

---

`141-148`: **Refine the "Set Up the Environment" Section Format**  
The directions for setting up the environment are well laid out. As with previous sections, please ensure that the header is aligned at the beginning of the line to eliminate markdownlint MD023 warnings.

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 markdownlint-cli2 (0.17.2)</summary>

141-141: Headings must start at the beginning of the line
null

(MD023, heading-start-left)

</details>

</details>

---

`149-154`: **Align "Build the Frontend" Header Consistently**  
This section is formatted clearly, and the code block is correct. A minor improvement would be to adjust the heading's indentation so that it starts at the left margin, conforming to markdown style guidelines.

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 markdownlint-cli2 (0.17.2)</summary>

149-149: Headings must start at the beginning of the line
null

(MD023, heading-start-left)

</details>

</details>

---

`155-160`: **Refine "Start the Application" Section Heading**  
The instructions to start the application are straightforward. Please modify the heading to start flush left (without leading spaces) to fully comply with markdownlint MD023.

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 markdownlint-cli2 (0.17.2)</summary>

155-155: Headings must start at the beginning of the line
null

(MD023, heading-start-left)

</details>

</details>

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

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

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between e1b311f3d5630ed16824baf079354cb02d66bd35 and 271fa05dcbcdfbdaaa24dd6c6643f47a5f114c37.

</details>

<details>
<summary>📒 Files selected for processing (1)</summary>

* `README.md` (1 hunks)

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>🪛 markdownlint-cli2 (0.17.2)</summary>

<details>
<summary>README.md</summary>

128-128: Headings must start at the beginning of the line
null

(MD023, heading-start-left)

---

134-134: Headings must start at the beginning of the line
null

(MD023, heading-start-left)

---

141-141: Headings must start at the beginning of the line
null

(MD023, heading-start-left)

---

149-149: Headings must start at the beginning of the line
null

(MD023, heading-start-left)

---

155-155: Headings must start at the beginning of the line
null

(MD023, heading-start-left)

</details>

</details>

</details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-10T08:03:43Z
user: login: dhirenmathur
state: APPROVED
author_association: CONTRIBUTOR
submitted_at: 2025-03-10T08:18:21Z

Review comments:
diff_hunk: @@ -74,3 +84,64 @@ async def list_prompts(
             return await prompt_service.list_prompts(query, skip, limit, user_id)
         except PromptServiceError as e:
             raise HTTPException(status_code=500, detail=str(e))
+
+    @staticmethod
+    async def enhance_prompt(
+        request_body: RequestModel,
+        db: Session,
+        user: dict,
+    ) -> str:
+
+        messages = (
+            db.query(Message)
+            .filter_by(conversation_id=request_body.conversation_id)
+            .filter_by(status=MessageStatus.ACTIVE)
+            .order_by(Message.created_at.desc())
+            .limit(2)
+            .all()
+        )
+
+        # to get them in chronological order
+        messages.reverse()
path: app/modules/intelligence/prompts/prompt_controller.py
user: login: dhirenmathur
body: nice
created_at: 2025-03-08T04:39:27Z
author_association: CONTRIBUTOR
diff_hunk: @@ -338,3 +342,130 @@ async def get_prompts_by_agent_id_and_types(
             raise PromptServiceError(
                 "Failed to get prompts by agent ID and types"
             ) from e
+
+    async def enhance_prompt(
+        self,
+        prompt: str,
+        last_messages: List[MessageResponse],
+        user: dict,
+        agent_ids=None,
+        available_agents=None,
+    ) -> str:
+
+        if agent_ids and available_agents:
+            inputs = {
+                "query": prompt,
+                "history": [msg.content for msg in last_messages],
+                "agent_id": agent_ids,
+                "available_agents": available_agents,
+            }
+
+            messages = [
+                {
+                    "role": "system",
+                    "content": get_prompt("Enhancer_Prompt_With_Classification"),
+                },
+                {
+                    "role": "user",
+                    "content": f"Query: {inputs['query']}\nHistory: {inputs['history']}\nCurent Agent Id: {inputs['agent_id']}\nAvailable Agents: {inputs['available_agents']}\n\n",
+                },
+            ]
+
+        else:
+            inputs = {
+                "query": prompt,
+                "history": [msg.content for msg in last_messages],
+            }
+
+            messages = [
+                {"role": "system", "content": get_prompt("Enhancer_Prompt")},
+                {
+                    "role": "user",
+                    "content": f"Query: {inputs['query']}\nHistory: {inputs['history']}\n\n",
+                },
+            ]
+
+        try:
+            provider_service = ProviderService(self.db, user["user_id"])
+            result = await provider_service.call_llm_with_structured_output(
+                messages=messages, output_schema=EnhancedPromptResponse, size="large"
+            )
+            return result.enhancedprompt
+        except Exception as e:
+            logger.error(f"Enhancing failed: {e}")
+            raise
+
+
+def get_prompt(prompt_key: str) -> str:
+    return PROMPTS.get(prompt_key, "Prompt not found.")
+
+
+PROMPTS = {
+    "Enhancer_Prompt_With_Classification": """You are a prompt enhancer. Your primary purpose is to improve user queries by adding context and clarity.
+    Process:
+    1. INTERNAL STEP ONLY: Classify the most appropriate agent based on the query and agent descriptions. This classification is only to help you understand which expertise domain to enhance the prompt for.
+    2. Enhance the original query using conversation history and the relevant expertise domain identified in step 1.
+
+    Input:
+    - Query: {query}
+    - Current Agent ID: {agent_id}
+    - Conversation History: {history}
+    - Available Agents: {agent_descriptions}
+
+    Agent Selection Process:
+    1. Identify key topics, technical terms, and user intent from the query
+    2. Compare query elements against each agent's specialty description
+    3. Apply contextual weighting:
+       - Current agent advantage: +0.15 for direct expertise, +0.1 for related knowledge
+       - For new topics outside current agent's domain, evaluate all agents equally
+    4. Use confidence scoring (0.9-1.0: ideal match, 0.7-0.9: strong match, 0.5-0.7: partial match, <0.5: weak match)
+
+    Query Enhancement Guidelines:
+    1. Resolve ambiguous references using conversation history
+    2. Incorporate relevant context from previous exchanges
+    3. Maintain factual integrity (no invented information)
+    4. Restructure ambiguous queries by clarifying:
+       - Problem statement
+       - Contextual details
+       - Expected outcome
+
+    Examples:
+    1. History: "I need to fetch total sales per month from my PostgreSQL sales table."
+       Query: "My query is slow. Fix it."
+       Enhanced: "My PostgreSQL query for monthly sales is slow. I indexed date, but it's still lagging. Would partitioning help?"
path: app/modules/intelligence/prompts/prompt_service.py
user: login: dhirenmathur
body: where does the data indexing details come from? You are misleading the LLM to assume stuff that is not in the history. 
created_at: 2025-03-08T04:42:20Z
author_association: CONTRIBUTOR
diff_hunk: @@ -338,3 +342,130 @@ async def get_prompts_by_agent_id_and_types(
             raise PromptServiceError(
                 "Failed to get prompts by agent ID and types"
             ) from e
+
+    async def enhance_prompt(
+        self,
+        prompt: str,
+        last_messages: List[MessageResponse],
+        user: dict,
+        agent_ids=None,
+        available_agents=None,
+    ) -> str:
+
+        if agent_ids and available_agents:
+            inputs = {
+                "query": prompt,
+                "history": [msg.content for msg in last_messages],
+                "agent_id": agent_ids,
+                "available_agents": available_agents,
+            }
+
+            messages = [
+                {
+                    "role": "system",
+                    "content": get_prompt("Enhancer_Prompt_With_Classification"),
+                },
+                {
+                    "role": "user",
+                    "content": f"Query: {inputs['query']}\nHistory: {inputs['history']}\nCurent Agent Id: {inputs['agent_id']}\nAvailable Agents: {inputs['available_agents']}\n\n",
+                },
+            ]
+
+        else:
+            inputs = {
+                "query": prompt,
+                "history": [msg.content for msg in last_messages],
+            }
+
+            messages = [
+                {"role": "system", "content": get_prompt("Enhancer_Prompt")},
+                {
+                    "role": "user",
+                    "content": f"Query: {inputs['query']}\nHistory: {inputs['history']}\n\n",
+                },
+            ]
+
+        try:
+            provider_service = ProviderService(self.db, user["user_id"])
+            result = await provider_service.call_llm_with_structured_output(
+                messages=messages, output_schema=EnhancedPromptResponse, size="large"
+            )
+            return result.enhancedprompt
+        except Exception as e:
+            logger.error(f"Enhancing failed: {e}")
+            raise
+
path: app/modules/intelligence/prompts/prompt_service.py
user: login: coderabbitai[bot]
body: _🛠️ Refactor suggestion_

**Add error type specificity and proper error propagation.**

The current exception handling is generic and could benefit from more specific error handling to aid debugging and client error reporting.


```diff
        try:
            provider_service = ProviderService(self.db, user["user_id"])
            result = await provider_service.call_llm_with_structured_output(
                messages=messages, output_schema=EnhancedPromptResponse, size="large"
            )
            return result.enhancedprompt
        except Exception as e:
-            logger.error(f"Enhancing failed: {e}")
-            raise
+            logger.error(f"Prompt enhancement failed: {e}", exc_info=True)
+            raise PromptServiceError(f"Failed to enhance prompt: {str(e)}") from e
```


<!-- suggestion_start -->

<details>
<summary>📝 Committable suggestion</summary>

> ‼️ **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.

`````suggestion
        try:
            provider_service = ProviderService(self.db, user["user_id"])
            result = await provider_service.call_llm_with_structured_output(
                messages=messages, output_schema=EnhancedPromptResponse, size="large"
            )
            return result.enhancedprompt
        except Exception as e:
            logger.error(f"Prompt enhancement failed: {e}", exc_info=True)
            raise PromptServiceError(f"Failed to enhance prompt: {str(e)}") from e
`````

</details>

<!-- suggestion_end -->

<!-- This is an auto-generated comment by CodeRabbit -->
created_at: 2025-03-08T11:29:43Z
author_association: CONTRIBUTOR
diff_hunk: @@ -338,3 +342,130 @@
             raise PromptServiceError(
                 "Failed to get prompts by agent ID and types"
             ) from e
+
+    async def enhance_prompt(
+        self,
+        prompt: str,
+        last_messages: List[MessageResponse],
+        user: dict,
+        agent_ids=None,
+        available_agents=None,
+    ) -> str:
+
+        if agent_ids and available_agents:
+            inputs = {
+                "query": prompt,
+                "history": [msg.content for msg in last_messages],
+                "agent_id": agent_ids,
+                "available_agents": available_agents,
+            }
+
+            messages = [
+                {
+                    "role": "system",
+                    "content": get_prompt("Enhancer_Prompt_With_Classification"),
+                },
+                {
+                    "role": "user",
+                    "content": f"Query: {inputs['query']}\nHistory: {inputs['history']}\nCurent Agent Id: {inputs['agent_id']}\nAvailable Agents: {inputs['available_agents']}\n\n",
+                },
+            ]
+
path: app/modules/intelligence/prompts/prompt_service.py
user: login: coderabbitai[bot]
body: _🛠️ Refactor suggestion_

**Add input validation for enhanced security and reliability.**

The code assumes inputs will always be in the expected format. Missing validation for empty or incorrect inputs could lead to unpredictable behavior.


```diff
+        if not prompt.strip():
+            raise ValueError("Empty prompt cannot be enhanced")
+
+        if not last_messages:
+            logger.warning("No message history provided for prompt enhancement")
+
         if agent_ids and available_agents:
             inputs = {
                 "query": prompt,
                 "history": [msg.content for msg in last_messages],
```


<!-- suggestion_start -->

<details>
<summary>📝 Committable suggestion</summary>

> ‼️ **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.

`````suggestion
        if not prompt.strip():
            raise ValueError("Empty prompt cannot be enhanced")

        if not last_messages:
            logger.warning("No message history provided for prompt enhancement")

        if agent_ids and available_agents:
            inputs = {
                "query": prompt,
                "history": [msg.content for msg in last_messages],
                "agent_id": agent_ids,
                "available_agents": available_agents,
            }

            messages = [
                {
                    "role": "system",
                    "content": get_prompt("Enhancer_Prompt_With_Classification"),
                },
                {
                    "role": "user",
                    "content": f"Query: {inputs['query']}\nHistory: {inputs['history']}\nCurent Agent Id: {inputs['agent_id']}\nAvailable Agents: {inputs['available_agents']}\n\n",
                },
            ]
`````

</details>

<!-- suggestion_end -->

<!-- This is an auto-generated comment by CodeRabbit -->
created_at: 2025-03-08T11:29:44Z
author_association: CONTRIBUTOR

PR comments:
user: login: coderabbitai[bot]
created_at: 2025-03-04T00:25:50Z
body: <!-- This is an auto-generated comment: summarize by coderabbit.ai -->
<!-- walkthrough_start -->

## Walkthrough
This pull request introduces a prompt enhancement capability that leverages context from recent conversation messages and available agent information. A new static method is added to the controller to retrieve the last two active messages, check for custom agents, and delegate the prompt enhancement to the service layer. A corresponding API endpoint is added in the router to expose this functionality. New schema models support the request and response payloads, and the prompt service is enhanced with a method for constructing prompt messages. Minor documentation formatting updates are also included.

## Changes

| File(s)                                                          | Change Summary                                                                                                                                                                                                                                                                                                                                                       |
|------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `app/modules/intelligence/prompts/prompt_controller.py`<br>`app/modules/intelligence/prompts/prompt_router.py`  | Added new methods for prompt enhancement. The controller now includes a static `enhance_prompt` method that retrieves conversation messages, determines agent availability, and calls the prompt service; the router exposes this via a new POST endpoint `/prompts/enhancer`.                                                                           |
| `app/modules/intelligence/prompts/prompt_schema.py`              | Introduced two new schema classes: `RequestModel` (with `conversation_id` and `prompt`) and `EnhancedPromptResponse` (with `enhancedprompt`) to standardize request and response structures for the new feature.                                                                                                     |
| `app/modules/intelligence/prompts/prompt_service.py`             | Added an asynchronous `enhance_prompt` method in the service to build enhanced prompts using conversation history and agent details. Also added a helper function `get_prompt` to retrieve prompt templates from a defined dictionary.                                                                              |
| `README.md`                                                      | Re-formatted indentation for instructions related to initializing the Potpie UI submodule to ensure a consistent and clearer presentation.                                                                                                                                                                                  |

## Sequence Diagram(s)
```mermaid
sequenceDiagram
    participant C as Client
    participant R as PromptAPI (Router)
    participant PC as PromptController
    participant AS as AgentsService
    participant PS as PromptService
    participant PSrv as ProviderService

    C->>R: POST /prompts/enhancer (RequestModel payload)
    R->>PC: enhance_prompt(request_body, db, user)
    PC->>Database: Retrieve last 2 active messages (by conversation_id)
    PC->>AS: Fetch available agents & check for custom agent
    alt Custom agent found
        PC->>PS: enhance_prompt(prompt, last_messages, user)
    else No custom agent
        PC->>PS: enhance_prompt(prompt, last_messages, user, agent_ids, available_agents)
    end
    PS->>PSrv: Process request with language model
    PSrv-->>PS: Return enhanced prompt
    PS-->>PC: Return enhanced prompt
    PC-->>R: Return enhanced prompt
    R-->>C: Response with enhanced prompt
```

## Possibly related PRs
- **potpie-ai/potpie#297**: Implements similar enhancement logic by introducing an `enhance_prompt` method in the PromptController, directly related to the new endpoint.
- **potpie-ai/potpie#210**: Contains prompt enhancement functionality that aligns with the controller's new method and router endpoint.
- **potpie-ai/potpie#270**: Involves changes in both PromptController and PromptService that are leveraged by the new prompt enhancement API endpoint.

## Suggested reviewers
- **dhirenmathur**

## Poem
> I hop through lines of code so fine,  
> Enhancing prompts with context divine.  
> Messages reversed and agents in view,  
> A seamless code dance, refreshingly new.  
> With every hop, our logic shines bright—  
> Celebrating changes with rabbit delight! 🐇✨

<!-- walkthrough_end -->
<!-- internal state start -->


<!-- DwQgtGAEAqAWCWBnSTIEMB26CuAXA9mAOYCmGJATmriQCaQDG+Ats2bgFyQAOFk+AIwBWJBrngA3EsgEBPRvlqU0AgfFwA6NPEgQAfACgjoCEejqANiS68W3XJDKxMDeBiKQAZtgx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aI0ayLQiTtQr5mZOXNISbrIYqgKc7tJoLCyCLFgEcEoJ9P9PIPLsdCOZuEqQhegI4RSPrEwSEKVg4RVtJjiT3EwXVp4Rilar4XajXI6ogB1v+UEKRQauRTVu4WatRY1vwM1n4QxdZoIktGKJJgKe+LAbuJ4LTDceAvcNMOTHUF5HgEsJDnOOsFiVwLsJSCQgemcMMMoGMNcJMHcAYApdLOoHUagp2B2DsHQKti2Q4JUGZdUJAPEAAOzuXxACAAAssQ7ltAsQAAjAIPEGgEFYvAzEFQAAwqmxACBRhJCeAADMPl8QAAHLQPENFclQAGyihTCuXRXeUMC0AMACDpUkAxWxCLzuW5WJC5U1VoA+UkDxClVtXJXpXxBBXuVdVoAkDRX1W3CGAKVVUCDJVBVBUpW0ANXJWxW0BBW5XpWxA+UjKeDRVeXJWJA+XlXRU1W5W5UJVbXDUuUQCQD+VTVoDRWJBlUCClWeAJVoBPUrUMz5UHU+XJWeA+XuVoCJCeCTU7XJXuUnWnVQAWXjwPiIDWVsSKL2W1DDVAA= -->

<!-- internal state end -->
<!-- tips_start -->

---



<details>
<summary>🪧 Tips</summary>

### Chat

There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=potpie-ai/potpie&utm_content=295):

- 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](https://docs.coderabbit.ai/finishing-touches/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](https://docs.coderabbit.ai/guides/configure-coderabbit) 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](https://docs.coderabbit.ai) for detailed information on how to use CodeRabbit.
- Join our [Discord Community](http://discord.gg/coderabbit) to get help, request features, and share feedback.
- Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.

</details>

<!-- tips_end -->
author_association: CONTRIBUTOR
user: login: sonarqubecloud[bot]
created_at: 2025-03-10T08:01:52Z
body: ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=getmomentum_momentum-server&pullRequest=295) **Quality Gate passed**  
Issues  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 New issues](https://sonarcloud.io/project/issues?id=getmomentum_momentum-server&pullRequest=295&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=getmomentum_momentum-server&pullRequest=295&issueStatuses=ACCEPTED)

Measures  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=getmomentum_momentum-server&pullRequest=295&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=getmomentum_momentum-server&pullRequest=295&metric=new_coverage&view=list)  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Duplication on New Code](https://sonarcloud.io/component_measures?id=getmomentum_momentum-server&pullRequest=295&metric=new_duplicated_lines_density&view=list)  
  
[See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=getmomentum_momentum-server&pullRequest=295)


author_association: NONE