kadsai commited on
Commit
4545002
·
verified ·
1 Parent(s): 1e2dbf5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -53
app.py CHANGED
@@ -1,81 +1,77 @@
1
  import os
2
  import gradio as gr
3
- from langchain.chains import RetrievalQA
4
- from langchain.embeddings import OpenAIEmbeddings
5
- from langchain.vectorstores import Chroma
6
- from langchain.agents import initialize_agent, Tool, AgentType
7
- from deepseek_chat import DeepSeekChat # Import du wrapper custom
8
  import ingest
9
 
10
- # Chargement des variables d’environnement
11
- openai_api_key = os.getenv("DEEPSEEK_KEY")
12
- openai_api_base = os.getenv("OPENAI_API_BASE")
13
  VECTORSTORE_BASE_DIR = "vectorstores_chroma"
14
 
15
- # Ingestion des documents
16
  try:
17
  ingest.main()
18
  except Exception as e:
19
  print(f"Erreur lors de l’ingestion initiale : {e}")
 
 
20
 
21
- # Création d’un outil (Tool) LangChain RAG
22
- def get_tool(domain: str, subdomain: str, temperature: float, max_tokens: int, top_p: float) -> Tool:
23
- embeddings = OpenAIEmbeddings(openai_api_key=openai_api_key, openai_api_base=openai_api_base)
24
- vectorstore_path = os.path.join(VECTORSTORE_BASE_DIR, domain.lower(), subdomain.lower())
25
 
26
- if not os.path.exists(vectorstore_path):
27
- raise ValueError(f"Aucun vecteur pour {domain}/{subdomain}")
 
 
 
28
 
29
- db = Chroma(persist_directory=vectorstore_path, embedding_function=embeddings)
30
- retriever = db.as_retriever()
 
 
 
31
 
32
- llm = DeepSeekChat(
33
- api_key=openai_api_key,
34
- base_url=openai_api_base,
35
- model="deepseek-chat",
36
- temperature=temperature,
37
- max_tokens=max_tokens,
38
- top_p=top_p
39
- )
40
 
41
- qa = RetrievalQA.from_chain_type(llm=llm, retriever=retriever)
42
-
43
- return Tool(
44
- name=f"{domain}_{subdomain}_tool",
45
- func=qa.run,
46
- description=f"Répond aux questions pour {domain}/{subdomain}"
47
- )
48
-
49
- # Fonction principale de réponse
50
  def respond(message, history, system_message, domain, subdomain, max_tokens, temperature, top_p):
51
  try:
52
- tool = get_tool(domain, subdomain, temperature, max_tokens, top_p)
 
 
 
 
 
 
 
 
 
53
 
54
- llm = DeepSeekChat(
55
- api_key=openai_api_key,
56
- base_url=openai_api_base,
 
 
 
 
 
57
  model="deepseek-chat",
 
58
  temperature=temperature,
59
  max_tokens=max_tokens,
60
  top_p=top_p
61
  )
62
 
63
- agent = initialize_agent(
64
- tools=[tool],
65
- llm=llm,
66
- agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
67
- verbose=False
68
- )
69
-
70
- if system_message and not any("System:" in turn[0] for turn in history):
71
- history.insert(0, (f"System: {system_message}", ""))
72
-
73
- response = agent.run(message)
74
- history.append((message, response))
75
- yield response
76
 
77
  except Exception as e:
78
- yield f"❌ Erreur : {str(e)}"
79
 
80
  # Interface Gradio
81
  chatbot_ui = gr.ChatInterface(
@@ -88,7 +84,7 @@ chatbot_ui = gr.ChatInterface(
88
  gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.1, label="Température"),
89
  gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p"),
90
  ],
91
- title="Agent IA - CorisMoney",
92
  description="Posez vos questions selon le domaine et le sous-domaine.",
93
  )
94
 
 
1
  import os
2
  import gradio as gr
3
+ import chromadb
4
+ from chromadb.config import Settings
5
+ from chromadb.utils import embedding_functions
6
+ from openai import OpenAI
7
+ from sentence_transformers import SentenceTransformer
8
  import ingest
9
 
10
+ # 🔑 Clés API et configuration
11
+ DEEPSEEK_KEY = os.getenv("DEEPSEEK_KEY")
12
+ DEEPSEEK_BASE = os.getenv("OPENAI_API_BASE")
13
  VECTORSTORE_BASE_DIR = "vectorstores_chroma"
14
 
15
+ # Lancement de l’ingestion
16
  try:
17
  ingest.main()
18
  except Exception as e:
19
  print(f"Erreur lors de l’ingestion initiale : {e}")
20
+ # Embedding model utilisé pour la recherche (doit être identique à celui d’ingestion)
21
+ embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
22
 
23
+ # Initialise client DeepSeek
24
+ client = OpenAI(api_key=DEEPSEEK_KEY, base_url=DEEPSEEK_BASE)
 
 
25
 
26
+ # Fonction : charge une collection vectorielle
27
+ def load_collection(domain: str, subdomain: str):
28
+ collection_path = os.path.join(VECTORSTORE_BASE_DIR, domain.lower(), subdomain.lower())
29
+ if not os.path.exists(collection_path):
30
+ raise FileNotFoundError(f"❌ Base vectorielle non trouvée : {collection_path}")
31
 
32
+ client_chroma = chromadb.Client(Settings(
33
+ persist_directory=collection_path,
34
+ chroma_db_impl="duckdb+parquet",
35
+ anonymized_telemetry=False
36
+ ))
37
 
38
+ return client_chroma.get_default_collection()
 
 
 
 
 
 
 
39
 
40
+ # Fonction : recherche contextuelle + réponse DeepSeek
 
 
 
 
 
 
 
 
41
  def respond(message, history, system_message, domain, subdomain, max_tokens, temperature, top_p):
42
  try:
43
+ collection = load_collection(domain, subdomain)
44
+ query_embedding = embedding_model.encode(message).tolist()
45
+
46
+ # Recherche contextuelle
47
+ results = collection.query(
48
+ query_embeddings=[query_embedding],
49
+ n_results=3
50
+ )
51
+
52
+ context = "\n".join(results["documents"][0]) if results["documents"] else ""
53
 
54
+ # Construction du prompt
55
+ full_prompt = [
56
+ {"role": "system", "content": f"{system_message}\n\nContexte:\n{context}"},
57
+ {"role": "user", "content": message}
58
+ ]
59
+
60
+ # Appel DeepSeek
61
+ response = client.chat.completions.create(
62
  model="deepseek-chat",
63
+ messages=full_prompt,
64
  temperature=temperature,
65
  max_tokens=max_tokens,
66
  top_p=top_p
67
  )
68
 
69
+ content = response.choices[0].message.content
70
+ history.append((message, content))
71
+ yield content
 
 
 
 
 
 
 
 
 
 
72
 
73
  except Exception as e:
74
+ yield f"❌ Erreur : {e}"
75
 
76
  # Interface Gradio
77
  chatbot_ui = gr.ChatInterface(
 
84
  gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.1, label="Température"),
85
  gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p"),
86
  ],
87
+ title="Assistant RAG CorisMoney (DeepSeek)",
88
  description="Posez vos questions selon le domaine et le sous-domaine.",
89
  )
90