File size: 8,993 Bytes
d545f81
 
 
 
3cdce90
d545f81
 
3cdce90
d545f81
3cdce90
 
d545f81
 
3cdce90
 
 
 
d545f81
 
 
 
 
3cdce90
d545f81
 
 
 
 
3cdce90
 
 
 
d545f81
 
3cdce90
 
d545f81
 
3cdce90
d545f81
 
 
 
 
 
3cdce90
d545f81
 
 
3cdce90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d545f81
 
 
 
 
3cdce90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d545f81
 
 
3cdce90
d545f81
 
3cdce90
 
 
 
 
 
 
 
d545f81
 
3cdce90
d545f81
 
 
 
 
 
 
 
 
 
3cdce90
 
 
d545f81
 
 
 
3cdce90
 
 
 
 
 
 
d545f81
 
3cdce90
d545f81
 
 
 
 
3cdce90
d545f81
3cdce90
 
 
 
 
 
 
 
 
d545f81
3cdce90
d545f81
 
 
 
 
 
 
3cdce90
 
 
d545f81
 
3cdce90
 
 
 
 
 
 
d545f81
 
3cdce90
d545f81
 
 
 
 
 
 
 
3cdce90
 
d545f81
 
3cdce90
d545f81
 
 
 
3cdce90
 
 
 
 
 
 
 
 
 
d545f81
3cdce90
d545f81
3cdce90
d545f81
 
 
 
 
 
 
 
3cdce90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
"""
Logging module for XENO Bot
Handles Google Sheets logging for responses and timing data
"""

import json
import os
import threading
from datetime import datetime
from typing import Dict, List, Optional, Tuple

import gspread
from google.oauth2.service_account import Credentials

from src.config import (FEEDBACK_SHEET_NAME, GOOGLE_SHEETS_CREDENTIALS_ENV,
                        RESPONSE_SHEET_INDEX, SPREADSHEET_NAME,
                        TIMING_SHEET_NAME)


def get_google_sheets_credentials() -> Credentials:
    """
    Get Google Sheets credentials from environment variable

    Returns:
        Google Sheets credentials object
    """
    credentials_json = os.environ.get(GOOGLE_SHEETS_CREDENTIALS_ENV)
    if not credentials_json:
        raise ValueError(
            f"{GOOGLE_SHEETS_CREDENTIALS_ENV} environment variable not set."
        )

    credentials_dict = json.loads(credentials_json)
    scope = [
        "https://spreadsheets.google.com/feeds",
        "https://www.googleapis.com/auth/drive",
    ]
    creds = Credentials.from_service_account_info(credentials_dict, scopes=scope)

    return creds


def initialize_sheets():
    """
    Initialize Google Sheets client and get sheets

    Returns:
        Tuple of (response_sheet, timing_sheet)
    """
    try:
        client_gspread = gspread.authorize(get_google_sheets_credentials())
        spreadsheet = client_gspread.open(SPREADSHEET_NAME)

        # Get response sheet
        response_sheet = spreadsheet.get_worksheet(RESPONSE_SHEET_INDEX)
    except Exception as e:
        print(f"Failed to initialize Google Sheets: {e}")

        # TODO Create dummy sheets or handle error appropriately
        class DummySheet:
            def append_row(self, *args, **kwargs):
                pass

            def worksheet(self, *args):
                return self

            def add_worksheet(self, *args, **kwargs):
                return self

        spreadsheet = DummySheet()
        response_sheet = DummySheet()

    # Get or create timing sheet
    try:
        timing_sheet = spreadsheet.worksheet(TIMING_SHEET_NAME)
    except:
        # Create timing sheet if it doesn't exist
        try:
            timing_sheet = spreadsheet.add_worksheet(
                title=TIMING_SHEET_NAME, rows=1000, cols=15
            )
            # Add headers
            headers = [
                "Timestamp",
                "Session_ID",
                "Question",
                "Total_Time_MS",
                "Intent_Classification_MS",
                "Memory_Retrieval_MS",
                "RAG_Retrieval_MS",
                "Embedding_Generation_MS",
                "Similarity_Calculation_MS",
                "Context_Processing_MS",
                "LLM_Generation_MS",
                "Memory_Update_MS",
                "Logging_MS",
                "Error_Step",
                "Notes",
            ]
            timing_sheet.append_row(headers)
        except Exception as e:
            print(f"Failed to create timing sheet: {e}")
            timing_sheet = DummySheet()

    # Feedback Sheet
    try:
        feedback_sheet = spreadsheet.worksheet(FEEDBACK_SHEET_NAME)
    except:
        try:
            feedback_sheet = spreadsheet.add_worksheet(
                title=FEEDBACK_SHEET_NAME, rows=1000, cols=6
            )
            headers = [
                "Timestamp",
                "Session_ID",
                "User_Message",
                "Bot_Response",
                "Rating",
                "Flag_Reason",
            ]
            feedback_sheet.append_row(headers)
        except Exception as e:
            print(f"Failed to create feedback sheet: {e}")
            feedback_sheet = DummySheet()

    return response_sheet, timing_sheet, feedback_sheet


