File size: 1,200 Bytes
bc829c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# pinecone_utils.py

import pinecone
from config import PINECONE_API_KEY, PINECONE_ENVIRONMENT, INDEX_NAME, CONTEXT_FIELDS
import torch

# Conectar a Pinecone
def connect_to_pinecone():
    pinecone.init(api_key=PINECONE_API_KEY, environment=PINECONE_ENVIRONMENT)
    index = pinecone.Index(INDEX_NAME)
    return index

# Realizar búsqueda vectorial
def vector_search(query, embedding_model, index):
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    # Generar el embedding utilizando el modelo de embeddings
    xq = embedding_model.encode(query, convert_to_tensor=True, device=device)

    # Convertir el tensor a lista
    xq = xq.cpu().tolist()

    # Realizar búsqueda vectorial en el índice de Pinecone
    res = index.query(vector=xq, top_k=3, include_metadata=True)
    if res and res['matches']:
        return [
            {
                'content': ' '.join(f"{k}: {v}" for k, v in match['metadata'].items() if k in CONTEXT_FIELDS and k != 'Tag'),
                'metadata': match['metadata'],
                'score': match.get('score', 0)
            }
            for match in res['matches']
            if 'metadata' in match
        ]
    return []