Spaces:
Sleeping
Sleeping
import streamlit as st | |
from langchain_core.messages import AIMessage, HumanMessage | |
from langchain_community.chat_models import ChatOpenAI | |
from dotenv import load_dotenv | |
from langchain_core.output_parsers import StrOutputParser | |
from langchain_core.prompts import ChatPromptTemplate | |
from langchain_mistralai.chat_models import ChatMistralAI | |
from download_chart import construct_plot | |
from prompt import get_prompts_list | |
from high_chart import test_chart | |
from export_doc import export_conversation,convert_pp_to_csv,get_conversation | |
import random | |
import pandas as pd | |
from codecarbon import EmissionsTracker | |
from ecologits.tracers.utils import compute_llm_impacts | |
import time | |
import itertools | |
load_dotenv() | |
def generate_random_color(): | |
# Generate random RGB values | |
r = random.randint(0, 255) | |
g = random.randint(0, 255) | |
b = random.randint(0, 255) | |
# Convert RGB to hexadecimal | |
color_hex = '#{:02x}{:02x}{:02x}'.format(r, g, b) | |
return color_hex | |
def format_pp_add_viz(pp): | |
y = 50 | |
x = 50 | |
for i in range(len(st.session_state['pp_grouped'])): | |
if st.session_state['pp_grouped'][i]['y'] == y and st.session_state['pp_grouped'][i]['x'] == x: | |
y += 5 | |
if y > 95: | |
y = 50 | |
x += 5 | |
if st.session_state['pp_grouped'][i]['name'] == pp: | |
return None | |
else: | |
st.session_state['pp_grouped'].append({'name':pp, 'x':x,'y':y, 'color':generate_random_color()}) | |
def format_context(partie_prenante_grouped,marque): | |
context = "la marque est " + marque + ".\n" | |
context += f"Le nombre de parties prenantes est {len(partie_prenante_grouped)} et ils sont les suivantes:\n" | |
for i,partie_prenante in enumerate(partie_prenante_grouped): | |
context += f"{i}.{partie_prenante['name']} est une partie prenante de {marque} et a un pouvoir de {partie_prenante['y']}% et une influence de {partie_prenante['x']}%.\n" | |
segmentation = ''' | |
Les parties prenantes sont segmentées en 4 catégories: | |
- Rendre satisfait: le pouvoir est entre 50 et 100 et l'influence est entre 0 et 50 | |
- Gérer étroitement: le pouvoir est entre 50 et 100 et l'influence est entre 50 et 100 | |
- Suivre de près: le pouvoir est entre 0 et 50 et l'influence est entre 0 et 50 | |
- Tenir informé: le pouvoir est entre 0 et 50 et l'influence est entre 50 et 100 | |
''' | |
context += segmentation | |
return context | |
def get_response(user_query, chat_history, context,llm=None,history_limit=5,stream=True): | |
template = """ | |
Fournir des réponses, en francais, précises et contextuelles en agissant comme un expert en affaires, en utilisant le contexte des parties prenantes et leur pouvoir en pourcentage et leur influence en pourcentage pour expliquer les implications pour la marque. Le modèle doit connecter les informations du contexte et de l'historique de la conversation pour donner une réponse éclairée à la dernière question posée. | |
Contexte: {context} | |
Chat history: {chat_history} | |
User question: {user_question} | |
""" | |
prompt = ChatPromptTemplate.from_template(template) | |
#llm = ChatOpenAI(model="gpt-4o") | |
if not llm: | |
llm = ChatOpenAI(model="gpt-4o") | |
elif llm == "GPT-4o": | |
llm = ChatOpenAI(model="gpt-4o") | |
elif llm == "Mistral (FR)": | |
llm = ChatMistralAI(model_name="mistral-large-latest") | |
chain = prompt | llm | |
if not stream: | |
return chain.invoke({ | |
"context": context, | |
"chat_history": chat_history[-history_limit:], | |
"user_question": user_query, | |
}) | |
chain = chain | StrOutputParser() | |
if history_limit: | |
return chain.stream({ | |
"context": context, | |
"chat_history": chat_history[-history_limit:], | |
"user_question": user_query, | |
}) | |
return chain.stream({ | |
"context": context, | |
"chat_history": chat_history, | |
"user_question": user_query, | |
}) | |
def get_response_with_impact(user_query, chat_history, context,llm=None,history_limit=5,stream=True): | |
model_vs_provider = { | |
"Mistral (FR)": ["mistral-large-latest","mistralai"], | |
"GPT-4o": ["gpt-4o","openai"] | |
} | |
if not stream: | |
start = time.perf_counter() | |
response = get_response(user_query, chat_history, context,llm,history_limit,stream) | |
request_latency = time.perf_counter() - start | |
token_count = response.response_metadata["token_usage"]["completion_tokens"] | |
nbre_out_tokens = token_count | |
model_name = model_vs_provider[st.session_state.model][0] | |
model_provider = model_vs_provider[st.session_state.model][1] | |
impact = compute_llm_impacts( | |
provider=model_provider, | |
model_name=model_name, | |
output_token_count=nbre_out_tokens, | |
request_latency=request_latency, | |
) | |
print(f"Request latency: {request_latency:.3f} s") | |
print(f"Output token count: {nbre_out_tokens}") | |
print(f"Impact: {impact.gwp.value} {impact.gwp.unit}") | |
st.session_state["partial_emissions"]["chatbot"]["el"] += impact.gwp.value | |
return response.content | |
else: | |
start = time.perf_counter() | |
response_generator = get_response(user_query, chat_history, context,llm,history_limit,stream) | |
wrapped_response_generator, token_count_generator = itertools.tee(response_generator) | |
token_count = 0 | |
final_response = st.write_stream(wrapped_response_generator) | |
request_latency = time.perf_counter() - start | |
for _ in token_count_generator: | |
token_count += 1 | |
nbre_out_tokens = token_count | |
model_name = model_vs_provider[st.session_state.model][0] | |
model_provider = model_vs_provider[st.session_state.model][1] | |
impact = compute_llm_impacts( | |
provider=model_provider, | |
model_name=model_name, | |
output_token_count=nbre_out_tokens, | |
request_latency=request_latency, | |
) | |
print(f"Request latency: {request_latency:.3f} s") | |
print(f"Output token count: {nbre_out_tokens}") | |
print(f"Impact: {impact.gwp.value} {impact.gwp.unit}") | |
st.session_state["partial_emissions"]["chatbot"]["el"] += impact.gwp.value | |
return final_response | |
def display_chart(): | |
if "pp_grouped" not in st.session_state or st.session_state['pp_grouped'] is None or len(st.session_state['pp_grouped']) == 0: | |
st.warning("Aucune partie prenante n'a été définie") | |
return None | |
plot = construct_plot() | |
st.plotly_chart(plot) | |
def show_prompts(): | |
get_prompts_list() | |
if st.button("Fermer"): | |
st.rerun() | |
def choose_model(index): | |
model = st.radio("Choisissez votre IA", ["(US) ChatGpt 4.o","(FR) Mistral AI - Large (open source)"],index=index) | |
if model == "(FR) Mistral AI - Large (open source)": | |
st.session_state.model = "Mistral (FR)" | |
if model == "(US) ChatGpt 4.o": | |
st.session_state.model = "GPT-4o" | |
if st.button("Valider"): | |
st.rerun() | |
def disp_carto_in_chat(): | |
if test_chart() == "saved": | |
st.rerun() | |
def dowmload_history(used_models=None): | |
brand_name = st.session_state['Nom de la marque'] | |
format = st.radio("Choisissez le document à télécharger",[f"Rapport des parties prenantes (PDF)",f"Tableau des parties prenantes (CSV)",f"Historique de conversation (Fichier Texte)"],index=None) | |
if format == f"Rapport des parties prenantes (PDF)": | |
with st.spinner("Generation en cours..."): | |
summary = get_response("Donne moi un RESUME de la Conversation", st.session_state.chat_history,format_context(st.session_state['pp_grouped'],st.session_state['Nom de la marque']),st.session_state.model) | |
summary = ''.join(summary) | |
pdf = export_conversation(AIMessage(content=summary).content,used_models=used_models) | |
st.session_state["partial_emissions"]["download_rapport"]["cc"] = st.session_state["emission"].stop() | |
if pdf: | |
st.download_button("Télécharger le PDF", data=pdf, file_name=f"Cartographie {brand_name}.pdf", mime="application/pdf") | |
if format == f"Tableau des parties prenantes (CSV)": | |
csv = convert_pp_to_csv(st.session_state['pp_grouped']) | |
if csv: | |
st.download_button("Télécharger le CSV", data=csv, file_name=f"parties_prenantes -{brand_name}-.csv", mime="application/vnd.ms-excel") | |
if format == f"Historique de conversation (Fichier Texte)": | |
conv = get_conversation() | |
if not conv: | |
st.error("Une erreur s'est produite lors de la récupération de l'historique de conversation") | |
return None | |
else: | |
conversation = "\n".join([f"{entry['speaker']}:\n{entry['text']}\n" for entry in conv]) | |
st.download_button("Télécharger l'historique de conversation", data=conversation, file_name=f"conversation {brand_name}.txt", mime="text/plain") | |
if st.button("Fermer"): | |
st.rerun() | |
def add_existing_pps(pp,pouvoir,influence): | |
for i in range(len(st.session_state['pp_grouped'])): | |
if st.session_state['pp_grouped'][i]['name'] == pp: | |
st.session_state['pp_grouped'][i]['x'] = influence | |
st.session_state['pp_grouped'][i]['y'] = pouvoir | |
return None | |
st.session_state['pp_grouped'].append({'name':pp, 'x':influence,'y':pouvoir, 'color':generate_random_color()}) | |
def load_csv(file): | |
df = pd.read_csv(file) | |
for index, row in df.iterrows(): | |
add_existing_pps(row['parties prenantes'],row['pouvoir'],row['influence']) | |
def import_conversation(): | |
uploaded_file = st.file_uploader("Télécharger le fichier CSV", type="csv") | |
if uploaded_file is not None: | |
file_name = uploaded_file.name | |
try: | |
load_csv(file_name) | |
brand_name_from_csv = file_name.split("-")[1] | |
st.session_state["Nom de la marque"] = brand_name_from_csv | |
st.rerun() | |
except Exception as e: | |
st.error("Erreur lors de la lecture du fichier") | |
def extract_format_prompts_from_response(response): | |
st.markdown("---") | |
st.markdown("**En découvrir plus avec l'IA RSE bziiit**") | |
prompts = response.split("\n") | |
prompts = [prompt.strip() for prompt in prompts if prompt.strip() != ""] | |
prompts_container = st.container() | |
with prompts_container: | |
for i,prompt in enumerate(prompts): | |
temp_p = f"{prompt} ➡️" | |
st.button(temp_p,key=f"exec_{i}",on_click=lambda i=i: st.session_state.chat_history.append(HumanMessage(content=prompts[i]))) | |
def extract_pp_from_query(query): | |
return " ".join(query.split(" ")[1:]) | |
def display_prompts(prompts): | |
for i,prompt in enumerate(prompts): | |
col1,col2 = st.columns([9,1]) | |
col1.markdown(f"{prompt}") | |
col2.button("➡️",key=f"execf_{i}",on_click=lambda i=i: st.session_state.chat_history.append(HumanMessage(content=prompts[i]))) | |
def display_chat(): | |
if "emission" not in st.session_state: | |
tracker = EmissionsTracker() | |
tracker.start() | |
st.session_state["emission"] = tracker | |
# app config | |
st.title("CHATBOT") | |
models_name = { | |
"Mistral (FR)":1, | |
"GPT-4o":0 | |
} | |
generated_prompt_question = '''En fonction de l'historique, proposez trois prompts pour continuer la conversation. Utilisez les informations fournies et les implications discutées: | |
- Prompt 1 : [Premier prompt suggéré] | |
- Prompt 2 : [Deuxième prompt suggéré] | |
- Prompt 3 : [Troisième prompt suggéré] | |
LA LISTE DOIT ETRE EN FRANCAIS CHAQUE LIGNE SANS LE NUMERO DE PROMPT SEULEMENT LE TEXTE DE LA QUESTION | |
''' | |
# session state | |
if "chat_history" not in st.session_state: | |
st.session_state.chat_history = [ | |
AIMessage(content="Salut, voici votre cartographie des parties prenantes. Que puis-je faire pour vous ?"), | |
] | |
if "model" not in st.session_state: | |
st.session_state.model = "GPT-4o" | |
if "used_models" not in st.session_state: | |
st.session_state.used_models = [] | |
#sticky bar at the top | |
header = st.container() | |
col1,col2,col3, col4,col5,col6 = header.columns([2,3,2,3,2,1]) | |
if col1.button("Prompts"): | |
show_prompts() | |
if col2.button(f"Modèle: {st.session_state.model}"): | |
index = models_name[st.session_state.model] | |
choose_model(index) | |
if col3.button("Ma Carto"): | |
disp_carto_in_chat() | |
if col4.button("Télécharger"): | |
dowmload_history(st.session_state.used_models) | |
header.write("""<div class='fixed-header'/>""", unsafe_allow_html=True) | |
# Custom CSS for the sticky header | |
st.markdown( | |
""" | |
<style> | |
div[data-testid="stVerticalBlock"] div:has(div.fixed-header) { | |
position: sticky; | |
top: 2.875rem; | |
background-color: white; | |
z-index: 999; | |
} | |
.fixed-header { | |
border-bottom: 0px solid black; | |
} | |
</style> | |
""", | |
unsafe_allow_html=True | |
) | |
# conversation | |
for message in st.session_state.chat_history: | |
if isinstance(message, AIMessage): | |
with st.chat_message("AI"): | |
st.write(message.content) | |
if "cartographie" in message.content: | |
st.markdown("\n") | |
display_chart() | |
if message.content == st.session_state.chat_history[0].content: | |
st.markdown("---") | |
st.markdown("**En découvrir plus avec l'IA RSE bziiit**") | |
first_prompts = ["En plus des parties prenantes déjà identifiées que tu peux consulter, quels groupes ou individus, impactés par les activités de mon organisation, devrais-je ajouter dans notre cartographie des parties prenantes ?", | |
"Quels sont les principaux acteurs internes et externes qui influencent ou sont influencés par mon organisation, et comment leurs intérêts ou préoccupations peuvent varier selon les différents domaines d'activité ?", | |
"En tenant compte de ma chaîne de valeur complète, quels sont les différentes parties prenantes stratégiques, incluant les partenaires commerciaux, les régulateurs, les groupes de pression, et la communauté, et comment leurs rôles et influences interagissent pour affecter les objectifs à court et long terme de mon organisation ?"] | |
display_prompts(first_prompts) | |
elif isinstance(message, HumanMessage): | |
with st.chat_message("Moi"): | |
st.write(message.content) | |
#check if the last message is from the user , that means execute button has been clicked in the prompts | |
last_message = st.session_state.chat_history[-1] | |
if isinstance(last_message, HumanMessage): | |
with st.chat_message("AI"): | |
if last_message.content.startswith("/rajoute"): | |
response = "Partie prenante ajoutée" | |
st.write(response) | |
st.session_state.chat_history.append(AIMessage(content=response)) | |
else: | |
st.markdown(f"**{st.session_state.model}**") | |
if st.session_state.model not in st.session_state.used_models: | |
st.session_state.used_models.append(st.session_state.model) | |
response = get_response_with_impact(last_message.content, st.session_state.chat_history,format_context(st.session_state['pp_grouped'],st.session_state['Nom de la marque']),st.session_state.model) | |
st.session_state.chat_history.append(AIMessage(content=response)) | |
with st.spinner("Proposition de prompts..."): | |
propositions_prompts = get_response_with_impact(generated_prompt_question, st.session_state.chat_history,format_context(st.session_state['pp_grouped'],st.session_state['Nom de la marque']),st.session_state.model,history_limit=1,stream=False) | |
extract_format_prompts_from_response(propositions_prompts) | |
st.session_state["partial_emissions"]["chatbot"]["cc"] = st.session_state["emission"].stop() | |
if "pp_grouped" not in st.session_state or st.session_state['pp_grouped'] is None or len(st.session_state['pp_grouped']) == 0: | |
st.session_state['pp_grouped'] = [] | |
if "Nom de la marque" not in st.session_state: | |
st.session_state["Nom de la marque"] = "" | |
# user input | |
user_query = st.chat_input("Par ici...") | |
if user_query is not None and user_query != "": | |
st.session_state.chat_history.append(HumanMessage(content=user_query)) | |
with st.chat_message("Moi"): | |
st.markdown(user_query) | |
with st.chat_message("AI"): | |
st.markdown(f"**{st.session_state.model}**") | |
if st.session_state.model not in st.session_state.used_models: | |
st.session_state.used_models.append(st.session_state.model) | |
if user_query.startswith("/rajoute"): | |
partie_prenante = extract_pp_from_query(user_query) | |
format_pp_add_viz(partie_prenante) | |
disp_carto_in_chat() | |
else: | |
#response = st.write_stream(get_response(user_query, st.session_state.chat_history,format_context(st.session_state['pp_grouped'],st.session_state['Nom de la marque']),st.session_state.model)) | |
response = get_response_with_impact(user_query, st.session_state.chat_history,format_context(st.session_state['pp_grouped'],st.session_state['Nom de la marque']),st.session_state.model) | |
st.session_state.chat_history.append(AIMessage(content=response)) | |
with st.spinner("Proposition de prompts..."): | |
propositions_prompts = get_response_with_impact(generated_prompt_question, st.session_state.chat_history,format_context(st.session_state['pp_grouped'],st.session_state['Nom de la marque']),st.session_state.model,history_limit=1,stream=False) | |
extract_format_prompts_from_response(propositions_prompts) | |
st.session_state["partial_emissions"]["chatbot"]["cc"] = st.session_state["emission"].stop() | |