Spaces:
Running

axeronis commited on
Commit
89c8da5
·
1 Parent(s): 220c548

fix: hardcoded Gemini schema and real-time UI data sync

Browse files
backend/app/api/webhook.py CHANGED
@@ -2401,9 +2401,11 @@ async def process_background_ai_tasks(
2401
  await notify_lead_updated(str(lead.id), {
2402
  "id": str(lead.id),
2403
  "ai_summary_json": lead.ai_summary_json,
 
 
2404
  "heat_score": lead.heat_score,
2405
- "heat_level": lead.heat_level.value if lead.heat_level else "unknown",
2406
- "psychotype": lead.psychotype.value if lead.psychotype else "unknown",
2407
  "name": lead.name,
2408
  "processing_status": "idle", # Explicitly set idle for UI
2409
  "needs_attention": lead.needs_attention,
 
2401
  await notify_lead_updated(str(lead.id), {
2402
  "id": str(lead.id),
2403
  "ai_summary_json": lead.ai_summary_json,
2404
+ "qualification_data": lead.qualification_data, # Added!
2405
+ "qualification_complete": lead.qualification_complete, # Added!
2406
  "heat_score": lead.heat_score,
2407
+ "heat_level": lead.heat_level.value if lead.heat_level and hasattr(lead.heat_level, 'value') else str(lead.heat_level),
2408
+ "psychotype": lead.psychotype.value if lead.psychotype and hasattr(lead.psychotype, 'value') else str(lead.psychotype),
2409
  "name": lead.name,
2410
  "processing_status": "idle", # Explicitly set idle for UI
2411
  "needs_attention": lead.needs_attention,
backend/app/services/gemini_client.py CHANGED
@@ -439,41 +439,53 @@ Respond with ONLY a number from 0 to 100."""
439
  """
440
 
441
  try:
442
- # Helper: Clean schema for Gemini (it's extremely picky about standard JSON Schema keys)
443
- def clean_schema_for_gemini(schema: dict) -> dict:
444
- """Recursively remove keys that Gemini API rejects in standard mode."""
445
- if not isinstance(schema, dict):
446
- return schema
447
-
448
- # Forbidden keys in Gemini's Controlled Generation
449
- forbidden = {'default', 'title', 'example', 'examples', 'description_html'}
450
-
451
- cleaned = {}
452
- for k, v in schema.items():
453
- if k in forbidden:
454
- continue
455
- if isinstance(v, dict):
456
- cleaned[k] = clean_schema_for_gemini(v)
457
- elif isinstance(v, list):
458
- cleaned[k] = [clean_schema_for_gemini(item) if isinstance(item, dict) else item for item in v]
459
- else:
460
- cleaned[k] = v
461
- return cleaned
462
-
463
- # Get raw schema
464
- raw_schema = AISummary.model_json_schema()
465
- # Clean it thoroughly
466
- clean_schema = clean_schema_for_gemini(raw_schema)
467
-
468
- # Debug: log the keys we are sending
469
- logger.info(f"🧠 Sending cleaned schema to Gemini: {list(clean_schema.get('properties', {}).keys())}")
470
-
 
 
 
 
 
 
 
 
 
 
 
 
471
  # Use new google.genai SDK with JSON response schema
472
  summary_config = types.GenerateContentConfig(
473
  temperature=0.1,
474
  max_output_tokens=4096,
475
  response_mime_type="application/json",
476
- response_schema=clean_schema
477
  )
478
 
479
  # Run in executor to avoid blocking
 
439
  """
440
 
441
  try:
442
+ # 🔧 HARDCODED STRICT SCHEMA FOR GEMINI (Avoids all Pydantic 'default'/'title' noise)
443
+ # Gemini response_schema DOES NOT SUPPORT 'default' keys.
444
+ gemini_strict_schema = {
445
+ "type": "object",
446
+ "properties": {
447
+ "client_name": {"type": "string", "description": "Настоящее имя клиента или null"},
448
+ "niche": {"type": "string", "description": "Ниша/бизнес клиента или null"},
449
+ "intent": {"type": "string", "description": "Основная цель клиента"},
450
+ "intent_confidence": {"type": "number"},
451
+ "budget": {"type": "string", "description": "Бюджет клиента"},
452
+ "budget_confidence": {"type": "number"},
453
+ "timeline": {"type": "string", "description": "Сроки"},
454
+ "timeline_confidence": {"type": "number"},
455
+ "authority": {"type": "string", "description": "Роль в принятии решения"},
456
+ "authority_confidence": {"type": "number"},
457
+ "pain_points": {
458
+ "type": "array",
459
+ "items": {"type": "string"}
460
+ },
461
+ "psychotype": {
462
+ "type": "string",
463
+ "enum": ["Dominant", "Influential", "Steady", "Conscientious", "Unknown"]
464
+ },
465
+ "psychotype_confidence": {"type": "number"},
466
+ "heat_score": {"type": "integer", "description": "0-100"},
467
+ "objections": {
468
+ "type": "array",
469
+ "items": {"type": "string"}
470
+ },
471
+ "hidden_signals": {"type": "string"},
472
+ "recommendation": {"type": "string"},
473
+ "draft_reply": {"type": "string"}
474
+ },
475
+ "required": [
476
+ "intent", "intent_confidence", "budget", "budget_confidence",
477
+ "timeline", "timeline_confidence", "authority", "authority_confidence",
478
+ "pain_points", "psychotype", "psychotype_confidence", "heat_score",
479
+ "objections", "hidden_signals", "recommendation", "draft_reply"
480
+ ]
481
+ }
482
+
483
  # Use new google.genai SDK with JSON response schema
484
  summary_config = types.GenerateContentConfig(
485
  temperature=0.1,
486
  max_output_tokens=4096,
487
  response_mime_type="application/json",
488
+ response_schema=gemini_strict_schema
489
  )
490
 
491
  # Run in executor to avoid blocking
frontend/app/chats/page.tsx CHANGED
@@ -121,16 +121,26 @@ function ChatsContent() {
121
 
122
  // Refresh only lead data (for AI summary updates) - doesn't reload messages
123
  const handleRefreshLeadOnly = async () => {
124
- await refetchLeads()
125
  // Update selectedLead from fresh data without reloading messages
126
- if (selectedLead && leads) {
127
- const updated = leads.find((l: Lead) => l.id === selectedLead.id)
128
  if (updated) {
129
  setSelectedLead(updated)
130
  }
131
  }
132
  }
133
 
 
 
 
 
 
 
 
 
 
 
134
  // Delete Lead Handler
135
  const handleDeleteLead = async (leadId: string, clearCache: boolean) => {
136
  try {
@@ -269,6 +279,7 @@ function ChatsContent() {
269
  isAnalyzing={selectedLead.processing_status === 'analyzing'}
270
  onRefresh={handleRefresh}
271
  onLeadRefresh={handleRefreshLeadOnly}
 
272
  onConversationUpdate={(data) => setConversation(data)}
273
  onTakeover={() => { }}
274
  onBack={() => {
 
121
 
122
  // Refresh only lead data (for AI summary updates) - doesn't reload messages
123
  const handleRefreshLeadOnly = async () => {
124
+ const { data: freshLeads } = await refetchLeads()
125
  // Update selectedLead from fresh data without reloading messages
126
+ if (selectedLead && freshLeads) {
127
+ const updated = freshLeads.find((l: Lead) => l.id === selectedLead.id)
128
  if (updated) {
129
  setSelectedLead(updated)
130
  }
131
  }
132
  }
133
 
134
+ // Direct update from WebSocket to avoid refetch lag
135
+ const handleLeadDataUpdate = (updatedData: any) => {
136
+ if (selectedLead && updatedData.id === selectedLead.id) {
137
+ setSelectedLead(prev => {
138
+ if (!prev) return prev
139
+ return { ...prev, ...updatedData }
140
+ })
141
+ }
142
+ }
143
+
144
  // Delete Lead Handler
145
  const handleDeleteLead = async (leadId: string, clearCache: boolean) => {
146
  try {
 
279
  isAnalyzing={selectedLead.processing_status === 'analyzing'}
280
  onRefresh={handleRefresh}
281
  onLeadRefresh={handleRefreshLeadOnly}
282
+ onLeadUpdate={handleLeadDataUpdate}
283
  onConversationUpdate={(data) => setConversation(data)}
284
  onTakeover={() => { }}
285
  onBack={() => {
frontend/components/ChatWindow.tsx CHANGED
@@ -34,6 +34,7 @@ interface ChatWindowProps {
34
  isAnalyzing?: boolean
35
  onRefresh?: () => void
36
  onLeadRefresh?: () => void
 
37
  onConversationUpdate?: (data: any) => void // New prop for silent updates
38
  onTakeover?: () => void
39
  onBack?: () => void
@@ -217,7 +218,9 @@ export function ChatWindow({
217
  // When lead data is updated (e.g., name extracted), refresh to update AI Summary
218
  onLeadUpdated: (updatedLead) => {
219
  console.log('📋 WebSocket: Lead updated', updatedLead?.name)
220
- // Use lead-only refresh to avoid reloading messages (no spinner)
 
 
221
  onLeadRefresh?.() || onRefresh?.()
222
  }
223
  })
 
34
  isAnalyzing?: boolean
35
  onRefresh?: () => void
36
  onLeadRefresh?: () => void
37
+ onLeadUpdate?: (leadData: any) => void
38
  onConversationUpdate?: (data: any) => void // New prop for silent updates
39
  onTakeover?: () => void
40
  onBack?: () => void
 
218
  // When lead data is updated (e.g., name extracted), refresh to update AI Summary
219
  onLeadUpdated: (updatedLead) => {
220
  console.log('📋 WebSocket: Lead updated', updatedLead?.name)
221
+ // 1. Direct state update for instant UI response
222
+ onLeadUpdate?.(updatedLead)
223
+ // 2. Fallback to full refresh to ensure all related data (lists etc) are synced
224
  onLeadRefresh?.() || onRefresh?.()
225
  }
226
  })