-
Notifications
You must be signed in to change notification settings - Fork 68
Rca prompt v2 comparison #457
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
Merged
Merged
Changes from 6 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
cd3e545
using raw webhook instead of parsing it
OlivierTrudeau 3a0409b
One consolidated build_rca_prompt method
OlivierTrudeau ffa30fc
rebase
OlivierTrudeau 2f74483
better system over 15k chars
OlivierTrudeau 17bf4fe
update
OlivierTrudeau fa77db0
comments
OlivierTrudeau 9875d04
boumn
OlivierTrudeau 47d2a34
address comments
OlivierTrudeau c0a77bc
fix
OlivierTrudeau be273bb
even larger limit
OlivierTrudeau 209f2e0
address coderabbit
OlivierTrudeau File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,187 @@ | ||
| """ | ||
| Alert Payload Drill-Down Tool | ||
|
|
||
| Retrieves full (untruncated) field values from the stored webhook payload. | ||
| Used by the RCA agent when the initial prompt contained a truncated payload | ||
| and the agent needs to inspect a specific field in full. | ||
| """ | ||
|
|
||
| import json | ||
| import logging | ||
| from datetime import timedelta | ||
| from typing import Any, Dict, Optional, Tuple | ||
|
|
||
| from pydantic import BaseModel, Field | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| _SOURCE_TABLE_MAP = { | ||
| "grafana": "grafana_alerts", | ||
| "datadog": "datadog_events", | ||
| "newrelic": "newrelic_events", | ||
| "pagerduty": "pagerduty_events", | ||
| "opsgenie": "opsgenie_events", | ||
| "sentry": "sentry_events", | ||
| "splunk": "splunk_alerts", | ||
| "dynatrace": "dynatrace_problems", | ||
| "bigpanda": "bigpanda_events", | ||
| "netdata": "netdata_alerts", | ||
| "incidentio": "incidentio_alerts", | ||
| "jenkins": "jenkins_deployment_events", | ||
| "cloudbees": "jenkins_deployment_events", | ||
| "spinnaker": "spinnaker_deployment_events", | ||
| } | ||
|
|
||
| _PAYLOAD_LOOKUP_WINDOW = timedelta(minutes=10) | ||
|
|
||
|
|
||
| class GetAlertFieldArgs(BaseModel): | ||
| json_path: str = Field( | ||
| description=( | ||
| "Dot-separated path to the field in the webhook payload. " | ||
| "Use numeric indices for arrays. " | ||
| "Examples: 'alerts.0.labels', 'event.incident.summary', 'results.0'" | ||
| ) | ||
| ) | ||
|
|
||
|
|
||
| GET_ALERT_FIELD_DESCRIPTION = ( | ||
| "Retrieve the full (untruncated) value of a field from the original webhook payload. " | ||
| "Use when the RCA prompt shows a truncated field you need to inspect fully. " | ||
| "Provide a dot-separated JSON path (e.g. 'event.incident.custom_field_entries', 'alerts.0.annotations')." | ||
| ) | ||
|
|
||
|
|
||
| def _validate_inputs(json_path: str, user_id: Optional[str], incident_id: Optional[str]) -> Optional[str]: | ||
| """Validate required inputs; returns an error string or None if valid.""" | ||
| if not user_id: | ||
| return "Error: User authentication required." | ||
| if not incident_id: | ||
| return "Error: No incident context. This tool is only available during RCA investigations." | ||
| if not json_path or not json_path.strip(): | ||
| return "Error: json_path is required. Provide a dot-separated path like 'event.incident.summary'." | ||
| return None | ||
|
|
||
|
|
||
| def _fetch_payload(cursor, conn, incident_id: str, user_id: str) -> Tuple[Optional[Any], Optional[str]]: | ||
| """Fetch the raw payload for an incident. Returns (payload_dict, error_string).""" | ||
| from utils.auth.stateless_auth import set_rls_context | ||
|
|
||
| set_rls_context(cursor, conn, user_id, log_prefix="[GetAlertField]") | ||
|
|
||
| cursor.execute( | ||
| "SELECT source_type, source_alert_id, created_at FROM incidents WHERE id = %s", | ||
| (incident_id,), | ||
| ) | ||
| row = cursor.fetchone() | ||
| if not row: | ||
| return None, f"Error: Incident {incident_id} not found." | ||
|
|
||
| source_type, source_alert_id, incident_created_at = row[0], row[1], row[2] | ||
| table = _SOURCE_TABLE_MAP.get(source_type) | ||
| if not table: | ||
| return None, f"Error: Unknown source type '{source_type}'. Cannot look up payload." | ||
|
|
||
| # Primary: direct ID lookup | ||
| cursor.execute( | ||
| f"SELECT payload FROM {table} WHERE id = %s", | ||
| (source_alert_id,), | ||
| ) | ||
| payload_row = cursor.fetchone() | ||
|
|
||
| # Fallback: time-window constrained lookup around incident creation | ||
| if not payload_row or not payload_row[0]: | ||
| if incident_created_at: | ||
| window_start = incident_created_at - _PAYLOAD_LOOKUP_WINDOW | ||
| window_end = incident_created_at + _PAYLOAD_LOOKUP_WINDOW | ||
| cursor.execute( | ||
| f"SELECT payload FROM {table} " | ||
| f"WHERE user_id = %s AND received_at BETWEEN %s AND %s " | ||
| f"ORDER BY received_at DESC LIMIT 1", | ||
| (user_id, window_start, window_end), | ||
| ) | ||
| payload_row = cursor.fetchone() | ||
|
|
||
| if not payload_row or not payload_row[0]: | ||
| return None, f"Error: No payload found in {table} for source_alert_id {source_alert_id}." | ||
|
|
||
| payload = payload_row[0] | ||
| if isinstance(payload, str): | ||
| payload = json.loads(payload) | ||
|
|
||
| return payload, None | ||
|
|
||
|
|
||
| def _traverse_path(payload: Any, json_path: str) -> Tuple[Optional[Any], Optional[str]]: | ||
|
Check failure on line 115 in server/chat/backend/agent/tools/alert_payload_tool.py
|
||
| """Walk a dot-separated path through the payload. Returns (value, error_string).""" | ||
| path_parts = json_path.strip().split(".") | ||
| current = payload | ||
| for part in path_parts: | ||
| if current is None: | ||
| return None, f"Error: Path '{json_path}' not found. Value is null at '{part}'." | ||
| if isinstance(current, dict): | ||
| if part in current: | ||
| current = current[part] | ||
| else: | ||
| available = list(current.keys())[:20] | ||
| return None, ( | ||
| f"Error: Key '{part}' not found at this level.\n" | ||
| f"Available keys: {available}" | ||
| ) | ||
| elif isinstance(current, list): | ||
| try: | ||
| idx = int(part) | ||
| except ValueError: | ||
| return None, f"Error: Expected numeric index for list, got '{part}'." | ||
| if 0 <= idx < len(current): | ||
| current = current[idx] | ||
| else: | ||
| return None, f"Error: Index {idx} out of range (list has {len(current)} items)." | ||
| else: | ||
| return None, f"Error: Cannot traverse into {type(current).__name__} at '{part}'." | ||
| return current, None | ||
|
|
||
|
|
||
| def _format_output(value: Any) -> str: | ||
| """Serialize and truncate the extracted value for tool output.""" | ||
| from chat.backend.constants import MAX_TOOL_OUTPUT_CHARS | ||
|
|
||
| if isinstance(value, (dict, list)): | ||
| result = json.dumps(value, ensure_ascii=False, default=str, indent=2) | ||
| else: | ||
| result = str(value) if value is not None else "null" | ||
|
|
||
| if len(result) > MAX_TOOL_OUTPUT_CHARS: | ||
| result = result[:MAX_TOOL_OUTPUT_CHARS] + "\n... [output truncated]" | ||
| return result | ||
|
|
||
|
|
||
| def get_alert_field( | ||
| json_path: str, | ||
| user_id: Optional[str] = None, | ||
| incident_id: Optional[str] = None, | ||
| **kwargs, | ||
| ) -> str: | ||
| """Retrieve a specific field from the stored webhook payload.""" | ||
| error = _validate_inputs(json_path, user_id, incident_id) | ||
| if error: | ||
| return error | ||
|
|
||
| from utils.db.connection_pool import db_pool | ||
|
|
||
| try: | ||
| with db_pool.get_admin_connection() as conn: | ||
| with conn.cursor() as cursor: | ||
| payload, err = _fetch_payload(cursor, conn, incident_id, user_id) | ||
| if err: | ||
| return err | ||
|
|
||
| value, err = _traverse_path(payload, json_path) | ||
| if err: | ||
| return err | ||
|
|
||
| return _format_output(value) | ||
|
|
||
| except Exception as e: | ||
| logger.exception("[GetAlertField] Error retrieving field: %s", e) | ||
| return f"Error retrieving alert field: {e}" | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.