ReallyFloppyPenguin commited on
Commit
c6899d7
Β·
verified Β·
1 Parent(s): 34f617a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +642 -0
app.py ADDED
@@ -0,0 +1,642 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import json
4
+ import hashlib
5
+ import datetime
6
+ from typing import List, Dict, Any, Optional
7
+ import requests
8
+ import time
9
+ import uuid
10
+ from pinecone import Pinecone
11
+
12
+ class RAGMemorySystem:
13
+ """RAG system using Pinecone with integrated inference for embeddings and vector storage"""
14
+
15
+ def __init__(self):
16
+ # Initialize Pinecone - use the hardcoded key or environment variable
17
+ self.pinecone_api_key = os.getenv("PINECONE_API_KEY")
18
+ self.pinecone_environment = os.getenv("PINECONE_ENVIRONMENT", "us-east-1") # Serverless doesn't need specific environment
19
+
20
+ # Generate unique index name with timestamp to avoid conflicts
21
+ timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M")
22
+ user_id = str(uuid.uuid4())[:8]
23
+ self.index_name = os.getenv("PINECONE_INDEX_NAME", f"ai-experiences-{timestamp}-{user_id}")
24
+
25
+ # Pinecone inference model configuration
26
+ self.embedding_model = os.getenv("PINECONE_EMBEDDING_MODEL", "multilingual-e5-large")
27
+ self.rerank_model = os.getenv("PINECONE_RERANK_MODEL", "pinecone-rerank-v0")
28
+
29
+ # Initialize OpenRouter
30
+ self.openrouter_api_key = os.getenv("OPENROUTER_API_KEY")
31
+ self.model_name = os.getenv("MODEL_NAME", "meta-llama/llama-4-maverick:free")
32
+
33
+ # Initialize Pinecone client
34
+ self.pc = None
35
+ self.index = None
36
+
37
+ # Initialize Pinecone
38
+ self.init_pinecone()
39
+
40
+ def init_pinecone(self):
41
+ """Initialize Pinecone connection with integrated inference"""
42
+ try:
43
+ if self.pinecone_api_key:
44
+ # Initialize Pinecone client
45
+ self.pc = Pinecone(api_key=self.pinecone_api_key)
46
+
47
+ print(f"Attempting to connect to Pinecone...")
48
+
49
+ # Check existing indexes
50
+ try:
51
+ existing_indexes = [idx.name for idx in self.pc.list_indexes()]
52
+ print(f"Existing indexes: {existing_indexes}")
53
+ except Exception as list_error:
54
+ print(f"Error listing indexes: {list_error}")
55
+ existing_indexes = []
56
+
57
+ # Create index with integrated inference if it doesn't exist
58
+ if self.index_name not in existing_indexes:
59
+ print(f"Creating new Pinecone index with integrated inference: {self.index_name}")
60
+ try:
61
+ # Create index with integrated embedding model
62
+ index_model = self.pc.create_index_for_model(
63
+ name=self.index_name,
64
+ cloud="aws",
65
+ region="us-east-1",
66
+ embed={
67
+ "model": self.embedding_model,
68
+ "field_map": {"text": "content"} # Map 'text' field to 'content' field
69
+ }
70
+ )
71
+ print(f"Successfully created index with integrated inference: {self.index_name}")
72
+ print(f"Index details: {index_model}")
73
+
74
+ # Wait for index to be ready
75
+ time.sleep(10)
76
+
77
+ except Exception as create_error:
78
+ print(f"Error creating index with integrated inference: {create_error}")
79
+ # Fallback to traditional index creation
80
+ try:
81
+ self.pc.create_index(
82
+ name=self.index_name,
83
+ dimension=1024, # multilingual-e5-large dimension
84
+ metric="cosine",
85
+ spec={
86
+ "serverless": {
87
+ "cloud": "aws",
88
+ "region": "us-east-1"
89
+ }
90
+ }
91
+ )
92
+ print(f"Created fallback traditional index: {self.index_name}")
93
+ time.sleep(5)
94
+ except Exception as fallback_error:
95
+ print(f"Failed to create fallback index: {fallback_error}")
96
+
97
+ # Try with simpler name
98
+ simple_name = f"ai-exp-{str(uuid.uuid4())[:6]}"
99
+ try:
100
+ self.pc.create_index(
101
+ name=simple_name,
102
+ dimension=1024,
103
+ metric="cosine",
104
+ spec={
105
+ "serverless": {
106
+ "cloud": "aws",
107
+ "region": "us-east-1"
108
+ }
109
+ }
110
+ )
111
+ self.index_name = simple_name
112
+ print(f"Created simple fallback index: {self.index_name}")
113
+ time.sleep(5)
114
+ except Exception as final_error:
115
+ print(f"Final index creation failed: {final_error}")
116
+ self.index = None
117
+ return
118
+
119
+ # Connect to the index
120
+ try:
121
+ self.index = self.pc.Index(self.index_name)
122
+ print(f"Successfully connected to Pinecone index: {self.index_name}")
123
+
124
+ # Test the connection
125
+ stats = self.index.describe_index_stats()
126
+ print(f"Index stats: {stats}")
127
+
128
+ except Exception as connect_error:
129
+ print(f"Error connecting to index: {connect_error}")
130
+ self.index = None
131
+
132
+ else:
133
+ print("Warning: Pinecone API key not found. Memory storage disabled.")
134
+ self.index = None
135
+
136
+ except Exception as e:
137
+ print(f"Error initializing Pinecone: {e}")
138
+ self.index = None
139
+
140
+ def create_embedding(self, text: str) -> List[float]:
141
+ """Create embedding using Pinecone's inference API"""
142
+ try:
143
+ if not self.pc:
144
+ print("Pinecone client not available, returning zero vector")
145
+ return [0.0] * 1024
146
+
147
+ # Use Pinecone's inference API for embeddings
148
+ response = self.pc.inference.embed(
149
+ model=self.embedding_model,
150
+ inputs=[text],
151
+ parameters={
152
+ "input_type": "passage", # Use 'passage' for storing, 'query' for searching
153
+ "truncate": "END"
154
+ }
155
+ )
156
+
157
+ if response and len(response.data) > 0:
158
+ return response.data[0].values
159
+ else:
160
+ print("No embedding data received, returning zero vector")
161
+ return [0.0] * 1024
162
+
163
+ except Exception as e:
164
+ print(f"Error creating embedding with Pinecone inference: {e}")
165
+ return [0.0] * 1024 # Return zero vector as fallback
166
+
167
+ def create_query_embedding(self, text: str) -> List[float]:
168
+ """Create embedding for query using Pinecone's inference API"""
169
+ try:
170
+ if not self.pc:
171
+ print("Pinecone client not available, returning zero vector")
172
+ return [0.0] * 1024
173
+
174
+ # Use Pinecone's inference API for query embeddings
175
+ response = self.pc.inference.embed(
176
+ model=self.embedding_model,
177
+ inputs=[text],
178
+ parameters={
179
+ "input_type": "query", # Use 'query' for searching
180
+ "truncate": "END"
181
+ }
182
+ )
183
+
184
+ if response and len(response.data) > 0:
185
+ return response.data[0].values
186
+ else:
187
+ print("No embedding data received, returning zero vector")
188
+ return [0.0] * 1024
189
+
190
+ except Exception as e:
191
+ print(f"Error creating query embedding with Pinecone inference: {e}")
192
+ return [0.0] * 1024 # Return zero vector as fallback
193
+
194
+ def store_experience(self, user_input: str, ai_response: str, context: str = "") -> str:
195
+ """Store conversation experience in Pinecone using integrated inference"""
196
+ if not self.index:
197
+ return "Memory storage not available (Pinecone not configured)"
198
+
199
+ try:
200
+ # Create a unique ID for this experience
201
+ experience_id = hashlib.md5(
202
+ f"{user_input}_{ai_response}_{datetime.datetime.now()}_{uuid.uuid4()}".encode()
203
+ ).hexdigest()
204
+
205
+ # Create combined text for embedding
206
+ combined_text = f"User: {user_input}\nAI: {ai_response}\nContext: {context}"
207
+
208
+ # Check if index supports integrated inference
209
+ try:
210
+ # Try using integrated inference first (if index was created with create_index_for_model)
211
+ record = {
212
+ "id": experience_id,
213
+ "content": combined_text, # This will be automatically embedded
214
+ "metadata": {
215
+ "user_input": user_input[:1000],
216
+ "ai_response": ai_response[:1000],
217
+ "context": context[:500],
218
+ "timestamp": datetime.datetime.now().isoformat(),
219
+ "interaction_type": "conversation",
220
+ "session_id": getattr(self, 'session_id', 'default')
221
+ }
222
+ }
223
+
224
+ # Try upsert with integrated inference
225
+ self.index.upsert_records([record])
226
+ return f"βœ… Experience stored with integrated inference, ID: {experience_id[:8]}... in index: {self.index_name}"
227
+
228
+ except Exception as integrated_error:
229
+ print(f"Integrated inference failed: {integrated_error}")
230
+
231
+ # Fallback to manual embedding
232
+ embedding = self.create_embedding(combined_text)
233
+
234
+ # Store in Pinecone with manual embedding
235
+ self.index.upsert([(experience_id, embedding, {
236
+ "user_input": user_input[:1000],
237
+ "ai_response": ai_response[:1000],
238
+ "context": context[:500],
239
+ "timestamp": datetime.datetime.now().isoformat(),
240
+ "interaction_type": "conversation",
241
+ "session_id": getattr(self, 'session_id', 'default')
242
+ })])
243
+
244
+ return f"βœ… Experience stored with manual embedding, ID: {experience_id[:8]}... in index: {self.index_name}"
245
+
246
+ except Exception as e:
247
+ return f"❌ Error storing experience: {e}"
248
+
249
+ def retrieve_relevant_experiences(self, query: str, top_k: int = 3) -> List[Dict]:
250
+ """Retrieve relevant past experiences based on query using Pinecone inference"""
251
+ if not self.index:
252
+ return []
253
+
254
+ try:
255
+ # Try integrated search first
256
+ try:
257
+ results = self.index.search_records(
258
+ query={
259
+ "top_k": top_k,
260
+ "inputs": {"text": query}
261
+ },
262
+ include_metadata=True
263
+ )
264
+
265
+ relevant_experiences = []
266
+ if hasattr(results, 'matches'):
267
+ for match in results.matches:
268
+ if match.score > 0.3:
269
+ relevant_experiences.append({
270
+ "score": match.score,
271
+ "user_input": match.metadata.get("user_input", ""),
272
+ "ai_response": match.metadata.get("ai_response", ""),
273
+ "context": match.metadata.get("context", ""),
274
+ "timestamp": match.metadata.get("timestamp", ""),
275
+ "id": match.id
276
+ })
277
+
278
+ return relevant_experiences
279
+
280
+ except Exception as integrated_error:
281
+ print(f"Integrated search failed: {integrated_error}")
282
+
283
+ # Fallback to manual embedding + query
284
+ query_embedding = self.create_query_embedding(query)
285
+
286
+ # Search Pinecone with manual embedding
287
+ results = self.index.query(
288
+ vector=query_embedding,
289
+ top_k=top_k,
290
+ include_metadata=True
291
+ )
292
+
293
+ relevant_experiences = []
294
+ for match in results.matches:
295
+ if match.score > 0.3:
296
+ relevant_experiences.append({
297
+ "score": match.score,
298
+ "user_input": match.metadata.get("user_input", ""),
299
+ "ai_response": match.metadata.get("ai_response", ""),
300
+ "context": match.metadata.get("context", ""),
301
+ "timestamp": match.metadata.get("timestamp", ""),
302
+ "id": match.id
303
+ })
304
+
305
+ return relevant_experiences
306
+
307
+ except Exception as e:
308
+ print(f"Error retrieving experiences: {e}")
309
+ return []
310
+
311
+ def rerank_results(self, query: str, documents: List[str]) -> List[Dict]:
312
+ """Rerank results using Pinecone's reranking model"""
313
+ if not self.pc or not documents:
314
+ return []
315
+
316
+ try:
317
+ # Use Pinecone's inference API for reranking
318
+ response = self.pc.inference.rerank(
319
+ model=self.rerank_model,
320
+ query=query,
321
+ documents=documents,
322
+ top_k=min(len(documents), 5) # Rerank top 5
323
+ )
324
+
325
+ reranked_results = []
326
+ if response and hasattr(response, 'data'):
327
+ for result in response.data:
328
+ reranked_results.append({
329
+ "document": result.document.text,
330
+ "score": result.relevance_score,
331
+ "index": result.index
332
+ })
333
+
334
+ return reranked_results
335
+
336
+ except Exception as e:
337
+ print(f"Error reranking results: {e}")
338
+ return []
339
+
340
+ def call_openrouter(self, messages: List[Dict], temperature: float = 0.7) -> str:
341
+ """Call OpenRouter API"""
342
+ if not self.openrouter_api_key:
343
+ return "Error: OpenRouter API key not configured. Please set the OPENROUTER_API_KEY environment variable."
344
+
345
+ try:
346
+ headers = {
347
+ "Authorization": f"Bearer {self.openrouter_api_key}",
348
+ "Content-Type": "application/json",
349
+ "HTTP-Referer": "https://huggingface.co",
350
+ "X-Title": "AI RAG Memory System"
351
+ }
352
+
353
+ data = {
354
+ "model": self.model_name,
355
+ "messages": messages,
356
+ "temperature": temperature,
357
+ "max_tokens": 1000
358
+ }
359
+
360
+ response = requests.post(
361
+ "https://openrouter.ai/api/v1/chat/completions",
362
+ headers=headers,
363
+ json=data,
364
+ timeout=30
365
+ )
366
+
367
+ if response.status_code == 200:
368
+ result = response.json()
369
+ return result["choices"][0]["message"]["content"]
370
+ else:
371
+ return f"API Error: {response.status_code} - {response.text}"
372
+
373
+ except Exception as e:
374
+ return f"Error calling OpenRouter: {e}"
375
+
376
+ def generate_response_with_rag(self, user_input: str, conversation_history: List = None) -> tuple:
377
+ """Generate AI response using RAG with stored experiences and Pinecone inference"""
378
+ # Retrieve relevant past experiences
379
+ relevant_experiences = self.retrieve_relevant_experiences(user_input)
380
+
381
+ # Build context from relevant experiences
382
+ context_parts = []
383
+ if relevant_experiences:
384
+ context_parts.append("🧠 Relevant past experiences (powered by Pinecone inference):")
385
+
386
+ # Extract documents for reranking
387
+ documents = [f"User: {exp['user_input']} AI: {exp['ai_response']}" for exp in relevant_experiences]
388
+
389
+ # Try to rerank the results
390
+ reranked = self.rerank_results(user_input, documents)
391
+
392
+ if reranked:
393
+ context_parts.append(f"\nπŸ”„ Reranked results using {self.rerank_model}:")
394
+ for i, result in enumerate(reranked, 1):
395
+ context_parts.append(f"{i}. (Relevance: {result['score']:.3f}) {result['document'][:200]}...")
396
+ else:
397
+ # Fallback to original results
398
+ for i, exp in enumerate(relevant_experiences, 1):
399
+ context_parts.append(f"\n{i}. Previous interaction (similarity: {exp['score']:.2f}):")
400
+ context_parts.append(f" πŸ‘€ User: {exp['user_input'][:200]}...")
401
+ context_parts.append(f" πŸ€– AI: {exp['ai_response'][:200]}...")
402
+ context_parts.append(f" πŸ•’ Time: {exp['timestamp'][:19]}")
403
+ if exp['context']:
404
+ context_parts.append(f" πŸ“ Context: {exp['context'][:100]}...")
405
+ context_parts.append("")
406
+ else:
407
+ context_parts.append("πŸ†• No previous relevant experiences found. This is a fresh conversation!")
408
+
409
+ context_str = "\n".join(context_parts)
410
+
411
+ # Build messages for the AI
412
+ messages = [
413
+ {
414
+ "role": "system",
415
+ "content": f"""You are an AI assistant with access to your past experiences and interactions through Pinecone's vector database with integrated inference.
416
+ The embeddings are generated using {self.embedding_model} and results are reranked with {self.rerank_model}.
417
+
418
+ Use the relevant past experiences below to inform your response, but don't just repeat them - learn from them and provide thoughtful, personalized responses.
419
+
420
+ {context_str}
421
+
422
+ Guidelines:
423
+ - Reference past experiences when relevant and helpful
424
+ - Show that you remember and learn from interactions using Pinecone's memory system
425
+ - Provide helpful, contextual responses
426
+ - Be conversational and engaging
427
+ - If you see similar questions from before, build upon previous responses
428
+ - Acknowledge when you're learning something new through the memory system"""
429
+ }
430
+ ]
431
+
432
+ # Add conversation history if provided
433
+ if conversation_history:
434
+ for msg in conversation_history[-5:]: # Last 5 messages
435
+ messages.append(msg)
436
+
437
+ # Add current user input
438
+ messages.append({"role": "user", "content": user_input})
439
+
440
+ # Generate response
441
+ ai_response = self.call_openrouter(messages)
442
+
443
+ # Store this interaction as a new experience
444
+ storage_result = self.store_experience(user_input, ai_response, context_str)
445
+
446
+ return ai_response, context_str, storage_result
447
+
448
+ # Initialize the RAG system
449
+ rag_system = RAGMemorySystem()
450
+
451
+ def chat_with_rag(message: str, history: List = None) -> tuple:
452
+ """Main chat function for Gradio interface"""
453
+ if not message.strip():
454
+ return "Please enter a message.", "", ""
455
+
456
+ # Convert Gradio history format to OpenAI format
457
+ conversation_history = []
458
+ if history:
459
+ for user_msg, ai_msg in history:
460
+ if user_msg:
461
+ conversation_history.append({"role": "user", "content": user_msg})
462
+ if ai_msg:
463
+ conversation_history.append({"role": "assistant", "content": ai_msg})
464
+
465
+ # Generate response with RAG
466
+ ai_response, context_used, storage_info = rag_system.generate_response_with_rag(
467
+ message, conversation_history
468
+ )
469
+
470
+ return ai_response, context_used, storage_info
471
+
472
+ def clear_conversation():
473
+ """Clear the conversation history"""
474
+ return [], "", "", ""
475
+
476
+ def get_system_status():
477
+ """Get current system status"""
478
+ status = []
479
+
480
+ # Check Pinecone connection
481
+ if rag_system.index:
482
+ try:
483
+ stats = rag_system.index.describe_index_stats()
484
+ status.append(f"βœ… Pinecone: Connected to '{rag_system.index_name}'")
485
+ status.append(f"πŸ“Š Stored experiences: {stats.get('total_vector_count', 0)}")
486
+ status.append(f"🧠 Embedding model: {rag_system.embedding_model}")
487
+ status.append(f"πŸ”„ Reranking model: {rag_system.rerank_model}")
488
+ except:
489
+ status.append(f"⚠️ Pinecone: Connected but cannot get stats")
490
+ else:
491
+ status.append("❌ Pinecone: Not connected")
492
+
493
+ # Check OpenRouter
494
+ if rag_system.openrouter_api_key:
495
+ status.append(f"βœ… OpenRouter: API key configured")
496
+ status.append(f"πŸ€– Model: {rag_system.model_name}")
497
+ else:
498
+ status.append("❌ OpenRouter: API key not configured")
499
+
500
+ return "\n".join(status)
501
+
502
+ # Create Gradio interface
503
+ with gr.Blocks(
504
+ title="AI with Pinecone Integrated Inference RAG",
505
+ theme=gr.themes.Soft(),
506
+ css="""
507
+ .container { max-width: 1200px; margin: auto; }
508
+ .chat-container { height: 400px; overflow-y: auto; }
509
+ .context-box { background-color: #f8f9fa; padding: 10px; border-radius: 5px; font-family: monospace; }
510
+ .status-box { background-color: #e8f4f8; padding: 10px; border-radius: 5px; font-family: monospace; }
511
+ """
512
+ ) as demo:
513
+
514
+ gr.HTML("""
515
+ <div style="text-align: center; padding: 20px;">
516
+ <h1>πŸ€– AI Assistant with Pinecone Integrated Inference RAG</h1>
517
+ <p>This AI assistant uses Pinecone's integrated inference for embeddings and reranking with vector storage for memory.</p>
518
+ <p>Powered by <strong>multilingual-e5-large</strong> embeddings and <strong>pinecone-rerank-v0</strong> reranking model.</p>
519
+ <p><strong>πŸ†• Auto-Environment Creation:</strong> The system automatically creates a new Pinecone environment with integrated inference!</p>
520
+ </div>
521
+ """)
522
+
523
+ # System Status
524
+ with gr.Row():
525
+ with gr.Column():
526
+ status_display = gr.Textbox(
527
+ label="πŸ”§ System Status",
528
+ value=get_system_status(),
529
+ lines=8,
530
+ interactive=False,
531
+ elem_classes=["status-box"]
532
+ )
533
+ refresh_status_btn = gr.Button("πŸ”„ Refresh Status", variant="secondary")
534
+
535
+ with gr.Row():
536
+ with gr.Column(scale=2):
537
+ chatbot = gr.Chatbot(
538
+ label="Conversation",
539
+ height=400,
540
+ elem_classes=["chat-container"]
541
+ )
542
+
543
+ with gr.Row():
544
+ msg = gr.Textbox(
545
+ placeholder="Type your message here...",
546
+ label="Your Message",
547
+ lines=2,
548
+ scale=4
549
+ )
550
+ send_btn = gr.Button("Send", variant="primary", scale=1)
551
+ clear_btn = gr.Button("Clear", variant="secondary", scale=1)
552
+
553
+ with gr.Column(scale=1):
554
+ gr.HTML("<h3>πŸ“š RAG Context</h3>")
555
+ context_display = gr.Textbox(
556
+ label="Retrieved & Reranked Experiences",
557
+ lines=15,
558
+ interactive=False,
559
+ elem_classes=["context-box"]
560
+ )
561
+
562
+ storage_info = gr.Textbox(
563
+ label="Memory Storage Info",
564
+ lines=3,
565
+ interactive=False
566
+ )
567
+
568
+ with gr.Row():
569
+ with gr.Column():
570
+ gr.HTML("""
571
+ <div style="margin-top: 20px; padding: 15px; background-color: #e8f4f8; border-radius: 8px;">
572
+ <h3>πŸ”§ Configuration</h3>
573
+ <p><strong>Pinecone:</strong> βœ… Auto-configured with integrated inference</p>
574
+ <p><strong>Embedding Model:</strong> multilingual-e5-large (1024 dimensions)</p>
575
+ <p><strong>Reranking Model:</strong> pinecone-rerank-v0</p>
576
+ <p><strong>OpenRouter:</strong> Set <code>OPENROUTER_API_KEY</code> environment variable</p>
577
+ <br>
578
+ <p><strong>πŸš€ Pinecone Integrated Inference Features:</strong></p>
579
+ <ul>
580
+ <li>🧠 Automatic text-to-vector conversion during upsert and search</li>
581
+ <li>πŸ” Smart retrieval with multilingual embeddings</li>
582
+ <li>πŸ”„ Advanced reranking for improved relevance</li>
583
+ <li>πŸ“ˆ Learning and improvement over time</li>
584
+ <li>πŸ†” Unique environment creation for each session</li>
585
+ <li>⚑ Single API for embedding, storage, and retrieval</li>
586
+ </ul>
587
+ <br>
588
+ <p><strong>Model Options:</strong></p>
589
+ <ul>
590
+ <li><code>multilingual-e5-large</code> - Multilingual embeddings (default)</li>
591
+ <li><code>pinecone-rerank-v0</code> - Pinecone's reranking model (default)</li>
592
+ <li><code>cohere-rerank-v3.5</code> - Cohere's reranking model</li>
593
+ <li><code>pinecone-sparse-english-v0</code> - Sparse embeddings for keyword search</li>
594
+ </ul>
595
+ </div>
596
+ """)
597
+
598
+ # Event handlers
599
+ def respond(message, history):
600
+ if not message:
601
+ return history, "", "", ""
602
+
603
+ # Get AI response
604
+ ai_response, context_used, storage_info_text = chat_with_rag(message, history)
605
+
606
+ # Update history
607
+ if history is None:
608
+ history = []
609
+ history.append((message, ai_response))
610
+
611
+ return history, "", context_used, storage_info_text
612
+
613
+ # Wire up the interface
614
+ send_btn.click(
615
+ respond,
616
+ inputs=[msg, chatbot],
617
+ outputs=[chatbot, msg, context_display, storage_info]
618
+ )
619
+
620
+ msg.submit(
621
+ respond,
622
+ inputs=[msg, chatbot],
623
+ outputs=[chatbot, msg, context_display, storage_info]
624
+ )
625
+
626
+ clear_btn.click(
627
+ clear_conversation,
628
+ outputs=[chatbot, msg, context_display, storage_info]
629
+ )
630
+
631
+ refresh_status_btn.click(
632
+ get_system_status,
633
+ outputs=[status_display]
634
+ )
635
+
636
+ # Launch the app
637
+ if __name__ == "__main__":
638
+ demo.launch(
639
+ share=True,
640
+ server_name="0.0.0.0",
641
+ server_port=7860
642
+ )