Spaces:
Sleeping
Sleeping
tool db and laguage
Browse files- main.py +11 -2
- prompts.py +5 -1
- rag.py +103 -11
main.py
CHANGED
@@ -210,7 +210,14 @@ def generate_answer(user_input: UserInput):
|
|
210 |
|
211 |
if user_input.style_tonality is None:
|
212 |
prompt_formated = prompt_reformatting(template_prompt,context,prompt,enterprise_name=getattr(user_input,"marque",""))
|
213 |
-
answer = generate_response_via_langchain(prompt,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
214 |
else:
|
215 |
prompt_formated = prompt_reformatting(template_prompt,
|
216 |
context,
|
@@ -225,7 +232,9 @@ def generate_answer(user_input: UserInput):
|
|
225 |
style=getattr(user_input.style_tonality,"style","neutral"),
|
226 |
tonality=getattr(user_input.style_tonality,"tonality","formal"),
|
227 |
template=template_prompt,
|
228 |
-
enterprise_name=getattr(user_input,"marque","")
|
|
|
|
|
229 |
|
230 |
if user_input.stream:
|
231 |
return StreamingResponse(stream_generator(answer,prompt_formated), media_type="application/json")
|
|
|
210 |
|
211 |
if user_input.style_tonality is None:
|
212 |
prompt_formated = prompt_reformatting(template_prompt,context,prompt,enterprise_name=getattr(user_input,"marque",""))
|
213 |
+
answer = generate_response_via_langchain(prompt,
|
214 |
+
model=getattr(user_input,"model","gpt-4o"),
|
215 |
+
stream=user_input.stream,context = context ,
|
216 |
+
messages=user_input.messages,
|
217 |
+
template=template_prompt,
|
218 |
+
enterprise_name=getattr(user_input,"marque",""),
|
219 |
+
enterprise_id=enterprise_id,
|
220 |
+
index=index)
|
221 |
else:
|
222 |
prompt_formated = prompt_reformatting(template_prompt,
|
223 |
context,
|
|
|
232 |
style=getattr(user_input.style_tonality,"style","neutral"),
|
233 |
tonality=getattr(user_input.style_tonality,"tonality","formal"),
|
234 |
template=template_prompt,
|
235 |
+
enterprise_name=getattr(user_input,"marque",""),
|
236 |
+
enterprise_id=enterprise_id,
|
237 |
+
index=index)
|
238 |
|
239 |
if user_input.stream:
|
240 |
return StreamingResponse(stream_generator(answer,prompt_formated), media_type="application/json")
|
prompts.py
CHANGED
@@ -39,7 +39,7 @@
|
|
39 |
|
40 |
base_template = '''
|
41 |
Rôle
|
42 |
-
Tu es spécialiste de la communication marketing {
|
43 |
|
44 |
Tâche / Action
|
45 |
Développer du matériel de marketing digital engageant et informatif.
|
@@ -68,4 +68,8 @@ Adapté aux médias digitaux, avec les hashtags appropriés si nécessaire.
|
|
68 |
Style et ton
|
69 |
{style}, {tonality}.
|
70 |
|
|
|
|
|
|
|
|
|
71 |
'''
|
|
|
39 |
|
40 |
base_template = '''
|
41 |
Rôle
|
42 |
+
Tu es spécialiste de la communication marketing {enterprise}. Tu maîtrises l'analyse de marché, la stratégie digitale, la créativité et la production de contenus marketing impactant et efficace..
|
43 |
|
44 |
Tâche / Action
|
45 |
Développer du matériel de marketing digital engageant et informatif.
|
|
|
68 |
Style et ton
|
69 |
{style}, {tonality}.
|
70 |
|
71 |
+
Format
|
72 |
+
Adapté aux médias digitaux, avec les hashtags appropriés si nécessaire.
|
73 |
+
|
74 |
+
Les attentes de l'utilisateur sont : {query}
|
75 |
'''
|
rag.py
CHANGED
@@ -10,15 +10,29 @@ from langchain_core.prompts import PromptTemplate
|
|
10 |
from langchain_mistralai import ChatMistralAI
|
11 |
from uuid import uuid4
|
12 |
|
|
|
|
|
|
|
|
|
13 |
import unicodedata
|
14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
def remove_non_standard_ascii(input_string: str) -> str:
|
16 |
normalized_string = unicodedata.normalize('NFKD', input_string)
|
17 |
return ''.join(char for char in normalized_string if 'a' <= char <= 'z' or 'A' <= char <= 'Z' or char.isdigit() or char in ' .,!?')
|
18 |
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
def get_text_from_content_for_doc(content):
|
23 |
text = ""
|
24 |
for page in content:
|
@@ -68,6 +82,32 @@ def get_vectorstore(text_chunks,filename, file_type,namespace,index,enterprise_n
|
|
68 |
print(e)
|
69 |
return False
|
70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
71 |
def get_retreive_answer(enterprise_id,prompt,index,common_id):
|
72 |
try:
|
73 |
|
@@ -111,17 +151,55 @@ def get_retreive_answer(enterprise_id,prompt,index,common_id):
|
|
111 |
print(e)
|
112 |
return False
|
113 |
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
119 |
|
|
|
120 |
|
|
|
|
|
|
|
|
|
|
|
121 |
prompt = PromptTemplate.from_template(template)
|
122 |
|
123 |
-
|
124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
125 |
|
126 |
# Initialize the OpenAI LLM with the specified model
|
127 |
if model.startswith("gpt"):
|
@@ -129,10 +207,24 @@ def generate_response_via_langchain(query: str, stream: bool = False, model: str
|
|
129 |
if model.startswith("mistral"):
|
130 |
llm = ChatMistralAI(model=model,temperature=0)
|
131 |
|
132 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
133 |
# Create an LLM chain with the prompt and the LLM
|
|
|
|
|
|
|
|
|
|
|
134 |
llm_chain = prompt | llm | StrOutputParser()
|
135 |
|
|
|
|
|
|
|
136 |
if stream:
|
137 |
# Return a generator that yields streamed responses
|
138 |
return llm_chain.astream({ "query": query, "context": context, "messages": messages, "style": style, "tonality": tonality, "enterprise":enterprise_name })
|
|
|
10 |
from langchain_mistralai import ChatMistralAI
|
11 |
from uuid import uuid4
|
12 |
|
13 |
+
from pydantic import BaseModel, Field
|
14 |
+
|
15 |
+
from langchain_core.tools import tool
|
16 |
+
|
17 |
import unicodedata
|
18 |
|
19 |
+
class AddToKnowledgeBase(BaseModel):
|
20 |
+
''' Add information to the knowledge base if the user asks for it in his query'''
|
21 |
+
information: str = Field(..., title="The information to add to the knowledge base")
|
22 |
+
|
23 |
+
def detect_language(text:str):
|
24 |
+
llm = ChatOpenAI(model="gpt-4o-mini",temperature=0)
|
25 |
+
template = "détecte la langue du texte suivant: {text}. rassure-toi que ta reponse contient seulement le nom de la langue detectée"
|
26 |
+
prompt = PromptTemplate.from_template(template)
|
27 |
+
chain = prompt | llm | StrOutputParser()
|
28 |
+
response = chain.invoke({"text": text}).strip().lower()
|
29 |
+
print(response)
|
30 |
+
return response
|
31 |
+
|
32 |
def remove_non_standard_ascii(input_string: str) -> str:
|
33 |
normalized_string = unicodedata.normalize('NFKD', input_string)
|
34 |
return ''.join(char for char in normalized_string if 'a' <= char <= 'z' or 'A' <= char <= 'Z' or char.isdigit() or char in ' .,!?')
|
35 |
|
|
|
|
|
|
|
36 |
def get_text_from_content_for_doc(content):
|
37 |
text = ""
|
38 |
for page in content:
|
|
|
82 |
print(e)
|
83 |
return False
|
84 |
|
85 |
+
|
86 |
+
def add_to_knowledge_base(enterprise_id,information,index,enterprise_name):
|
87 |
+
''' Add information to the knowledge base
|
88 |
+
Args:
|
89 |
+
enterprise_id (str): the enterprise id
|
90 |
+
information (str): the information to add
|
91 |
+
index (str): the index name
|
92 |
+
'''
|
93 |
+
try:
|
94 |
+
embedding = OpenAIEmbeddings(model="text-embedding-3-large")
|
95 |
+
vector_store = PineconeVectorStore(index=index, embedding=embedding,namespace=enterprise_id)
|
96 |
+
|
97 |
+
document = Document(
|
98 |
+
page_content=information,
|
99 |
+
metadata={"filename":"knowledge_base","file_type":"text", "filename_id":"knowledge_base", "entreprise_name":enterprise_name},
|
100 |
+
)
|
101 |
+
|
102 |
+
uuid = f"knowledge_base_{uuid4()}"
|
103 |
+
|
104 |
+
vector_store.add_documents(documents=[document], id=uuid)
|
105 |
+
return True
|
106 |
+
|
107 |
+
except Exception as e:
|
108 |
+
print(e)
|
109 |
+
return False
|
110 |
+
|
111 |
def get_retreive_answer(enterprise_id,prompt,index,common_id):
|
112 |
try:
|
113 |
|
|
|
151 |
print(e)
|
152 |
return False
|
153 |
|
154 |
+
def handle_calling_add_to_knowledge_base(query,enterprise_id = "",index = "",enterprise_name = "",llm = None):
|
155 |
+
''' Handle the calling of the add_to_knowledge_base function
|
156 |
+
if the user, in his query, wants to add information to the knowledge base, the function will be called
|
157 |
+
'''
|
158 |
+
template = """
|
159 |
+
You are an AI assistant that processes user queries.
|
160 |
+
|
161 |
+
Determine if the user wants to add something to the knowledge base.
|
162 |
+
|
163 |
+
- If the user wants to add something, output 'add' followed by the content to add.
|
164 |
+
- If the user does not want to add something, output 'no action'.
|
165 |
|
166 |
+
Ensure your response is only 'add <content>' or 'no action'.
|
167 |
|
168 |
+
User Query: "{query}"
|
169 |
+
|
170 |
+
Response:
|
171 |
+
""".strip()
|
172 |
+
|
173 |
prompt = PromptTemplate.from_template(template)
|
174 |
|
175 |
+
if not llm:
|
176 |
+
llm = ChatOpenAI(model="gpt-4o-mini",temperature=0)
|
177 |
+
|
178 |
+
llm_with_tool = llm.bind_tools([AddToKnowledgeBase])
|
179 |
+
|
180 |
+
# template = "En tant qu'IA experte en marketing, tu travailles pour l'entreprise {enterprise}, si dans la question, il y a une demande d'ajout d'information à la base de connaissance, fait appel à la fonction add_to_knowledge_base en ajoutant l'information demandée, sinon, n'appelle pas la fonction. la question est la suivante: {query}"
|
181 |
+
|
182 |
+
# prompt = PromptTemplate.from_template(template)
|
183 |
+
chain = prompt | llm | StrOutputParser()
|
184 |
+
response = chain.invoke({"query": query}).strip().lower()
|
185 |
+
|
186 |
+
if response.startswith("add"):
|
187 |
+
item = response[len("add"):].strip()
|
188 |
+
if item:
|
189 |
+
add_to_knowledge_base(enterprise_id,item,index,enterprise_name)
|
190 |
+
print("added to knowledge base")
|
191 |
+
return True
|
192 |
+
|
193 |
+
print(response)
|
194 |
+
return False
|
195 |
+
|
196 |
+
|
197 |
+
|
198 |
+
|
199 |
+
def generate_response_via_langchain(query: str, stream: bool = False, model: str = "gpt-4o",context:str="",messages = [],style:str="formel",tonality:str="neutre",template:str = "",enterprise_name:str="",enterprise_id:str="",index:str=""):
|
200 |
+
# Define the prompt template
|
201 |
+
if template == "":
|
202 |
+
template = "En tant qu'IA experte en marketing, réponds avec un style {style} et une tonalité {tonality} dans ta communcation pour l'entreprise {enterprise}, sachant le context suivant: {context}, et l'historique de la conversation, {messages}, {query}"
|
203 |
|
204 |
# Initialize the OpenAI LLM with the specified model
|
205 |
if model.startswith("gpt"):
|
|
|
207 |
if model.startswith("mistral"):
|
208 |
llm = ChatMistralAI(model=model,temperature=0)
|
209 |
|
210 |
+
|
211 |
+
#handle_calling_add_to_knowledge_base(prompt.format(context=context,messages=messages,query=query,style=style,tonality=tonality,enterprise=enterprise_name))
|
212 |
+
if handle_calling_add_to_knowledge_base(query,enterprise_id,index,enterprise_name):
|
213 |
+
template += " la base de connaissance a été mise à jour"
|
214 |
+
|
215 |
+
language = detect_language(query)
|
216 |
+
template += f" Reponds en {language}"
|
217 |
# Create an LLM chain with the prompt and the LLM
|
218 |
+
prompt = PromptTemplate.from_template(template)
|
219 |
+
|
220 |
+
print(f"model: {model}")
|
221 |
+
print(f"marque: {enterprise_name}")
|
222 |
+
|
223 |
llm_chain = prompt | llm | StrOutputParser()
|
224 |
|
225 |
+
|
226 |
+
print(f"language: {language}")
|
227 |
+
|
228 |
if stream:
|
229 |
# Return a generator that yields streamed responses
|
230 |
return llm_chain.astream({ "query": query, "context": context, "messages": messages, "style": style, "tonality": tonality, "enterprise":enterprise_name })
|