[email protected] commited on
Commit
415e2c4
·
1 Parent(s): fc40f0c

Include pages by chapter

Browse files
app.py CHANGED
@@ -33,8 +33,8 @@ def init_app():
33
  st.session_state["chapters"] = config['chapters']
34
 
35
  for chapter in st.session_state["chapters"]:
36
- st.session_state[f"chapter_{chapter['key']}"] = {
37
- "num": 0,
38
  "messages": [],
39
  "prompt_system": chapter['prompt_system'],
40
  "prompt": chapter['prompts'],
@@ -65,10 +65,13 @@ def main():
65
  # st.write(f"**User ID:** {userId}")
66
 
67
  documents = st.Page("pages/documents.py", title="Vos documents", icon="📂")
68
- prompt_system = st.Page("pages/prompt_system.py", title="Prompt système", icon="🖊️", default=True)
69
  form = st.Page("pages/chapter_params.py", title="Paramètres", icon="📋")
70
 
71
- chapters_pages = []
 
 
 
 
72
 
73
  pg = st.navigation(
74
  {
@@ -76,7 +79,6 @@ def main():
76
  documents,
77
  ],
78
  "Configurations": [
79
- # prompt_system,
80
  form,
81
  ],
82
  "Dialogue": chapters_pages,
 
33
  st.session_state["chapters"] = config['chapters']
34
 
35
  for chapter in st.session_state["chapters"]:
36
+ st.session_state[f"chapter_{chapter['num']}"] = {
37
+ "num": chapter['num'],
38
  "messages": [],
39
  "prompt_system": chapter['prompt_system'],
40
  "prompt": chapter['prompts'],
 
65
  # st.write(f"**User ID:** {userId}")
66
 
67
  documents = st.Page("pages/documents.py", title="Vos documents", icon="📂")
 
68
  form = st.Page("pages/chapter_params.py", title="Paramètres", icon="📋")
69
 
70
+ chapters_pages = [
71
+ st.Page(f"pages/chap_{chapter['num']}.py", title=chapter['name'], icon="📄")
72
+ for chapter in st.session_state["chapters"]
73
+ ]
74
+
75
 
76
  pg = st.navigation(
77
  {
 
79
  documents,
80
  ],
81
  "Configurations": [
 
82
  form,
83
  ],
84
  "Dialogue": chapters_pages,
config.yaml CHANGED
@@ -12,50 +12,6 @@ prompts:
12
  - "Quelles sont les techniques de lutte biologique contre les nuisibles ?"
13
 
14
 
15
- # ----------------------------------------------------------
16
- # Gestion du formulaire dynamique
17
- # ----------------------------------------------------------
18
- # Version 1 : Liste de champs sous 'variables' (sans structure de 'parts')
19
- # ----------------------------------------------------------
20
- # Chaque champ est défini directement sous 'variables'.
21
- # Vous pouvez ajouter des champs en suivant ce format.
22
- # Pour utiliser cette version, laissez-la telle quelle et commentez la version 2 ci-dessous.
23
-
24
- # variables:
25
- # - label: "Région viticole"
26
- # nature: 'radio'
27
- # key: param1
28
- # options: ["Champagne", "Vin de Bordeaux", "Occitanie"]
29
- # value: # Valeur par défaut
30
-
31
- # - label: "Millésime"
32
- # nature: 'selectbox'
33
- # key: param2
34
- # options: ["2019", "2020", "2021", "2022"]
35
- # value: # Valeur par défaut
36
-
37
- # - label: "Budget prévu (en €)"
38
- # nature: 'numeric'
39
- # key: param3
40
- # value: # Valeur par défaut
41
-
42
- # - label: "Date de récolte"
43
- # nature: 'date'
44
- # key: param4
45
- # value: # Valeur par défaut
46
-
47
- # - label: "Remarques sur la récolte"
48
- # nature: 'text_area'
49
- # key: param5
50
- # value: # Valeur par défaut
51
-
52
-
53
- # Version 2 : Structure de 'parts' pour organiser les champs en sections
54
- # ----------------------------------------------------------------------
55
- # Chaque 'part' représente une section contenant un groupe de champs (par exemple : Panier, Livraison).
56
- # La clé 'number' permet d’ordonner les sections.
57
- # Pour activer cette version, commentez la Version 1 ci-dessus et décommentez cette section.
58
-
59
  chapters:
60
  - name: "Contexte et objectifs"
61
  num: 1
@@ -158,10 +114,6 @@ variables:
158
  prompt_system: "Prompt system par défaut"
159
 
160
  prompt_template: "
161
- Paramètre 1 : {param1}
162
- Paramètre 2 : {param2}
163
- Paramètre 3 : {param3}
164
- Paramètre 4 : {param4}
165
 
166
  Document de référence : {documentContext}
167
 
 
12
  - "Quelles sont les techniques de lutte biologique contre les nuisibles ?"
13
 
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  chapters:
16
  - name: "Contexte et objectifs"
17
  num: 1
 
114
  prompt_system: "Prompt system par défaut"
115
 
116
  prompt_template: "
 
 
 
 
117
 
118
  Document de référence : {documentContext}
119
 
pages/__init__.py ADDED
File without changes
pages/chap_1.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from pages.chatbot import page
3
+
4
+ # Définir les paramètres à transmettre
5
+ st.session_state["current_page"] = 1
6
+
7
+ # Appeler la fonction page avec les paramètres
8
+ page()
pages/chap_2.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from pages.chatbot import page
3
+
4
+ # Définir les paramètres à transmettre
5
+ st.session_state["current_page"] = 2
6
+
7
+ # Appeler la fonction page avec les paramètres
8
+ page()
pages/chap_3.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from pages.chatbot import page
3
+
4
+ # Définir les paramètres à transmettre
5
+ st.session_state["current_page"] = 3
6
+
7
+ # Appeler la fonction page avec les paramètres
8
+ page()
pages/chap_4.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from pages.chatbot import page
3
+
4
+ # Définir les paramètres à transmettre
5
+ st.session_state["current_page"] = 4
6
+
7
+ # Appeler la fonction page avec les paramètres
8
+ page()
pages/chap_5.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from pages.chatbot import page
3
+
4
+ # Définir les paramètres à transmettre
5
+ st.session_state["current_page"] = 5
6
+
7
+ # Appeler la fonction page avec les paramètres
8
+ page()
pages/chatbot.py CHANGED
@@ -1,12 +1,22 @@
1
  import streamlit as st
 
2
  from langchain_core.messages import AIMessage, HumanMessage
3
  from model import selector
4
  from util import getYamlConfig
5
  from st_copy_to_clipboard import st_copy_to_clipboard
6
 
 
 
 
 
 
 
 
 
 
7
  def display_messages():
8
 
9
- for i, message in enumerate(st.session_state.chat_history):
10
  if isinstance(message, AIMessage):
11
  with st.chat_message("AI"):
12
  # Display the model from the kwargs
@@ -22,46 +32,71 @@ def display_messages():
22
 
23
  def launchQuery(query: str = None):
24
 
 
25
  # Initialize the assistant's response
26
  full_response = st.write_stream(
27
  st.session_state["assistant"].ask(
28
  query,
29
  prompt_system=st.session_state.prompt_system,
30
- messages=st.session_state["chat_history"] if "chat_history" in st.session_state else [],
31
  variables=st.session_state["data_dict"]
32
  ))
33
 
34
  # Temporary placeholder AI message in chat history
35
- st.session_state["chat_history"].append(AIMessage(content=full_response, kwargs={"model": st.session_state["assistant"].getReadableModel()}))
36
  st.rerun()
37
 
38
 
39
- def show_prompts():
40
- yaml_data = getYamlConfig()["prompts"]
41
 
42
  expander = st.expander("Prompts pré-définis")
43
-
44
- for categroy in yaml_data:
45
- expander.write(categroy.capitalize())
46
 
47
- for item in yaml_data[categroy]:
48
- if expander.button(item, key=f"button_{item}"):
49
- launchQuery(item)
50
 
51
 
52
  def page():
53
- st.subheader("Posez vos questions")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
  if "assistant" not in st.session_state:
56
  st.text("Assistant non initialisé")
57
 
58
- if "chat_history" not in st.session_state:
59
- st.session_state["chat_history"] = []
 
 
 
 
 
 
 
60
 
61
  st.markdown("<style>iframe{height:50px;}</style>", unsafe_allow_html=True)
62
 
63
  # Collpase for default prompts
64
- show_prompts()
65
 
66
  # Models selector
67
  selector.ModelSelector()
@@ -70,10 +105,13 @@ def page():
70
  display_messages()
71
 
72
 
73
- user_query = st.chat_input("")
 
74
  if user_query is not None and user_query != "":
 
75
 
76
- st.session_state["chat_history"].append(HumanMessage(content=user_query))
 
77
 
78
  # Stream and display response
79
  launchQuery(user_query)
 
1
  import streamlit as st
2
+ import uuid
3
  from langchain_core.messages import AIMessage, HumanMessage
4
  from model import selector
5
  from util import getYamlConfig
6
  from st_copy_to_clipboard import st_copy_to_clipboard
7
 
8
+ chapter_num = 0
9
+ chapter_session_key = f"chapter_{chapter_num}"
10
+
11
+ def setChapter(num: int):
12
+ global chapter_num, chapter_session_key
13
+ chapter_num = num
14
+ chapter_session_key = f"chapter_{chapter_num}"
15
+
16
+
17
  def display_messages():
18
 
19
+ for i, message in enumerate(st.session_state[chapter_session_key]["messages"]):
20
  if isinstance(message, AIMessage):
21
  with st.chat_message("AI"):
22
  # Display the model from the kwargs
 
32
 
33
  def launchQuery(query: str = None):
34
 
35
+ print(f"launchQuery : {query}")
36
  # Initialize the assistant's response
37
  full_response = st.write_stream(
38
  st.session_state["assistant"].ask(
39
  query,
40
  prompt_system=st.session_state.prompt_system,
41
+ messages=st.session_state[chapter_session_key]["messages"] if "messages" in st.session_state[chapter_session_key] else [],
42
  variables=st.session_state["data_dict"]
43
  ))
44
 
45
  # Temporary placeholder AI message in chat history
46
+ st.session_state[chapter_session_key]["messages"].append(AIMessage(content=full_response, kwargs={"model": st.session_state["assistant"].getReadableModel()}))
47
  st.rerun()
48
 
49
 
50
+ def show_prompts(prompts: list[str]):
 
51
 
52
  expander = st.expander("Prompts pré-définis")
 
 
 
53
 
54
+ for i, p in enumerate(prompts):
55
+ if expander.button(p, key=f"button_{chapter_num}_{i}"):
56
+ launchQuery(p)
57
 
58
 
59
  def page():
60
+ yaml_data = getYamlConfig()["chapters"]
61
+
62
+
63
+ ###############################################
64
+ # Récupération du chapitre depuis YAML Config #
65
+ ###############################################
66
+
67
+ chapter_num = st.session_state.get('current_page', 0)
68
+ if chapter_num == 0:
69
+ return
70
+
71
+ setChapter(int(chapter_num))
72
+
73
+ chapter = next((ch for ch in yaml_data if ch['num'] == chapter_num), None)
74
+ if not chapter:
75
+ st.text("Chapitre non trouvé")
76
+ return
77
+
78
+
79
+ #################
80
+ # Some controls #
81
+ #################
82
 
83
  if "assistant" not in st.session_state:
84
  st.text("Assistant non initialisé")
85
 
86
+ if "messages" not in st.session_state[chapter_session_key]:
87
+ st.session_state[chapter_session_key]["messages"] = []
88
+
89
+
90
+ ############
91
+ #### UI ####
92
+ ############
93
+
94
+ st.subheader(chapter['name'])
95
 
96
  st.markdown("<style>iframe{height:50px;}</style>", unsafe_allow_html=True)
97
 
98
  # Collpase for default prompts
99
+ show_prompts(chapter['prompts'])
100
 
101
  # Models selector
102
  selector.ModelSelector()
 
105
  display_messages()
106
 
107
 
108
+ user_query = st.chat_input("", key=str(uuid.uuid4()))
109
+
110
  if user_query is not None and user_query != "":
111
+ print(user_query)
112
 
113
+ st.session_state[chapter_session_key]["messages"].append(HumanMessage(content=user_query))
114
+ print(st.session_state[chapter_session_key]["messages"])
115
 
116
  # Stream and display response
117
  launchQuery(user_query)