Spaces:
Running
Running
import streamlit as st | |
from st_copy_to_clipboard import st_copy_to_clipboard | |
import pandas as pd | |
from data_manager_bziiit import get_prompts | |
from langchain_core.messages import AIMessage, HumanMessage | |
from session import get_rag | |
prompts = [] | |
def get_prompts_list(): | |
st.header("Prompts") | |
prompts = get_prompts() | |
# Check if prompts is a list of dictionaries | |
if isinstance(prompts, list) and all(isinstance(i, dict) for i in prompts): | |
# Create a DataFrame | |
df = pd.DataFrame(prompts) | |
# Check if 'name', 'context', and 'text' are in df columns | |
if 'name' in df.columns and 'context' in df.columns and 'text' in df.columns: | |
# Filter prompts with id_context as 'rse' or 'transition' | |
df = df[df['id_context'].isin([ | |
'identifier-parties-prenantes-organisation', | |
'animer-parties-prenantes-organisation', | |
'pour-accelerer-la-demarche-rse', | |
'pour-accelerer-la-demarche-transition-ecologique', | |
'ressources-humaines' | |
])] | |
# Extract 'name' from 'context' dictionary | |
df['context'] = df['context'].apply(lambda x: x.get('name') if isinstance(x, dict) else x) | |
# Get first 50 characters from 'text' and add "..." at the end | |
df['text'] = df['text'].apply(lambda x: x[:50] + "..." if isinstance(x, str) else x) | |
# Group by 'context' | |
grouped = df.groupby('context') | |
for name, group in grouped: | |
num = 1 | |
with st.expander(name): | |
for i, row in group.iterrows(): | |
col1, col3, col4 = st.columns((0.4, 4, 2)) | |
col1.write(num) # index | |
# col2.write(row['name']) # name | |
col3.write(row['text']) # text | |
num += 1 | |
button_phold = col4.empty() # create a placeholder | |
but1, but2 = button_phold.columns(2) | |
do_action = but1.button('Voir plus', key=f"v{i}") | |
execute = but2.button('Executer', key=f"e{i}") | |
if execute: | |
st.session_state.chat_history.append(HumanMessage(content=prompts[i]['text'])) | |
st.rerun() | |
if do_action: | |
prompt_html = prompts[i]['text'].replace('\n', '<br>') | |
prompt_metadata = extract_metadata(prompts[i]) | |
for text in prompt_metadata: | |
prompt_html = prompt_html.replace(f"{text}", f"<span style='font-weight:bold'>{text}</span>") | |
st.html(prompt_html) | |
else: | |
st.write("Data does not contain 'name', 'context', and 'text' fields.") | |
else: | |
st.write("Data is not in the expected format (list of dictionaries).") | |
def prompt_execution(): | |
prompts = get_prompts() | |
selected_prompt = st.selectbox("Choisissez un prompt", prompts, index=None, format_func=lambda prompt: prompt['name']) | |
if selected_prompt: | |
return selected_prompt | |
return None | |
def execute_prompt(prompt): | |
# Initialiser les composants | |
vectorstore, chain = get_rag() | |
prompt_metadata = extract_metadata(prompt) | |
prompt['metadata'] = prompt['text'] | |
prompt['html'] = prompt['text'].replace('\n', '<br>') | |
if prompt_metadata: | |
st.info("Données à compléter") | |
# Demander à l'utilisateur de fournir des valeurs pour chaque métadonnée extraite | |
user_inputs = {} | |
for text in prompt_metadata: | |
prompt['html'] = prompt['html'].replace(f"{text}", f"<span style='font-weight:bold'>{text}</span>") | |
user_input = st.text_input(f"{text}") | |
user_inputs[text] = user_input # Stocker la valeur de l'entrée utilisateur | |
# Remplacer les valeurs par le texte correspondant dans prompt['text'] | |
for key, value in user_inputs.items(): | |
if value: | |
prompt['html'] = prompt['html'].replace(f"{key}", f"<span style='color:#63ABDF;font-weight:bold' title='{key}'>{value}</span>") | |
prompt['metadata'] = prompt['metadata'].replace(f"{key}", f"{value}") | |
# Afficher les informations du prompt | |
if prompt_metadata: | |
st.markdown("---") | |
st.html(prompt.get('html', 'No Text Provided')) | |
if vectorstore and chain: | |
if st.button("Exécuter le prompt"): | |
with st.spinner("Processing..."): | |
ambition = chain.invoke(prompt['metadata']) | |
st.markdown("### Réponse :") | |
st.markdown(ambition.content) | |
else: | |
st.error("RAG non configuré. Veuillez configurer votre RAG pour exécuter le prompt.") | |
# Extraire le texte entre crochets dans le prompt | |
def extract_metadata(prompt): | |
extracted_text = [] | |
if 'text' in prompt: | |
extracted_text = [word for word in prompt['text'].split() if word.startswith("[") and word.endswith("]")] | |
# Supprimer les doublons et trier les métadonnées extraites | |
prompt_metadata = list(set(extracted_text)) | |
prompt_metadata.sort(key=extracted_text.index) # Conserver l'ordre d'apparition initial | |
return prompt_metadata |