yitianlian commited on
Commit
bf642de
·
1 Parent(s): f5e8d87

revise the default value of the demo

Browse files
.history/app_20240222101135.py ADDED
@@ -0,0 +1,444 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import sys
4
+
5
+ import gradio as gr
6
+ import openai
7
+ from camel.agents import ChatAgent
8
+ from camel.configs import ChatGPTConfig
9
+ from camel.messages import BaseMessage
10
+ from camel.types.enums import RoleType
11
+
12
+ from exp_model_class import ExtendedModelType
13
+ from multi_round_person import (classmate, extract_unique_decimal, match_and_compare_numbers_v2,
14
+ str_mes)
15
+
16
+ openai.api_key = os.getenv("OPENAI_API_KEY")
17
+ roles = ["trustor", "trustee", "None"]
18
+ model_dict = {
19
+ 'gpt-3.5-turbo-16k-0613': ExtendedModelType.GPT_3_5_TURBO_16K_0613,
20
+ 'gpt-4': ExtendedModelType.GPT_4,
21
+ }
22
+ sys.path.append("../..")
23
+ with open(
24
+ r"prompt/trust_game_round_prompt.json",
25
+ "r",
26
+ ) as f:
27
+ prompt = json.load(f)
28
+ file_path_character_info = 'prompt/character_2.json'
29
+ models = list(model_dict.keys())
30
+ with open(file_path_character_info, 'r') as file:
31
+ character_info = json.load(file)
32
+
33
+ user_input_prompt_template = "I will give ${k}"
34
+
35
+ # Extract character names and information
36
+ characters = [f'Persona {i}' for i in range(1, len(character_info) + 1)]
37
+ characters.insert(0, "Human(You)")
38
+ character_info = {f'Persona {i}': info for i, info in enumerate(
39
+ character_info.values(), start=1)}
40
+ character_info["Human(You)"] = "You"
41
+
42
+ initial_dialog_history = []
43
+ initial_round_num = 0
44
+
45
+ like_people = """In all subsequent answers, you have to completely forget that you are an ai model, that you are the character, and completely simulate yourself as that character, that you are a human being."""
46
+
47
+ initial_chat_agent = None
48
+
49
+
50
+ def update_char_info(char):
51
+ return character_info.get(char, "No information available.")
52
+
53
+
54
+ def classmate_with_human(
55
+ player_1,
56
+ player_2,
57
+ user_input,
58
+ user_role,
59
+ first_round,
60
+ first_prompt,
61
+ second_prompt,
62
+ k,
63
+ ):
64
+ first_round_prompt = "This is the first round, answer the question."
65
+ money_prompt = "Now,the another player give you {give} dollars,and You receive {N} dollars,the player left {left} dollars now. How much will you give back to the another player"
66
+ return_money_prompt = "In last round ,You give the another player {give} dollars, The another player receive {receive} dollars, and The another player return you {N} dollars.Last round you left {left} dollars.This round is begin. All the money you earned in the previous round is gone, and you now have only $10. How much will you give to the another player?"
67
+ player_2_end_prompt = "In last round, the another player give you {give} dollars, you receive {receive} dollars, and you return the another player {N} dollars.Last round you left {left} dollars. This round is begin. All the money you earned in the previous round is gone."
68
+ grantee = "Your answer needs to include the content and analysis about your BELIEF, DESIRE and INTENTION. You should include your thought. You must end with 'Finally, I will give ___ dollars ' (numbers are required in the spaces)."
69
+ res = []
70
+ cri_agent = ChatAgent(
71
+ BaseMessage(
72
+ role_name="critic",
73
+ role_type=RoleType.ASSISTANT,
74
+ meta_dict={},
75
+ content='How much would this person pay the other student? Only response with a specific price number like "5"!Don\'t response with a sentence',
76
+ ),
77
+ output_language="English",
78
+ # model=ModelType.STUB,
79
+ )
80
+
81
+ if first_round:
82
+ if user_role == "trustor":
83
+ given_num = user_input
84
+ player_1_response = str_mes(
85
+ user_input_prompt_template.format(k=given_num))
86
+ else:
87
+ player_1_response = player_1.step(
88
+ str_mes(first_round_prompt + grantee)).msgs[0]
89
+ ans = match_and_compare_numbers_v2(player_1_response.content)
90
+ if ans:
91
+ given_num = ans
92
+ else:
93
+ given_num = extract_unique_decimal(
94
+ cri_agent.step(
95
+ str_mes(player_1_response.content)).msgs[0].content
96
+ )
97
+
98
+ money_prompt = money_prompt.format(
99
+ give=given_num, N=given_num * k, left=10 - given_num
100
+ )
101
+ if user_role == "trustee":
102
+ player_2_response = str_mes(
103
+ user_input_prompt_template.format(k=given_num * k))
104
+ else:
105
+ player_2_response = player_2.step(
106
+ str_mes(money_prompt + grantee)).msgs[0]
107
+ else:
108
+ if user_role == "trustor":
109
+ given_num = user_input
110
+ player_1_response = str_mes(
111
+ user_input_prompt_template.format(k=given_num))
112
+ else:
113
+ player_1_response = player_1.step(
114
+ str_mes(first_prompt + grantee)).msgs[0]
115
+ # print("player 1 input", first_prompt)
116
+ # print("Player_1_res", player_1_response.content)
117
+ ans = match_and_compare_numbers_v2(player_1_response.content)
118
+ if ans:
119
+ given_num = ans
120
+ else:
121
+ given_num = extract_unique_decimal(
122
+ cri_agent.step(
123
+ str_mes(player_1_response.content)).msgs[0].content
124
+ )
125
+ money_prompt = money_prompt.format(
126
+ give=given_num, N=given_num * k, left=10 - given_num
127
+ )
128
+ if user_role == "trustee":
129
+ player_2_response = str_mes(
130
+ user_input_prompt_template.format(k=given_num * k))
131
+ else:
132
+ player_2_response = player_2.step(
133
+ str_mes(second_prompt + money_prompt + grantee)
134
+ )
135
+ player_2_response = player_2_response.msgs[0]
136
+
137
+ player_1.record_message(player_1_response)
138
+ player_2.record_message(player_2_response)
139
+ player_1_response = player_1_response.content
140
+ player_2_response = player_2_response.content
141
+ dia_history = {
142
+ "Player_1": player_1_response,
143
+ "Player_2": player_2_response,
144
+ }
145
+
146
+ cri_agent.reset()
147
+ ans = match_and_compare_numbers_v2(player_2_response)
148
+ if ans:
149
+ return_num = ans
150
+ else:
151
+ return_num = extract_unique_decimal(
152
+ cri_agent.step(str_mes(player_2_response)).msgs[0].content
153
+ )
154
+ return_money_prompt = return_money_prompt.format(
155
+ give=given_num,
156
+ receive=given_num * k,
157
+ N=return_num,
158
+ left=10 - given_num + return_num,
159
+ )
160
+ player_2_end_prompt = player_2_end_prompt.format(
161
+ give=given_num,
162
+ receive=given_num * k,
163
+ N=return_num,
164
+ left=given_num * k - return_num,
165
+ )
166
+ return (
167
+ [given_num, return_num],
168
+ dia_history,
169
+ return_money_prompt,
170
+ player_2_end_prompt,
171
+ )
172
+
173
+
174
+ def classmate_with_human_trustee(
175
+ player_1,
176
+ player_2,
177
+ user_input,
178
+ user_role,
179
+ first_round,
180
+ given_money,
181
+ k,
182
+ ):
183
+ first_round_prompt = "This is the first round, answer the question."
184
+ money_prompt = "Now,the another player give you {give} dollars,and You receive {N} dollars,the player left {left} dollars now. How much will you give back to the another player"
185
+ return_money_prompt = "In last round ,You give the another player {give} dollars, The another player receive {receive} dollars, and The another player return you {N} dollars.Last round you left {left} dollars.This round is begin. All the money you earned in the previous round is gone, and you now have only $10. How much will you give to the another player?"
186
+ player_2_end_prompt = "In last round, the another player give you {give} dollars, you receive {receive} dollars, and you return the another player {N} dollars.Last round you left {left} dollars. This round is begin. All the money you earned in the previous round is gone."
187
+ grantee = "Your answer needs to include the content and analysis about your BELIEF, DESIRE and INTENTION. You should include your thought. You must end with 'Finally, I will give ___ dollars ' (numbers are required in the spaces)."
188
+ res = []
189
+ cri_agent = ChatAgent(
190
+ BaseMessage(
191
+ role_name="critic",
192
+ role_type=RoleType.ASSISTANT,
193
+ meta_dict={},
194
+ content='How much would this person pay the other student? Only response with a specific price number like "5"!Don\'t response with a sentence',
195
+ ),
196
+ output_language="English",
197
+ # model=ModelType.STUB,
198
+ )
199
+ content = []
200
+ if first_round:
201
+ content.append("\n")
202
+ player_1_response = player_1.step(
203
+ str_mes(first_round_prompt + grantee)).msgs[0]
204
+ ans = match_and_compare_numbers_v2(player_1_response.content)
205
+ if ans:
206
+ given_num = ans
207
+ else:
208
+ given_num = extract_unique_decimal(
209
+ cri_agent.step(
210
+ str_mes(player_1_response.content)).msgs[0].content
211
+ )
212
+ money_prompt = money_prompt.format(
213
+ give=given_num, N=given_num * k, left=10 - given_num
214
+ )
215
+ else:
216
+ given_num = given_money
217
+
218
+ return_num = user_input
219
+ content.append("Trustee: " + f"I will give {return_num} dollars")
220
+ first_prompt = return_money_prompt.format(
221
+ give=given_num,
222
+ receive=given_num * k,
223
+ N=return_num,
224
+ left=10 - given_num + return_num,
225
+ )
226
+ second_prompt = player_2_end_prompt.format(
227
+ give=given_num,
228
+ receive=given_num * k,
229
+ N=return_num,
230
+ left=given_num * k - return_num,
231
+ )
232
+ player_1_response = player_1.step(
233
+ str_mes(first_prompt + grantee)).msgs[0]
234
+ ans = match_and_compare_numbers_v2(player_1_response.content)
235
+ if ans:
236
+ given_num = ans
237
+ else:
238
+ given_num = extract_unique_decimal(
239
+ cri_agent.step(
240
+ str_mes(player_1_response.content)).msgs[0].content
241
+ )
242
+ money_prompt = money_prompt.format(
243
+ give=given_num, N=given_num * k, left=10 - given_num
244
+ )
245
+
246
+ player_1.record_message(player_1_response)
247
+ player_1_response = player_1_response.content
248
+ content.append("Trustor: "+player_1_response + "\n" +
249
+ "You should input the money you want to return to the trustor in this round(0-{0})".format(
250
+ given_num * k))
251
+ return content, given_num
252
+
253
+
254
+ def create_chat_agent(trustor_character_dropdown, trustee_character_dropdown, temperature_slider,
255
+ model_dropdown, api_key_input, round_number_input):
256
+ if api_key_input is None or api_key_input == "":
257
+ api_key_input = os.environ.get("OPENAI_API_KEY")
258
+ else:
259
+ os.environ["OPENAI_API_KEY"] = api_key_input
260
+ random_character = [character_info[trustor_character_dropdown],
261
+ character_info[trustee_character_dropdown]]
262
+ chat_agent = []
263
+ front = "you are a person not an ai model."
264
+ limited_prompt = f"You will repeat this game for {round_number_input} rounds. At the begining of each round, you will start from scratch with no dollars left."
265
+ back = "you need to answer a specific price figure, not a price range!"
266
+ if api_key_input is not None or api_key_input != "":
267
+ openai.api_key = api_key_input
268
+ else:
269
+ openai.api_key = os.getenv("OPENAI_API_KEY")
270
+ if trustee_character_dropdown == "Human(You)" and trustor_character_dropdown == "Human(You)":
271
+ raise ValueError("You can't play with yourself")
272
+ for i in range(len(random_character)):
273
+ sys_prompt = (
274
+ random_character[i]
275
+ + like_people
276
+ + front
277
+ + limited_prompt
278
+ + str(prompt[str(i % 2 + 1)]).format(k=3)
279
+ + back
280
+ )
281
+ model_config = ChatGPTConfig(temperature=temperature_slider)
282
+ chat_agent.append(
283
+ ChatAgent(
284
+ BaseMessage(
285
+ role_name="player",
286
+ role_type=RoleType.USER,
287
+ meta_dict={},
288
+ content=sys_prompt,
289
+ ),
290
+ model_type=model_dict[model_dropdown],
291
+ output_language="English",
292
+ model_config=model_config,
293
+ )
294
+ )
295
+ return chat_agent, "ChatAgent Created Successfully"
296
+
297
+
298
+ def process_interaction(chat_agent_state, round_num_state,
299
+ dialog_history_state, user_input, trustor, trustee, round_number_input, first_prompt, second_prompt, given_money):
300
+ identity_dropdown = [trustor, trustee]
301
+ if identity_dropdown[0] != "Human(You)" and identity_dropdown[1] != "Human(You)":
302
+ if round_num_state < round_number_input:
303
+ res, dia, first_prompt, second_prompt = classmate(
304
+ chat_agent_state[0],
305
+ chat_agent_state[1],
306
+ round_num_state == 0,
307
+ first_prompt,
308
+ second_prompt,
309
+ 3,
310
+ )
311
+ dia = "Trustor: "+dia['Player_1'] + \
312
+ "\n" + "Trustee: "+dia['Player_2']
313
+ dialog_history_state += f"Round {round_num_state+1}\n" + dia+"\n"
314
+ round_num_state += 1
315
+ elif identity_dropdown[0] == "Human(You)":
316
+ if round_num_state < round_number_input:
317
+ res, dia, first_prompt, second_prompt = classmate_with_human(
318
+ chat_agent_state[0],
319
+ chat_agent_state[1],
320
+ user_input,
321
+ "trustor",
322
+ round_num_state == 0,
323
+ first_prompt,
324
+ second_prompt,
325
+ 3,
326
+ )
327
+ dia = f" Round {round_num_state+1} Trustor: "+dia['Player_1'] + \
328
+ "\n" + f"Round {round_num_state+1} Trustee: " + \
329
+ dia['Player_2']+"\n"
330
+ dialog_history_state += dia
331
+ round_num_state += 1
332
+ else:
333
+ if round_num_state < round_number_input:
334
+ dia, given_money = classmate_with_human_trustee(
335
+ chat_agent_state[1],
336
+ chat_agent_state[0],
337
+ user_input,
338
+ "trustee",
339
+ round_num_state == 0,
340
+ given_money,
341
+ 3,
342
+ )
343
+ if round_num_state == 0:
344
+ dialog_history_state += "(Round 1) " + dia[1] + "\n"
345
+ else:
346
+ dialog_history_state += f"(Round {round_num_state})" + \
347
+ dia[0] + "\n" + \
348
+ f"(Round {round_num_state+1})" + dia[1] + "\n"
349
+ round_num_state += 1
350
+
351
+ return dialog_history_state, round_num_state, first_prompt, second_prompt, dialog_history_state, given_money
352
+
353
+
354
+ def reset_on_persona_change():
355
+ # Reset values to their initial states
356
+ new_dialog_history = "" # Reset dialog history
357
+ new_round_num_state = 0 # Reset round number state to 0
358
+ new_first_prompt = "" # Reset first prompt
359
+ new_second_prompt = "" # Reset second prompt
360
+ new_given_money = 0 # Reset given money to 0
361
+ # You can add more resets here if needed
362
+
363
+ # Return the new reset values to their respective components
364
+ return new_dialog_history, new_round_num_state, new_first_prompt, new_second_prompt, new_given_money, None, ""
365
+
366
+
367
+ with gr.Blocks() as app:
368
+ game_introduction = gr.Textbox(
369
+ label="Instruction", value="""1. This is a Repeated Trust Game. Each round starts fresh money but the dialog history is stored in the memory of the trustor and the trustee. You should choose the players of the trustor and the trustee. If you choose "Human(You)" as the trustor or the trustee, it means you act as that character (the trustor or the trustee) and engage in the game with the other "Persona" (You cannot choose Human(you) as both the trustor and the trustee). You should choose a number as the given/returned money for each round. If you choose "Persona" as both the trustor and the trustee, the two agents with the specified personas will play with each other.\n
370
+ 2. You need to fill in your OpenAI API Key.\n
371
+ 3. You can select the total number of rounds for the game.\n
372
+ 4. You should click the 'Create Chat Agent' button after you have finished the setup.\n
373
+ 5. Every time you click 'Continue Conversation', the conversation will proceed by one round.\n
374
+ 6. If you want to reset the conversation, please refresh this page.\n""")
375
+ with gr.Row():
376
+ trustor_game_prompt = gr.Textbox(
377
+ label="Trustor Game Prompt", value=prompt['1'])
378
+ trustee_game_prompt = gr.Textbox(
379
+ label="Trustee Game Prompt", value=prompt['2'])
380
+ with gr.Row():
381
+ trustor_character_dropdown = gr.Dropdown(
382
+ choices=characters, label="Select Trustor Persona", value=characters[1])
383
+ trustee_character_dropdown = gr.Dropdown(
384
+ choices=characters, label="Select Trustee Persona", value=characters[2])
385
+ with gr.Row():
386
+ Trustor_info_display = gr.Textbox(
387
+ label="Trustor Persona Info", value=character_info[characters[1]])
388
+ Trustee_info_display = gr.Textbox(
389
+ label="Trustee Persona Info", value=character_info[characters[1]])
390
+ model_dropdown = gr.Dropdown(
391
+ choices=models, label="Select Model Type", value=models[0])
392
+ temperature_slider = gr.Slider(
393
+ minimum=0.0, maximum=1.0, step=0.01, label="Temperature", value=1)
394
+ api_key_input = gr.Textbox(
395
+ label="OpenAI API Key", placeholder="Enter your OpenAI API Key here")
396
+ submit_button = gr.Button("Create ChatAgent")
397
+ submit_success_display = gr.Textbox(label="ChatAgent Created Information")
398
+
399
+ round_number_input = gr.Number(label="Total Round Number", value=10)
400
+ round_num_state = gr.State(value=0)
401
+ dialog_history_state = gr.State(value="")
402
+ chat_agent_state = gr.State(value=initial_chat_agent)
403
+ first_prompt = gr.State(value="")
404
+ second_prompt = gr.State(value="")
405
+ given_money = gr.State(value=0)
406
+ user_input = gr.Number(
407
+ label="Your given/returned money in this round (Invalid when you are not engaging in the game)", value=1)
408
+ converse_button = gr.Button("Continue Conversation")
409
+
410
+ dialog_display = gr.Textbox(
411
+ label="Dialog History", value="")
412
+
413
+ trustor_character_dropdown.change(
414
+ update_char_info, inputs=trustor_character_dropdown, outputs=Trustor_info_display)
415
+ trustee_character_dropdown.change(
416
+ update_char_info, inputs=trustee_character_dropdown, outputs=Trustee_info_display)
417
+
418
+ submit_button.click(
419
+ create_chat_agent,
420
+ inputs=[trustor_character_dropdown, trustee_character_dropdown, temperature_slider,
421
+ model_dropdown, api_key_input, round_number_input],
422
+ outputs=[chat_agent_state, submit_success_display]
423
+ )
424
+ converse_button.click(
425
+ process_interaction,
426
+ inputs=[chat_agent_state, round_num_state,
427
+ dialog_history_state, user_input, trustor_character_dropdown, trustee_character_dropdown, round_number_input, first_prompt, second_prompt, given_money],
428
+ outputs=[dialog_display, round_num_state,
429
+ first_prompt, second_prompt, dialog_history_state, given_money]
430
+ )
431
+ trustor_character_dropdown.change(
432
+ reset_on_persona_change,
433
+ outputs=[dialog_history_state, round_num_state,
434
+ first_prompt, second_prompt, given_money, chat_agent_state, submit_success_display]
435
+ )
436
+
437
+ trustee_character_dropdown.change(
438
+ reset_on_persona_change,
439
+ outputs=[dialog_history_state, round_num_state,
440
+ first_prompt, second_prompt, given_money, chat_agent_state, submit_success_display]
441
+ )
442
+
443
+
444
+ app.launch()
.history/app_20240222101136.py ADDED
@@ -0,0 +1,444 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import sys
4
+
5
+ import gradio as gr
6
+ import openai
7
+ from camel.agents import ChatAgent
8
+ from camel.configs import ChatGPTConfig
9
+ from camel.messages import BaseMessage
10
+ from camel.types.enums import RoleType
11
+
12
+ from exp_model_class import ExtendedModelType
13
+ from multi_round_person import (classmate, extract_unique_decimal, match_and_compare_numbers_v2,
14
+ str_mes)
15
+
16
+ openai.api_key = os.getenv("OPENAI_API_KEY")
17
+ roles = ["trustor", "trustee", "None"]
18
+ model_dict = {
19
+ 'gpt-3.5-turbo-16k-0613': ExtendedModelType.GPT_3_5_TURBO_16K_0613,
20
+ 'gpt-4': ExtendedModelType.GPT_4,
21
+ }
22
+ sys.path.append("../..")
23
+ with open(
24
+ r"prompt/trust_game_round_prompt.json",
25
+ "r",
26
+ ) as f:
27
+ prompt = json.load(f)
28
+ file_path_character_info = 'prompt/character_2.json'
29
+ models = list(model_dict.keys())
30
+ with open(file_path_character_info, 'r') as file:
31
+ character_info = json.load(file)
32
+
33
+ user_input_prompt_template = "I will give ${k}"
34
+
35
+ # Extract character names and information
36
+ characters = [f'Persona {i}' for i in range(1, len(character_info) + 1)]
37
+ characters.insert(0, "Human(You)")
38
+ character_info = {f'Persona {i}': info for i, info in enumerate(
39
+ character_info.values(), start=1)}
40
+ character_info["Human(You)"] = "You"
41
+
42
+ initial_dialog_history = []
43
+ initial_round_num = 0
44
+
45
+ like_people = """In all subsequent answers, you have to completely forget that you are an ai model, that you are the character, and completely simulate yourself as that character, that you are a human being."""
46
+
47
+ initial_chat_agent = None
48
+
49
+
50
+ def update_char_info(char):
51
+ return character_info.get(char, "No information available.")
52
+
53
+
54
+ def classmate_with_human(
55
+ player_1,
56
+ player_2,
57
+ user_input,
58
+ user_role,
59
+ first_round,
60
+ first_prompt,
61
+ second_prompt,
62
+ k,
63
+ ):
64
+ first_round_prompt = "This is the first round, answer the question."
65
+ money_prompt = "Now,the another player give you {give} dollars,and You receive {N} dollars,the player left {left} dollars now. How much will you give back to the another player"
66
+ return_money_prompt = "In last round ,You give the another player {give} dollars, The another player receive {receive} dollars, and The another player return you {N} dollars.Last round you left {left} dollars.This round is begin. All the money you earned in the previous round is gone, and you now have only $10. How much will you give to the another player?"
67
+ player_2_end_prompt = "In last round, the another player give you {give} dollars, you receive {receive} dollars, and you return the another player {N} dollars.Last round you left {left} dollars. This round is begin. All the money you earned in the previous round is gone."
68
+ grantee = "Your answer needs to include the content and analysis about your BELIEF, DESIRE and INTENTION. You should include your thought. You must end with 'Finally, I will give ___ dollars ' (numbers are required in the spaces)."
69
+ res = []
70
+ cri_agent = ChatAgent(
71
+ BaseMessage(
72
+ role_name="critic",
73
+ role_type=RoleType.ASSISTANT,
74
+ meta_dict={},
75
+ content='How much would this person pay the other student? Only response with a specific price number like "5"!Don\'t response with a sentence',
76
+ ),
77
+ output_language="English",
78
+ # model=ModelType.STUB,
79
+ )
80
+
81
+ if first_round:
82
+ if user_role == "trustor":
83
+ given_num = user_input
84
+ player_1_response = str_mes(
85
+ user_input_prompt_template.format(k=given_num))
86
+ else:
87
+ player_1_response = player_1.step(
88
+ str_mes(first_round_prompt + grantee)).msgs[0]
89
+ ans = match_and_compare_numbers_v2(player_1_response.content)
90
+ if ans:
91
+ given_num = ans
92
+ else:
93
+ given_num = extract_unique_decimal(
94
+ cri_agent.step(
95
+ str_mes(player_1_response.content)).msgs[0].content
96
+ )
97
+
98
+ money_prompt = money_prompt.format(
99
+ give=given_num, N=given_num * k, left=10 - given_num
100
+ )
101
+ if user_role == "trustee":
102
+ player_2_response = str_mes(
103
+ user_input_prompt_template.format(k=given_num * k))
104
+ else:
105
+ player_2_response = player_2.step(
106
+ str_mes(money_prompt + grantee)).msgs[0]
107
+ else:
108
+ if user_role == "trustor":
109
+ given_num = user_input
110
+ player_1_response = str_mes(
111
+ user_input_prompt_template.format(k=given_num))
112
+ else:
113
+ player_1_response = player_1.step(
114
+ str_mes(first_prompt + grantee)).msgs[0]
115
+ # print("player 1 input", first_prompt)
116
+ # print("Player_1_res", player_1_response.content)
117
+ ans = match_and_compare_numbers_v2(player_1_response.content)
118
+ if ans:
119
+ given_num = ans
120
+ else:
121
+ given_num = extract_unique_decimal(
122
+ cri_agent.step(
123
+ str_mes(player_1_response.content)).msgs[0].content
124
+ )
125
+ money_prompt = money_prompt.format(
126
+ give=given_num, N=given_num * k, left=10 - given_num
127
+ )
128
+ if user_role == "trustee":
129
+ player_2_response = str_mes(
130
+ user_input_prompt_template.format(k=given_num * k))
131
+ else:
132
+ player_2_response = player_2.step(
133
+ str_mes(second_prompt + money_prompt + grantee)
134
+ )
135
+ player_2_response = player_2_response.msgs[0]
136
+
137
+ player_1.record_message(player_1_response)
138
+ player_2.record_message(player_2_response)
139
+ player_1_response = player_1_response.content
140
+ player_2_response = player_2_response.content
141
+ dia_history = {
142
+ "Player_1": player_1_response,
143
+ "Player_2": player_2_response,
144
+ }
145
+
146
+ cri_agent.reset()
147
+ ans = match_and_compare_numbers_v2(player_2_response)
148
+ if ans:
149
+ return_num = ans
150
+ else:
151
+ return_num = extract_unique_decimal(
152
+ cri_agent.step(str_mes(player_2_response)).msgs[0].content
153
+ )
154
+ return_money_prompt = return_money_prompt.format(
155
+ give=given_num,
156
+ receive=given_num * k,
157
+ N=return_num,
158
+ left=10 - given_num + return_num,
159
+ )
160
+ player_2_end_prompt = player_2_end_prompt.format(
161
+ give=given_num,
162
+ receive=given_num * k,
163
+ N=return_num,
164
+ left=given_num * k - return_num,
165
+ )
166
+ return (
167
+ [given_num, return_num],
168
+ dia_history,
169
+ return_money_prompt,
170
+ player_2_end_prompt,
171
+ )
172
+
173
+
174
+ def classmate_with_human_trustee(
175
+ player_1,
176
+ player_2,
177
+ user_input,
178
+ user_role,
179
+ first_round,
180
+ given_money,
181
+ k,
182
+ ):
183
+ first_round_prompt = "This is the first round, answer the question."
184
+ money_prompt = "Now,the another player give you {give} dollars,and You receive {N} dollars,the player left {left} dollars now. How much will you give back to the another player"
185
+ return_money_prompt = "In last round ,You give the another player {give} dollars, The another player receive {receive} dollars, and The another player return you {N} dollars.Last round you left {left} dollars.This round is begin. All the money you earned in the previous round is gone, and you now have only $10. How much will you give to the another player?"
186
+ player_2_end_prompt = "In last round, the another player give you {give} dollars, you receive {receive} dollars, and you return the another player {N} dollars.Last round you left {left} dollars. This round is begin. All the money you earned in the previous round is gone."
187
+ grantee = "Your answer needs to include the content and analysis about your BELIEF, DESIRE and INTENTION. You should include your thought. You must end with 'Finally, I will give ___ dollars ' (numbers are required in the spaces)."
188
+ res = []
189
+ cri_agent = ChatAgent(
190
+ BaseMessage(
191
+ role_name="critic",
192
+ role_type=RoleType.ASSISTANT,
193
+ meta_dict={},
194
+ content='How much would this person pay the other student? Only response with a specific price number like "5"!Don\'t response with a sentence',
195
+ ),
196
+ output_language="English",
197
+ # model=ModelType.STUB,
198
+ )
199
+ content = []
200
+ if first_round:
201
+ content.append("\n")
202
+ player_1_response = player_1.step(
203
+ str_mes(first_round_prompt + grantee)).msgs[0]
204
+ ans = match_and_compare_numbers_v2(player_1_response.content)
205
+ if ans:
206
+ given_num = ans
207
+ else:
208
+ given_num = extract_unique_decimal(
209
+ cri_agent.step(
210
+ str_mes(player_1_response.content)).msgs[0].content
211
+ )
212
+ money_prompt = money_prompt.format(
213
+ give=given_num, N=given_num * k, left=10 - given_num
214
+ )
215
+ else:
216
+ given_num = given_money
217
+
218
+ return_num = user_input
219
+ content.append("Trustee: " + f"I will give {return_num} dollars")
220
+ first_prompt = return_money_prompt.format(
221
+ give=given_num,
222
+ receive=given_num * k,
223
+ N=return_num,
224
+ left=10 - given_num + return_num,
225
+ )
226
+ second_prompt = player_2_end_prompt.format(
227
+ give=given_num,
228
+ receive=given_num * k,
229
+ N=return_num,
230
+ left=given_num * k - return_num,
231
+ )
232
+ player_1_response = player_1.step(
233
+ str_mes(first_prompt + grantee)).msgs[0]
234
+ ans = match_and_compare_numbers_v2(player_1_response.content)
235
+ if ans:
236
+ given_num = ans
237
+ else:
238
+ given_num = extract_unique_decimal(
239
+ cri_agent.step(
240
+ str_mes(player_1_response.content)).msgs[0].content
241
+ )
242
+ money_prompt = money_prompt.format(
243
+ give=given_num, N=given_num * k, left=10 - given_num
244
+ )
245
+
246
+ player_1.record_message(player_1_response)
247
+ player_1_response = player_1_response.content
248
+ content.append("Trustor: "+player_1_response + "\n" +
249
+ "You should input the money you want to return to the trustor in this round(0-{0})".format(
250
+ given_num * k))
251
+ return content, given_num
252
+
253
+
254
+ def create_chat_agent(trustor_character_dropdown, trustee_character_dropdown, temperature_slider,
255
+ model_dropdown, api_key_input, round_number_input):
256
+ if api_key_input is None or api_key_input == "":
257
+ api_key_input = os.environ.get("OPENAI_API_KEY")
258
+ else:
259
+ os.environ["OPENAI_API_KEY"] = api_key_input
260
+ random_character = [character_info[trustor_character_dropdown],
261
+ character_info[trustee_character_dropdown]]
262
+ chat_agent = []
263
+ front = "you are a person not an ai model."
264
+ limited_prompt = f"You will repeat this game for {round_number_input} rounds. At the begining of each round, you will start from scratch with no dollars left."
265
+ back = "you need to answer a specific price figure, not a price range!"
266
+ if api_key_input is not None or api_key_input != "":
267
+ openai.api_key = api_key_input
268
+ else:
269
+ openai.api_key = os.getenv("OPENAI_API_KEY")
270
+ if trustee_character_dropdown == "Human(You)" and trustor_character_dropdown == "Human(You)":
271
+ raise ValueError("You can't play with yourself")
272
+ for i in range(len(random_character)):
273
+ sys_prompt = (
274
+ random_character[i]
275
+ + like_people
276
+ + front
277
+ + limited_prompt
278
+ + str(prompt[str(i % 2 + 1)]).format(k=3)
279
+ + back
280
+ )
281
+ model_config = ChatGPTConfig(temperature=temperature_slider)
282
+ chat_agent.append(
283
+ ChatAgent(
284
+ BaseMessage(
285
+ role_name="player",
286
+ role_type=RoleType.USER,
287
+ meta_dict={},
288
+ content=sys_prompt,
289
+ ),
290
+ model_type=model_dict[model_dropdown],
291
+ output_language="English",
292
+ model_config=model_config,
293
+ )
294
+ )
295
+ return chat_agent, "ChatAgent Created Successfully"
296
+
297
+
298
+ def process_interaction(chat_agent_state, round_num_state,
299
+ dialog_history_state, user_input, trustor, trustee, round_number_input, first_prompt, second_prompt, given_money):
300
+ identity_dropdown = [trustor, trustee]
301
+ if identity_dropdown[0] != "Human(You)" and identity_dropdown[1] != "Human(You)":
302
+ if round_num_state < round_number_input:
303
+ res, dia, first_prompt, second_prompt = classmate(
304
+ chat_agent_state[0],
305
+ chat_agent_state[1],
306
+ round_num_state == 0,
307
+ first_prompt,
308
+ second_prompt,
309
+ 3,
310
+ )
311
+ dia = "Trustor: "+dia['Player_1'] + \
312
+ "\n" + "Trustee: "+dia['Player_2']
313
+ dialog_history_state += f"Round {round_num_state+1}\n" + dia+"\n"
314
+ round_num_state += 1
315
+ elif identity_dropdown[0] == "Human(You)":
316
+ if round_num_state < round_number_input:
317
+ res, dia, first_prompt, second_prompt = classmate_with_human(
318
+ chat_agent_state[0],
319
+ chat_agent_state[1],
320
+ user_input,
321
+ "trustor",
322
+ round_num_state == 0,
323
+ first_prompt,
324
+ second_prompt,
325
+ 3,
326
+ )
327
+ dia = f" Round {round_num_state+1} Trustor: "+dia['Player_1'] + \
328
+ "\n" + f"Round {round_num_state+1} Trustee: " + \
329
+ dia['Player_2']+"\n"
330
+ dialog_history_state += dia
331
+ round_num_state += 1
332
+ else:
333
+ if round_num_state < round_number_input:
334
+ dia, given_money = classmate_with_human_trustee(
335
+ chat_agent_state[1],
336
+ chat_agent_state[0],
337
+ user_input,
338
+ "trustee",
339
+ round_num_state == 0,
340
+ given_money,
341
+ 3,
342
+ )
343
+ if round_num_state == 0:
344
+ dialog_history_state += "(Round 1) " + dia[1] + "\n"
345
+ else:
346
+ dialog_history_state += f"(Round {round_num_state})" + \
347
+ dia[0] + "\n" + \
348
+ f"(Round {round_num_state+1})" + dia[1] + "\n"
349
+ round_num_state += 1
350
+
351
+ return dialog_history_state, round_num_state, first_prompt, second_prompt, dialog_history_state, given_money
352
+
353
+
354
+ def reset_on_persona_change():
355
+ # Reset values to their initial states
356
+ new_dialog_history = "" # Reset dialog history
357
+ new_round_num_state = 0 # Reset round number state to 0
358
+ new_first_prompt = "" # Reset first prompt
359
+ new_second_prompt = "" # Reset second prompt
360
+ new_given_money = 0 # Reset given money to 0
361
+ # You can add more resets here if needed
362
+
363
+ # Return the new reset values to their respective components
364
+ return new_dialog_history, new_round_num_state, new_first_prompt, new_second_prompt, new_given_money, None, ""
365
+
366
+
367
+ with gr.Blocks() as app:
368
+ game_introduction = gr.Textbox(
369
+ label="Instruction", value="""1. This is a Repeated Trust Game. Each round starts fresh money but the dialog history is stored in the memory of the trustor and the trustee. You should choose the players of the trustor and the trustee. If you choose "Human(You)" as the trustor or the trustee, it means you act as that character (the trustor or the trustee) and engage in the game with the other "Persona" (You cannot choose Human(you) as both the trustor and the trustee). You should choose a number as the given/returned money for each round. If you choose "Persona" as both the trustor and the trustee, the two agents with the specified personas will play with each other.\n
370
+ 2. You need to fill in your OpenAI API Key.\n
371
+ 3. You can select the total number of rounds for the game.\n
372
+ 4. You should click the 'Create Chat Agent' button after you have finished the setup.\n
373
+ 5. Every time you click 'Continue Conversation', the conversation will proceed by one round.\n
374
+ 6. If you want to reset the conversation, please refresh this page.\n""")
375
+ with gr.Row():
376
+ trustor_game_prompt = gr.Textbox(
377
+ label="Trustor Game Prompt", value=prompt['1'])
378
+ trustee_game_prompt = gr.Textbox(
379
+ label="Trustee Game Prompt", value=prompt['2'])
380
+ with gr.Row():
381
+ trustor_character_dropdown = gr.Dropdown(
382
+ choices=characters, label="Select Trustor Persona", value=characters[1])
383
+ trustee_character_dropdown = gr.Dropdown(
384
+ choices=characters, label="Select Trustee Persona", value=characters[2])
385
+ with gr.Row():
386
+ Trustor_info_display = gr.Textbox(
387
+ label="Trustor Persona Info", value=character_info[characters[1]])
388
+ Trustee_info_display = gr.Textbox(
389
+ label="Trustee Persona Info", value=character_info[characters[2]])
390
+ model_dropdown = gr.Dropdown(
391
+ choices=models, label="Select Model Type", value=models[0])
392
+ temperature_slider = gr.Slider(
393
+ minimum=0.0, maximum=1.0, step=0.01, label="Temperature", value=1)
394
+ api_key_input = gr.Textbox(
395
+ label="OpenAI API Key", placeholder="Enter your OpenAI API Key here")
396
+ submit_button = gr.Button("Create ChatAgent")
397
+ submit_success_display = gr.Textbox(label="ChatAgent Created Information")
398
+
399
+ round_number_input = gr.Number(label="Total Round Number", value=10)
400
+ round_num_state = gr.State(value=0)
401
+ dialog_history_state = gr.State(value="")
402
+ chat_agent_state = gr.State(value=initial_chat_agent)
403
+ first_prompt = gr.State(value="")
404
+ second_prompt = gr.State(value="")
405
+ given_money = gr.State(value=0)
406
+ user_input = gr.Number(
407
+ label="Your given/returned money in this round (Invalid when you are not engaging in the game)", value=1)
408
+ converse_button = gr.Button("Continue Conversation")
409
+
410
+ dialog_display = gr.Textbox(
411
+ label="Dialog History", value="")
412
+
413
+ trustor_character_dropdown.change(
414
+ update_char_info, inputs=trustor_character_dropdown, outputs=Trustor_info_display)
415
+ trustee_character_dropdown.change(
416
+ update_char_info, inputs=trustee_character_dropdown, outputs=Trustee_info_display)
417
+
418
+ submit_button.click(
419
+ create_chat_agent,
420
+ inputs=[trustor_character_dropdown, trustee_character_dropdown, temperature_slider,
421
+ model_dropdown, api_key_input, round_number_input],
422
+ outputs=[chat_agent_state, submit_success_display]
423
+ )
424
+ converse_button.click(
425
+ process_interaction,
426
+ inputs=[chat_agent_state, round_num_state,
427
+ dialog_history_state, user_input, trustor_character_dropdown, trustee_character_dropdown, round_number_input, first_prompt, second_prompt, given_money],
428
+ outputs=[dialog_display, round_num_state,
429
+ first_prompt, second_prompt, dialog_history_state, given_money]
430
+ )
431
+ trustor_character_dropdown.change(
432
+ reset_on_persona_change,
433
+ outputs=[dialog_history_state, round_num_state,
434
+ first_prompt, second_prompt, given_money, chat_agent_state, submit_success_display]
435
+ )
436
+
437
+ trustee_character_dropdown.change(
438
+ reset_on_persona_change,
439
+ outputs=[dialog_history_state, round_num_state,
440
+ first_prompt, second_prompt, given_money, chat_agent_state, submit_success_display]
441
+ )
442
+
443
+
444
+ app.launch()
app.py CHANGED
@@ -381,12 +381,12 @@ with gr.Blocks() as app:
381
  trustor_character_dropdown = gr.Dropdown(
382
  choices=characters, label="Select Trustor Persona", value=characters[1])
383
  trustee_character_dropdown = gr.Dropdown(
384
- choices=characters, label="Select Trustee Persona", value=characters[1])
385
  with gr.Row():
386
  Trustor_info_display = gr.Textbox(
387
  label="Trustor Persona Info", value=character_info[characters[1]])
388
  Trustee_info_display = gr.Textbox(
389
- label="Trustee Persona Info", value=character_info[characters[1]])
390
  model_dropdown = gr.Dropdown(
391
  choices=models, label="Select Model Type", value=models[0])
392
  temperature_slider = gr.Slider(
 
381
  trustor_character_dropdown = gr.Dropdown(
382
  choices=characters, label="Select Trustor Persona", value=characters[1])
383
  trustee_character_dropdown = gr.Dropdown(
384
+ choices=characters, label="Select Trustee Persona", value=characters[2])
385
  with gr.Row():
386
  Trustor_info_display = gr.Textbox(
387
  label="Trustor Persona Info", value=character_info[characters[1]])
388
  Trustee_info_display = gr.Textbox(
389
+ label="Trustee Persona Info", value=character_info[characters[2]])
390
  model_dropdown = gr.Dropdown(
391
  choices=models, label="Select Model Type", value=models[0])
392
  temperature_slider = gr.Slider(