# Initialize sheets
response_sheet, timing_sheet, feedback_sheet = initialize_sheets()


def log_response(
    question: str,
    answer: str,
    source_ids: str,
    knowledge_pairs: List[Tuple[str, str]],
    session_id: str,
    timer=None,
):
    """
    Log response to Google Sheets

    Args:
        question: User's question
        answer: Generated answer
        source_ids: Source IDs used
        knowledge_pairs: Knowledge base Q&A pairs used
        session_id: Session identifier
        timer: Optional timer object for tracking
    """
    if timer:
        with timer.time_step("response_logging"):
            _log_response_impl(
                question, answer, source_ids, knowledge_pairs, session_id
            )
    else:
        _log_response_impl(question, answer, source_ids, knowledge_pairs, session_id)


def _log_response_impl(
    question: str,
    answer: str,
    source_ids: str,
    knowledge_pairs: List[Tuple[str, str]],
    session_id: str,
):
    """Internal implementation of response logging"""
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    # Extract knowledge pairs
    knowledge_question_1 = knowledge_pairs[0][0] if len(knowledge_pairs) > 0 else "N/A"
    knowledge_answer_1 = knowledge_pairs[0][1] if len(knowledge_pairs) > 0 else "N/A"
    knowledge_question_2 = knowledge_pairs[1][0] if len(knowledge_pairs) > 1 else "N/A"
    knowledge_answer_2 = knowledge_pairs[1][1] if len(knowledge_pairs) > 1 else "N/A"

    row = [
        timestamp,
        session_id,
        question,
        answer,
        source_ids,
        knowledge_question_1,
        knowledge_answer_1,
        knowledge_question_2,
        knowledge_answer_2,
    ]

    try:
        response_sheet.append_row(row)
        print(f"Logged response: {question} | Source IDs: {source_ids}")
    except Exception as e:
        print(f"Failed to log to Google Sheet: {e}")
        # Fallback to local file
        with open("/tmp/response_log.txt", "a") as f:
            f.write(
                f"{timestamp},{question},{answer},{source_ids},{knowledge_question_1},{knowledge_answer_1},{knowledge_question_2},{knowledge_answer_2}\n"
            )


def log_timing_data(
    question: str,
    session_id: str,
    timing_summary: Dict,
    error_step: Optional[str] = None,
    notes: Optional[str] = None,
):
    """
    Log timing data to Google Sheets

    Args:
        question: User's question
        session_id: Session identifier
        timing_summary: Timing summary dictionary
        error_step: Step where error occurred (if any)
        notes: Additional notes
    """
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    step_times = timing_summary["step_times"]

    # Truncate long questions
    truncated_question = question[:100] + "..." if len(question) > 100 else question

    row = [
        timestamp,
        session_id,
        truncated_question,
        timing_summary["total_time_ms"],
        step_times.get("intent_classification", 0),
        step_times.get("memory_retrieval", 0),
        step_times.get("rag_retrieval", 0),
        step_times.get("embedding_generation", 0),
        step_times.get("similarity_calculation", 0),
        step_times.get("context_processing", 0),
        step_times.get("llm_generation", 0),
        step_times.get("memory_update", 0),
        step_times.get("response_logging", 0),
        error_step or "",
        notes or "",
    ]

    try:
        timing_sheet.append_row(row)
        print(f"Logged timing data: Total {timing_summary['total_time_ms']}ms")
    except Exception as e:
        print(f"Failed to log timing data: {e}")
        # Fallback to local file
        with open("/tmp/timing_log.txt", "a") as f:
            f.write(f"{timestamp},{session_id},{question},{timing_summary}\n")


def _log_feedback_background(row):
    """Helper to run network request in background thread"""
    try:
        if feedback_sheet:
            feedback_sheet.append_row(row)
            print("Feedback logged successfully.")
        else:
            print("Feedback sheet not available.")
    except Exception as e:
        print(f"Failed to log feedback: {e}")


def log_feedback(rating, reason, history, session_id):
    """
    Handles user feedback submission.
    rating: 'Positive' or 'Negative'
    reason: User provided text
    history: Gradio chat history list
    """
    if not history or len(history) == 0:
        return "No conversation to rate yet."

    # Get the last interaction (Gradio history is a list of lists: [[user, bot], ...])
    last_interaction = history[-1]

    # Safety check for history format
    if isinstance(last_interaction, list) and len(last_interaction) >= 2:
        user_msg = last_interaction[0]
        bot_msg = last_interaction[1]
    else:
        return "Error reading conversation history."

    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    # Prepare row data
    row = [timestamp, session_id, user_msg, bot_msg, rating, reason]

    # Run in thread to prevent UI blocking
    threading.Thread(target=_log_feedback_background, args=(row,)).start()

    return f"Feedback received ({rating}). Thank you!"