daniel-simeone commited on
Commit
49fdc18
·
1 Parent(s): 080bb85

add logging

Browse files
Files changed (1) hide show
  1. app.py +29 -16
app.py CHANGED
@@ -104,21 +104,25 @@ class RAGChatbot:
104
 
105
  # Initialize Inference API client
106
  hf_token = os.environ.get("HF_TOKEN")
 
107
  if not hf_token:
 
108
  print("Warning: HF_TOKEN not set. Inference API calls may fail.")
109
  print("Set HF_TOKEN environment variable or add it to Space secrets.")
110
  else:
 
 
111
  print("HF_TOKEN found. Inference API ready.")
112
 
113
- print(f"Initializing Inference API client for model: {model_name}")
114
  try:
115
  self.inference_client = InferenceClient(
116
  model=model_name,
117
  token=hf_token
118
  )
119
- print("Inference API client initialized successfully")
120
  except Exception as e:
121
- print(f"Error initializing Inference API client: {e}")
122
  self.inference_client = None
123
 
124
  # Initialize document ingestion
@@ -138,18 +142,27 @@ class RAGChatbot:
138
 
139
  def _generate_with_chat(self, user_content: str, max_new_tokens: int = 512) -> str:
140
  """Call the Inference API using chat/comversational endpoint (required for Mistral instruct)."""
141
- response = self.inference_client.chat_completion(
142
- model=self.model_name,
143
- messages=[{"role": "user", "content": user_content}],
144
- max_tokens=max_new_tokens,
145
- temperature=0.7,
146
- )
147
- # ChatCompletion has choices[0].message.content
148
- if response and response.choices and len(response.choices) > 0:
149
- msg = response.choices[0].message
150
- if hasattr(msg, "content") and msg.content:
151
- return msg.content.strip()
152
- return ""
 
 
 
 
 
 
 
 
 
153
 
154
  def generate_response(self, query: str, use_rag: bool = True, num_results: int = 5) -> str:
155
  """
@@ -197,7 +210,7 @@ Answer:"""
197
  return response_text
198
  raise ValueError("Empty response from model")
199
  except Exception as api_error:
200
- print(f"Error calling Inference API: {api_error}")
201
  # Fallback: return formatted chunks with note
202
  response_parts = []
203
  response_parts.append("I retrieved relevant information, but couldn't generate a synthesized answer. Here are the relevant chunks:\n\n")
 
104
 
105
  # Initialize Inference API client
106
  hf_token = os.environ.get("HF_TOKEN")
107
+ # Debug: report HF_TOKEN status (masked)
108
  if not hf_token:
109
+ print("[DEBUG] HF_TOKEN: not set (empty or missing)")
110
  print("Warning: HF_TOKEN not set. Inference API calls may fail.")
111
  print("Set HF_TOKEN environment variable or add it to Space secrets.")
112
  else:
113
+ masked = f"{hf_token[:4]}...{hf_token[-4:]}" if len(hf_token) > 8 else "****"
114
+ print(f"[DEBUG] HF_TOKEN: set (length={len(hf_token)}, masked={masked})")
115
  print("HF_TOKEN found. Inference API ready.")
116
 
117
+ print(f"[DEBUG] Initializing Inference API client for model: {model_name}")
118
  try:
119
  self.inference_client = InferenceClient(
120
  model=model_name,
121
  token=hf_token
122
  )
123
+ print("[DEBUG] Inference API client initialized successfully (using chat_completion for this model)")
124
  except Exception as e:
125
+ print(f"[DEBUG] Error initializing Inference API client: {type(e).__name__}: {e}")
126
  self.inference_client = None
127
 
128
  # Initialize document ingestion
 
142
 
143
  def _generate_with_chat(self, user_content: str, max_new_tokens: int = 512) -> str:
144
  """Call the Inference API using chat/comversational endpoint (required for Mistral instruct)."""
145
+ print(f"[DEBUG] _generate_with_chat: model={self.model_name}, API=chat_completion, prompt_len={len(user_content)}, max_tokens={max_new_tokens}")
146
+ try:
147
+ response = self.inference_client.chat_completion(
148
+ model=self.model_name,
149
+ messages=[{"role": "user", "content": user_content}],
150
+ max_tokens=max_new_tokens,
151
+ temperature=0.7,
152
+ )
153
+ print(f"[DEBUG] chat_completion response type: {type(response).__name__}")
154
+ # ChatCompletion has choices[0].message.content
155
+ if response and response.choices and len(response.choices) > 0:
156
+ msg = response.choices[0].message
157
+ if hasattr(msg, "content") and msg.content:
158
+ return msg.content.strip()
159
+ print("[DEBUG] chat_completion returned empty or unexpected structure")
160
+ return ""
161
+ except Exception as e:
162
+ print(f"[DEBUG] _generate_with_chat exception: {type(e).__name__}: {e}")
163
+ import traceback
164
+ traceback.print_exc()
165
+ raise
166
 
167
  def generate_response(self, query: str, use_rag: bool = True, num_results: int = 5) -> str:
168
  """
 
210
  return response_text
211
  raise ValueError("Empty response from model")
212
  except Exception as api_error:
213
+ print(f"[DEBUG] RAG generation failed: {type(api_error).__name__}: {api_error}")
214
  # Fallback: return formatted chunks with note
215
  response_parts = []
216
  response_parts.append("I retrieved relevant information, but couldn't generate a synthesized answer. Here are the relevant chunks:\n\n")