Syluh27 commited on
Commit
b206c20
·
1 Parent(s): 122e667
Files changed (1) hide show
  1. model.py +38 -66
model.py CHANGED
@@ -1,4 +1,3 @@
1
- # model.py actualizado
2
  from langchain.chains import RetrievalQA
3
  from langchain.vectorstores import Chroma
4
  from langchain.embeddings import HuggingFaceEmbeddings
@@ -8,78 +7,51 @@ from huggingface_hub import hf_hub_download
8
  import os
9
  import shutil
10
 
11
- # 1. Configuración esencial
12
  HF_TOKEN = os.getenv("HF_TOKEN")
13
- MISTRAL_API_KEY = os.getenv("MISTRAL_API_KEY")
14
- CHROMA_DIR = "/home/user/app/chroma_db"
15
-
16
-
17
- # 2. Limpieza inicial radical
18
- def full_clean():
19
- # Eliminar todo rastro previo
20
- shutil.rmtree(CHROMA_DIR, ignore_errors=True)
21
- shutil.rmtree("/home/user/.cache/huggingface/hub", ignore_errors=True)
22
- os.makedirs(CHROMA_DIR, exist_ok=True)
23
-
24
-
25
- full_clean()
26
-
27
-
28
- # 3. Descargar y configurar ChromaDB
29
- def setup_chroma():
30
- # Descargar archivo original
31
- chroma_src = hf_hub_download(
32
- repo_id="VictorCarr02/Conversational-Agent-LawsEC",
33
- repo_type="dataset",
34
- filename="chroma.sqlite3",
35
- token=HF_TOKEN
36
- )
37
-
38
- # Configurar estructura requerida por Chroma
39
- tenant_dir = os.path.join(CHROMA_DIR, "chroma.sqlite3")
40
- os.makedirs(os.path.dirname(tenant_dir), exist_ok=True)
41
- shutil.copy(chroma_src, tenant_dir)
42
-
43
-
44
- setup_chroma()
45
 
46
- # 4. Conexión explícita a ChromaDB
47
- chroma_client = chromadb.PersistentClient(
48
- path=CHROMA_DIR,
49
- tenant="default_tenant",
50
- database="default_database"
 
51
  )
52
 
53
- # 5. Verificar/crear collection
54
- try:
55
- collection = chroma_client.get_collection("legal_docs")
56
- except ValueError:
57
- collection = chroma_client.create_collection("legal_docs")
58
 
59
- # 6. Configurar embeddings
60
- embeddings = HuggingFaceEmbeddings(
61
- model_name="sentence-transformers/all-mpnet-base-v2",
62
- model_kwargs={"device": "cpu"}
63
- )
64
 
65
- # 7. Inicializar Chroma LangChain
66
- vector_store = Chroma(
67
- client=chroma_client,
68
- collection_name="legal_docs",
69
- embedding_function=embeddings
70
- )
71
 
72
- # 8. Configurar Mistral
73
- llm = ChatMistralAI(
74
- api_key=MISTRAL_API_KEY,
75
- model="mistral-large-latest",
76
- temperature=0.1
77
- )
78
 
79
- # 9. Cadena RAG final
80
  rag_chain = RetrievalQA.from_chain_type(
81
  llm=llm,
82
- retriever=vector_store.as_retriever(search_kwargs={"k": 3}),
83
- chain_type="stuff",
84
- return_source_documents=True
85
- )
 
 
1
  from langchain.chains import RetrievalQA
2
  from langchain.vectorstores import Chroma
3
  from langchain.embeddings import HuggingFaceEmbeddings
 
7
  import os
8
  import shutil
9
 
10
+ # Obtener el token desde las variables de entorno de Hugging Face Space
11
  HF_TOKEN = os.getenv("HF_TOKEN")
12
+ if HF_TOKEN is None:
13
+ raise ValueError("No se encontró la variable de entorno HF_TOKEN.")
14
+
15
+ # Descargar los archivos
16
+ embedding_path = hf_hub_download(
17
+ repo_id="VictorCarr02/Conversational-Agent-LawsEC",
18
+ repo_type="dataset",
19
+ filename="data_level0.bin",
20
+ token=HF_TOKEN,
21
+ force_download=True # Fuerza la descarga
22
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
+ chroma_path = hf_hub_download(
25
+ repo_id="VictorCarr02/Conversational-Agent-LawsEC",
26
+ repo_type="dataset",
27
+ filename="chroma.sqlite3",
28
+ token=HF_TOKEN,
29
+ force_download=True # Fuerza la descarga
30
  )
31
 
32
+ print("Archivos descargados en:")
33
+ print(f"Embeddings: {embedding_path}")
34
+ print(f"ChromaDB: {chroma_path}")
 
 
35
 
36
+ # Cargar ChromaDB y los embeddings
37
+ chromadb_client = chromadb.PersistentClient(path=chroma_path)
38
+ collection = chromadb_client.get_or_create_collection(name="mis_embeddings")
39
+ embeddings = HuggingFaceEmbeddings(model_name="mistralai/MistralAIEmbeddings", path=embedding_path)
40
+ vector_store = Chroma(collection=collection, embedding_function=embeddings)
41
 
42
+ # Acceder a la clave API desde la variable de entorno
43
+ api_key = os.getenv("MISTRAL_API_KEY")
 
 
 
 
44
 
45
+ # Verifica si la clave fue obtenida correctamente
46
+ if api_key is None:
47
+ raise ValueError("La clave API MISTRAL_API_KEY no está configurada como variable de entorno.")
48
+
49
+ # Crear el modelo LLM con la clave API
50
+ llm = ChatMistralAI(api_key=api_key)
51
 
52
+ # Crear el agente RAG
53
  rag_chain = RetrievalQA.from_chain_type(
54
  llm=llm,
55
+ retriever=vector_store.as_retriever(),
56
+ chain_type="stuff"
57
+ )