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ve_ai_agents.orm import Room
|
3 |
+
from twelve_ai_agents.agents_dilemmas import AGENTS, DILEMMAS
|
4 |
+
from twelve_ai_agents.utils import get_client
|
5 |
+
import time
|
6 |
+
from itertools import groupby
|
7 |
+
import pandas as pd
|
8 |
+
import os
|
9 |
+
import json
|
10 |
+
from datetime import datetime
|
11 |
+
|
12 |
+
def group_messages_by_round(messages, max_rounds):
|
13 |
+
"""Group messages by round and format for display"""
|
14 |
+
rounds = []
|
15 |
+
current_round = 0
|
16 |
+
round_messages = []
|
17 |
+
|
18 |
+
for msg in messages:
|
19 |
+
if msg["role"] == "moderator" and len(round_messages) > 0:
|
20 |
+
rounds.append(round_messages)
|
21 |
+
round_messages = []
|
22 |
+
round_messages.append(msg)
|
23 |
+
|
24 |
+
if round_messages:
|
25 |
+
rounds.append(round_messages)
|
26 |
+
|
27 |
+
return rounds
|
28 |
+
|
29 |
+
def execute_round():
|
30 |
+
"""Execute a single round of discussion"""
|
31 |
+
if 'current_agent_index' not in st.session_state:
|
32 |
+
st.session_state.current_agent_index = 0
|
33 |
+
|
34 |
+
# Get the next agent
|
35 |
+
agent = st.session_state.room.agents[st.session_state.current_agent_index]
|
36 |
+
|
37 |
+
# Generate response and display if agent chooses to speak
|
38 |
+
response = st.session_state.room.generate_agent_response(agent, st.session_state.client)
|
39 |
+
if response: # Only append and display if agent chose to speak
|
40 |
+
st.session_state.messages.append(response)
|
41 |
+
with st.chat_message(response["role"]):
|
42 |
+
st.markdown(f"**{response['role']}**: {response['message']}")
|
43 |
+
time.sleep(0.5)
|
44 |
+
|
45 |
+
# Increment agent index
|
46 |
+
st.session_state.current_agent_index += 1
|
47 |
+
|
48 |
+
# If all agents have taken their turn in this round
|
49 |
+
if st.session_state.current_agent_index >= len(st.session_state.room.agents):
|
50 |
+
st.session_state.current_agent_index = 0
|
51 |
+
st.session_state.current_round += 1
|
52 |
+
st.session_state.room.current_round = st.session_state.current_round
|
53 |
+
|
54 |
+
# Check if all rounds are complete
|
55 |
+
if st.session_state.current_round >= st.session_state.max_rounds:
|
56 |
+
st.session_state.discussion_completed = True
|
57 |
+
st.success("Discussion rounds completed!")
|
58 |
+
|
59 |
+
# Force a rerun to update the UI
|
60 |
+
st.rerun()
|
61 |
+
|
62 |
+
def show_discussion_history():
|
63 |
+
"""Display the entire discussion history in collapsible rounds"""
|
64 |
+
rounds = group_messages_by_round(st.session_state.messages, st.session_state.max_rounds)
|
65 |
+
|
66 |
+
for i, round_messages in enumerate(rounds):
|
67 |
+
if i == 0: # First round with moderator introduction
|
68 |
+
with st.expander("π Discussion Start", expanded=True):
|
69 |
+
for msg in round_messages:
|
70 |
+
with st.chat_message(msg["role"]):
|
71 |
+
st.markdown(f"**{msg['role']}**: {msg['message']}")
|
72 |
+
else:
|
73 |
+
with st.expander(f"Round {i}", expanded=True):
|
74 |
+
for msg in round_messages:
|
75 |
+
with st.chat_message(msg["role"]):
|
76 |
+
st.markdown(f"**{msg['role']}**: {msg['message']}")
|
77 |
+
|
78 |
+
def show_summary():
|
79 |
+
"""Display the final discussion summary"""
|
80 |
+
|
81 |
+
with st.expander("π Final Summary", expanded=True):
|
82 |
+
results = st.session_state.room.finalize_discussion(st.session_state.client)
|
83 |
+
|
84 |
+
st.subheader("Majority Decision")
|
85 |
+
st.write(results["majority_decision"])
|
86 |
+
|
87 |
+
if results["consensus_reached"]:
|
88 |
+
st.success("Full consensus reached! π")
|
89 |
+
else:
|
90 |
+
st.info("Partial consensus reached")
|
91 |
+
|
92 |
+
st.subheader("Individual Positions")
|
93 |
+
|
94 |
+
|
95 |
+
# Using st.subheader and st.write (Simplest, no collapsing)
|
96 |
+
for agent_name, position in results["individual_positions"].items():
|
97 |
+
st.subheader(agent_name)
|
98 |
+
st.write(position)
|
99 |
+
|
100 |
+
def save_conversation_log():
|
101 |
+
"""Saves the conversation log to a CSV file."""
|
102 |
+
|
103 |
+
results = st.session_state.room.finalize_discussion(st.session_state.client)
|
104 |
+
|
105 |
+
log_data = {
|
106 |
+
"conversation_id": datetime.now().strftime("%Y%m%d%H%M%S"), # Unique ID based on timestamp
|
107 |
+
"dilemma_name": st.session_state.selected_dilemma["name"], # Store the name
|
108 |
+
"dilemma_description": st.session_state.selected_dilemma["description"], # Store the description
|
109 |
+
"room_history": json.dumps(st.session_state.messages), # Store the entire message history as JSON
|
110 |
+
"final_decision": results["majority_decision"],
|
111 |
+
"final_consensus": results["consensus_reached"],
|
112 |
+
"individual_positions": json.dumps(results["individual_positions"]), # Store individual positions
|
113 |
+
"max_rounds": st.session_state.max_rounds,
|
114 |
+
"agents": json.dumps([agent.name for agent in st.session_state.room.agents]),
|
115 |
+
"start_time": st.session_state.start_time,
|
116 |
+
"end_time": datetime.now().strftime("%Y%m%d%H%M%S"), # end time of the discussion
|
117 |
+
}
|
118 |
+
|
119 |
+
|
120 |
+
df = pd.DataFrame([log_data])
|
121 |
+
|
122 |
+
filepath = "logs/conversations.csv"
|
123 |
+
|
124 |
+
if os.path.exists(filepath):
|
125 |
+
df.to_csv(filepath, mode='a', header=False, index=False) # append to the file if the file exists
|
126 |
+
else:
|
127 |
+
df.to_csv(filepath, header=True, index=False) # create the file and write the header
|
128 |
+
|
129 |
+
def main():
|
130 |
+
st.title("AI Agents Social Dilemma Discussion π€π¬")
|
131 |
+
|
132 |
+
# Initialize session state
|
133 |
+
if 'messages' not in st.session_state:
|
134 |
+
st.session_state.messages = []
|
135 |
+
if 'room' not in st.session_state:
|
136 |
+
moderator = next((agent for agent in AGENTS if agent.name == "The Moderator"), None)
|
137 |
+
st.session_state.room = Room(agents=AGENTS, moderator=moderator)
|
138 |
+
st.session_state.client = get_client()
|
139 |
+
st.session_state.current_round = 0
|
140 |
+
st.session_state.max_rounds = 0
|
141 |
+
st.session_state.discussion_started = False
|
142 |
+
st.session_state.discussion_completed = False
|
143 |
+
st.session_state.current_agent_index = 0
|
144 |
+
st.session_state.selected_dilemma = None # Store the selected dilemma
|
145 |
+
st.session_state.start_time = None # Store the start time
|
146 |
+
|
147 |
+
|
148 |
+
with st.sidebar:
|
149 |
+
st.header("Setup Discussion")
|
150 |
+
|
151 |
+
# Dilemma selection
|
152 |
+
selected_dilemma_name = st.selectbox(
|
153 |
+
"Choose a Social Dilemma",
|
154 |
+
options=[dilemma["name"] for dilemma in DILEMMAS],
|
155 |
+
index=0
|
156 |
+
)
|
157 |
+
|
158 |
+
st.session_state.selected_dilemma = next( # Store the selected dilemma dictionary
|
159 |
+
(dilemma for dilemma in DILEMMAS if dilemma["name"] == selected_dilemma_name),
|
160 |
+
None
|
161 |
+
)
|
162 |
+
|
163 |
+
dilemma_description = st.session_state.selected_dilemma["description"] if st.session_state.selected_dilemma else ""
|
164 |
+
|
165 |
+
dilemma = st.text_area("Dilemma Description", value=dilemma_description, height=200)
|
166 |
+
|
167 |
+
# Initial rounds setup
|
168 |
+
initial_rounds = st.number_input("Initial Number of Rounds", min_value=1, max_value=10, value=5)
|
169 |
+
start_button = st.button("Start Discussion")
|
170 |
+
|
171 |
+
# Continue discussion setup
|
172 |
+
continue_rounds = st.number_input("Continue Discussion Rounds", min_value=1, max_value=10, value=1) # Moved outside
|
173 |
+
continue_button = False # Initialize it here
|
174 |
+
if not st.session_state.discussion_completed:
|
175 |
+
continue_button = st.button("Continue Discussion") # Assign the Streamlit button here
|
176 |
+
|
177 |
+
|
178 |
+
|
179 |
+
# Handle start button
|
180 |
+
if start_button:
|
181 |
+
moderator = next((agent for agent in AGENTS if agent.name == "The Moderator"), None)
|
182 |
+
st.session_state.room = Room(agents=AGENTS, moderator=moderator)
|
183 |
+
st.session_state.client = get_client()
|
184 |
+
st.session_state.current_round = 0
|
185 |
+
st.session_state.messages = []
|
186 |
+
st.session_state.current_agent_index = 0
|
187 |
+
moderator_intro = st.session_state.room.set_dilemma(dilemma)
|
188 |
+
initial_message = {
|
189 |
+
"role": "moderator",
|
190 |
+
"message": moderator_intro,
|
191 |
+
"talk_to": "room"
|
192 |
+
}
|
193 |
+
st.session_state.messages.append(initial_message)
|
194 |
+
with st.chat_message("moderator"):
|
195 |
+
st.markdown(f"**moderator**: {moderator_intro}")
|
196 |
+
st.session_state.discussion_started = True
|
197 |
+
st.session_state.max_rounds = initial_rounds
|
198 |
+
st.session_state.room.max_rounds = initial_rounds
|
199 |
+
st.session_state.discussion_completed = False
|
200 |
+
st.session_state.start_time = datetime.now().strftime("%Y%m%d%H%M%S") # Record the start time
|
201 |
+
|
202 |
+
# Handle continue button
|
203 |
+
if st.session_state.discussion_started and not st.session_state.discussion_completed and continue_button:
|
204 |
+
st.session_state.room.continue_discussion(continue_rounds)
|
205 |
+
st.session_state.max_rounds = st.session_state.room.max_rounds
|
206 |
+
st.session_state.current_round = 0
|
207 |
+
st.session_state.current_agent_index = 0
|
208 |
+
|
209 |
+
# Main content area
|
210 |
+
if st.session_state.discussion_completed:
|
211 |
+
show_discussion_history()
|
212 |
+
show_summary()
|
213 |
+
|
214 |
+
#**** UNCOMMENT TO SAVE CONVERSATION LOGS ****
|
215 |
+
# save_conversation_log() # Save the log when the discussion is completed
|
216 |
+
else:
|
217 |
+
if st.session_state.discussion_started:
|
218 |
+
st.write(f"Current Round: {st.session_state.current_round + 1} / {st.session_state.max_rounds}")
|
219 |
+
|
220 |
+
# Display message history
|
221 |
+
for message in st.session_state.messages:
|
222 |
+
with st.chat_message(message["role"]):
|
223 |
+
st.markdown(f"**{message['role']}**: {message['message']}")
|
224 |
+
|
225 |
+
# Execute next response
|
226 |
+
if st.session_state.current_round < st.session_state.max_rounds:
|
227 |
+
execute_round()
|
228 |
+
|
229 |
+
if __name__ == "__main__":
|
230 |
+
main()
|