From ca910f0592393b7acdbdaf075bf8ed4dfe94756e Mon Sep 17 00:00:00 2001 From: SereneWalden <22496084+SereneWalden@users.noreply.github.com> Date: Mon, 2 Oct 2023 23:04:41 +0800 Subject: [PATCH] add actions necessary for st_plan --- .../st_game/actions/gen_daily_schedule.py | 61 +++++++ .../st_game/actions/gen_hourly_schedule.py | 164 ++++++++++++++++++ examples/st_game/actions/task_decomp.py | 162 +++++++++++++++++ examples/st_game/actions/wake_up.py | 45 +++++ .../st_game/prompts/daily_planning_v6.txt | 14 ++ .../prompts/generate_event_triple_v1.txt | 2 +- .../prompts/generate_hourly_schedule_v2.txt | 18 ++ .../st_game/prompts/generate_obj_event_v1.txt | 16 ++ examples/st_game/prompts/task_decomp_v3.txt | 39 +++++ examples/st_game/prompts/wake_up_hour_v1.txt | 12 ++ 10 files changed, 532 insertions(+), 1 deletion(-) create mode 100644 examples/st_game/actions/gen_daily_schedule.py create mode 100644 examples/st_game/actions/gen_hourly_schedule.py create mode 100644 examples/st_game/actions/task_decomp.py create mode 100644 examples/st_game/actions/wake_up.py create mode 100644 examples/st_game/prompts/daily_planning_v6.txt create mode 100644 examples/st_game/prompts/generate_hourly_schedule_v2.txt create mode 100644 examples/st_game/prompts/generate_obj_event_v1.txt create mode 100644 examples/st_game/prompts/task_decomp_v3.txt create mode 100644 examples/st_game/prompts/wake_up_hour_v1.txt diff --git a/examples/st_game/actions/gen_daily_schedule.py b/examples/st_game/actions/gen_daily_schedule.py new file mode 100644 index 000000000..0bc743511 --- /dev/null +++ b/examples/st_game/actions/gen_daily_schedule.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# @Desc : gen_daily_schedule + +import datetime + +from metagpt.logs import logger +from metagpt.schema import Message + +from ..roles.st_role import STRole +from .st_action import STAction + +class GenDailySchedule(STAction): + def __init__(self, name="GenDailySchedule", context: list[Message] = None, llm=None): + super().__init__(name, context, llm) + + def _func_validate(self, llm_resp: str, prompt: str) -> bool: + try: + self._func_cleanup(llm_resp, prompt="") + except: + return False + return True + + def _func_cleanup(self, llm_resp: str, prompt: str) -> list: + cr = [] + _cr = llm_resp.split(")") + for i in _cr: + if i[-1].isdigit(): + i = i[:-1].strip() + if i[-1] == "." or i[-1] == ",": + cr += [i[:-1].strip()] + return cr + + def _func_fail_default_resp(self) -> int: + fs = ['wake up and complete the morning routine at 6:00 am', + 'eat breakfast at 7:00 am', + 'read a book from 8:00 am to 12:00 pm', + 'have lunch at 12:00 pm', + 'take a nap from 1:00 pm to 4:00 pm', + 'relax and watch TV from 7:00 pm to 8:00 pm', + 'go to bed at 11:00 pm'] + return fs + + def run(self, role: STRole, wake_up_hour: str): + def create_prompt_input(role, wake_up_hour): + prompt_input = [] + prompt_input += [role.scratch.get_str_iss()] + prompt_input += [role.scratch.get_str_lifestyle()] + prompt_input += [role.scratch.get_str_curr_date_str()] + prompt_input += [role.scratch.get_str_firstname()] + prompt_input += [f"{str(wake_up_hour)}:00 am"] + return prompt_input + wake_up_hour = int(wake_up_hour) + prompt_template = "daily_planning_v6.txt" + prompt_input = create_prompt_input(role, wake_up_hour) + prompt = self.generate_prompt_with_tmpl_filename(prompt_input, prompt_template) + self.fail_default_resp = self._func_fail_default_resp() + output = self._run_v1(prompt) + output = ([f"wake up and complete the morning routine at {wake_up_hour}:00 am"] + + output) + return output diff --git a/examples/st_game/actions/gen_hourly_schedule.py b/examples/st_game/actions/gen_hourly_schedule.py new file mode 100644 index 000000000..b823dae01 --- /dev/null +++ b/examples/st_game/actions/gen_hourly_schedule.py @@ -0,0 +1,164 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# @Desc : gen_hourly_schedule + +import datetime +import random +import string + +from metagpt.logs import logger +from metagpt.schema import Message + +from ..roles.st_role import STRole +from .st_action import STAction + +def get_random_alphanumeric(i=6, j=6): + """ + Returns a random alpha numeric strength that has the length of somewhere + between i and j. + + INPUT: + i: min_range for the length + j: max_range for the length + OUTPUT: + an alpha numeric str with the length of somewhere between i and j. + """ + k = random.randint(i, j) + x = ''.join(random.choices(string.ascii_letters + string.digits, k=k)) + return x + +class GenHourlySchedule(STAction): + def __init__(self, name="GenHourlySchedule", context: list[Message] = None, llm=None): + super().__init__(name, context, llm) + + def _func_validate(self, llm_resp: str, prompt: str) -> bool: + try: + self._func_cleanup(llm_resp, prompt="") + except: + return False + return True + + def _func_cleanup(self, llm_resp: str, prompt: str) -> list: + cr = llm_resp.strip() + if cr[-1] == ".": + cr = cr[:-1] + return cr + + def _func_fail_default_resp(self) -> int: + fs = "asleep" + return fs + + def _generate_schedule_for_given_hour(self, role: STRole, + curr_hour_str, + p_f_ds_hourly_org, + hour_str, + intermission2): + def create_prompt_input(persona, + curr_hour_str, + p_f_ds_hourly_org, + hour_str, + intermission2=None): + schedule_format = "" + for i in hour_str: + schedule_format += f"[{persona.scratch.get_str_curr_date_str()} -- {i}]" + schedule_format += f" Activity: [Fill in]\n" + schedule_format = schedule_format[:-1] + + intermission_str = f"Here the originally intended hourly breakdown of" + intermission_str += f" {persona.scratch.get_str_firstname()}'s schedule today: " + for count, i in enumerate(persona.scratch.daily_req): + intermission_str += f"{str(count+1)}) {i}, " + intermission_str = intermission_str[:-2] + + prior_schedule = "" + if p_f_ds_hourly_org: + prior_schedule = "\n" + for count, i in enumerate(p_f_ds_hourly_org): + prior_schedule += f"[(ID:{get_random_alphanumeric()})" + prior_schedule += f" {persona.scratch.get_str_curr_date_str()} --" + prior_schedule += f" {hour_str[count]}] Activity:" + prior_schedule += f" {persona.scratch.get_str_firstname()}" + prior_schedule += f" is {i}\n" + + prompt_ending = f"[(ID:{get_random_alphanumeric()})" + prompt_ending += f" {persona.scratch.get_str_curr_date_str()}" + prompt_ending += f" -- {curr_hour_str}] Activity:" + prompt_ending += f" {persona.scratch.get_str_firstname()} is" + + if intermission2: + intermission2 = f"\n{intermission2}" + + prompt_input = [] + prompt_input += [schedule_format] + prompt_input += [persona.scratch.get_str_iss()] + + prompt_input += [prior_schedule + "\n"] + prompt_input += [intermission_str] + if intermission2: + prompt_input += [intermission2] + else: + prompt_input += [""] + prompt_input += [prompt_ending] + + return prompt_input + + wake_up_hour = int(wake_up_hour) + prompt_template = "generate_hourly_schedule_v2.txt" + prompt_input = create_prompt_input(role, + curr_hour_str, + p_f_ds_hourly_org, + hour_str, + intermission2) + prompt = self.generate_prompt_with_tmpl_filename(prompt_input, prompt_template) + self.fail_default_resp = self._func_fail_default_resp() + output = self._run_v1(prompt) + return output + + def run(self, role: STRole, wake_up_hour: str): + hour_str = ["00:00 AM", "01:00 AM", "02:00 AM", "03:00 AM", "04:00 AM", + "05:00 AM", "06:00 AM", "07:00 AM", "08:00 AM", "09:00 AM", + "10:00 AM", "11:00 AM", "12:00 PM", "01:00 PM", "02:00 PM", + "03:00 PM", "04:00 PM", "05:00 PM", "06:00 PM", "07:00 PM", + "08:00 PM", "09:00 PM", "10:00 PM", "11:00 PM"] + n_m1_activity = [] + diversity_repeat_count = 3 + for i in range(diversity_repeat_count): + n_m1_activity_set = set(n_m1_activity) + if len(n_m1_activity_set) < 5: + n_m1_activity = [] + for count, curr_hour_str in enumerate(hour_str): + if wake_up_hour > 0: + n_m1_activity += ["sleeping"] + wake_up_hour -= 1 + else: + n_m1_activity += [self._generate_schedule_for_given_hour( + role, curr_hour_str, n_m1_activity, hour_str)[0]] + + # Step 1. Compressing the hourly schedule to the following format: + # The integer indicates the number of hours. They should add up to 24. + # [['sleeping', 6], ['waking up and starting her morning routine', 1], + # ['eating breakfast', 1], ['getting ready for the day', 1], + # ['working on her painting', 2], ['taking a break', 1], + # ['having lunch', 1], ['working on her painting', 3], + # ['taking a break', 2], ['working on her painting', 2], + # ['relaxing and watching TV', 1], ['going to bed', 1], ['sleeping', 2]] + _n_m1_hourly_compressed = [] + prev = None + prev_count = 0 + for i in n_m1_activity: + if i != prev: + prev_count = 1 + _n_m1_hourly_compressed += [[i, prev_count]] + prev = i + elif _n_m1_hourly_compressed: + _n_m1_hourly_compressed[-1][1] += 1 + + # Step 2. Expand to min scale (from hour scale) + # [['sleeping', 360], ['waking up and starting her morning routine', 60], + # ['eating breakfast', 60],.. + n_m1_hourly_compressed = [] + for task, duration in _n_m1_hourly_compressed: + n_m1_hourly_compressed += [[task, duration*60]] + + return n_m1_hourly_compressed + diff --git a/examples/st_game/actions/task_decomp.py b/examples/st_game/actions/task_decomp.py new file mode 100644 index 000000000..13bd01727 --- /dev/null +++ b/examples/st_game/actions/task_decomp.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# @Desc : task_decomp + +import datetime + +from metagpt.logs import logger +from metagpt.schema import Message + +from ..roles.st_role import STRole +from ..actions.st_action import STAction + + +class TaskDecomp(STAction): + + def __init__(self, name="TaskDecomp", context: list[Message] = None, llm=None): + super().__init__(name, context, llm) + + def _func_cleanup(self, llm_resp: str, prompt: str) -> list: + # TODO SOMETHING HERE sometimes fails... See screenshot + temp = [i.strip() for i in llm_resp.split("\n")] + _cr = [] + cr = [] + for count, i in enumerate(temp): + if count != 0: + _cr += [" ".join([j.strip () for j in i.split(" ")][3:])] + else: + _cr += [i] + for count, i in enumerate(_cr): + k = [j.strip() for j in i.split("(duration in minutes:")] + task = k[0] + if task[-1] == ".": + task = task[:-1] + duration = int(k[1].split(",")[0].strip()) + cr += [[task, duration]] + + total_expected_min = int(prompt.split("(total duration in minutes")[-1] + .split("):")[0].strip()) + + # TODO -- now, you need to make sure that this is the same as the sum of + # the current action sequence. + curr_min_slot = [["dummy", -1],] # (task_name, task_index) + for count, i in enumerate(cr): + i_task = i[0] + i_duration = i[1] + + i_duration -= (i_duration % 5) + if i_duration > 0: + for j in range(i_duration): + curr_min_slot += [(i_task, count)] + curr_min_slot = curr_min_slot[1:] + + if len(curr_min_slot) > total_expected_min: + last_task = curr_min_slot[60] + for i in range(1, 6): + curr_min_slot[-1 * i] = last_task + elif len(curr_min_slot) < total_expected_min: + last_task = curr_min_slot[-1] + for i in range(total_expected_min - len(curr_min_slot)): + curr_min_slot += [last_task] + + cr_ret = [["dummy", -1],] + for task, task_index in curr_min_slot: + if task != cr_ret[-1][0]: + cr_ret += [[task, 1]] + else: + cr_ret[-1][1] += 1 + cr = cr_ret[1:] + + return cr + + def _func_validate(self, llm_resp: str, prompt: str) -> bool: + # TODO -- this sometimes generates error + try: + self._func_cleanup(llm_resp) + except: + return False + return True + + def _func_fail_default_resp(self) -> int: + fs = ["asleep"] + return fs + + def run(self, + role: STRole, + main_act_dur: int, + truncated_act_dur: int, + start_time_hour: datetime, + end_time_hour: datetime, + inserted_act: str, + inserted_act_dur: int, + *args, **kwargs): + + def create_prompt_input(role, task, duration): + + """ + Today is Saturday June 25. From 00:00 ~ 06:00am, Maeve is + planning on sleeping, 06:00 ~ 07:00am, Maeve is + planning on waking up and doing her morning routine, + and from 07:00am ~08:00am, Maeve is planning on having breakfast. + """ + + curr_f_org_index = role.scratch.get_f_daily_schedule_hourly_org_index() + all_indices = [] + # if curr_f_org_index > 0: + # all_indices += [curr_f_org_index-1] + all_indices += [curr_f_org_index] + if curr_f_org_index+1 <= len(role.scratch.f_daily_schedule_hourly_org): + all_indices += [curr_f_org_index+1] + if curr_f_org_index+2 <= len(role.scratch.f_daily_schedule_hourly_org): + all_indices += [curr_f_org_index+2] + + curr_time_range = "" + + print ("DEBUG") + print (role.scratch.f_daily_schedule_hourly_org) + print (all_indices) + + summ_str = f'Today is {role.scratch.curr_time.strftime("%B %d, %Y")}. ' + summ_str += f'From ' + for index in all_indices: + print ("index", index) + if index < len(role.scratch.f_daily_schedule_hourly_org): + start_min = 0 + for i in range(index): + start_min += role.scratch.f_daily_schedule_hourly_org[i][1] + end_min = start_min + role.scratch.f_daily_schedule_hourly_org[index][1] + start_time = (datetime.datetime.strptime("00:00:00", "%H:%M:%S") + + datetime.timedelta(minutes=start_min)) + end_time = (datetime.datetime.strptime("00:00:00", "%H:%M:%S") + + datetime.timedelta(minutes=end_min)) + start_time_str = start_time.strftime("%H:%M%p") + end_time_str = end_time.strftime("%H:%M%p") + summ_str += f"{start_time_str} ~ {end_time_str}, {role.name} is planning on {role.scratch.f_daily_schedule_hourly_org[index][0]}, " + if curr_f_org_index+1 == index: + curr_time_range = f'{start_time_str} ~ {end_time_str}' + summ_str = summ_str[:-2] + "." + + prompt_input = [] + prompt_input += [role.scratch.get_str_iss()] + prompt_input += [summ_str] + # prompt_input += [role.scratch.get_str_curr_date_str()] + prompt_input += [role.scratch.get_str_firstname()] + prompt_input += [role.scratch.get_str_firstname()] + prompt_input += [task] + prompt_input += [curr_time_range] + prompt_input += [duration] + prompt_input += [role.scratch.get_str_firstname()] + return prompt_input + + prompt_input = create_prompt_input(role, + main_act_dur, + truncated_act_dur, + start_time_hour, + end_time_hour, + inserted_act, + inserted_act_dur) + prompt = self.generate_prompt_with_tmpl_filename(prompt_input, + "task_decomp_v3.txt") + self.fail_default_resp = self._func_fail_default_resp(main_act_dur, truncated_act_dur) + output = self._run_v1(prompt) + return output diff --git a/examples/st_game/actions/wake_up.py b/examples/st_game/actions/wake_up.py new file mode 100644 index 000000000..911c8ebcf --- /dev/null +++ b/examples/st_game/actions/wake_up.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# @Desc : wake_up + +import datetime + +from metagpt.logs import logger +from metagpt.schema import Message + +from ..roles.st_role import STRole +from ..actions.st_action import STAction + + +class WakeUp(STAction): + + def __init__(self, name="WakeUp", context: list[Message] = None, llm=None): + super().__init__(name, context, llm) + + def _func_validate(self, llm_resp: str, prompt: str) -> bool: + try: + self._func_cleanup(llm_resp, prompt="") + except: + return False + return True + + def _func_cleanup(self, llm_resp: str, prompt: str) -> list: + cr = int(llm_resp.strip().lower().split("am")[0]) + return cr + + def _func_fail_default_resp(self) -> int: + fs = 8 + return fs + + def run(self, role: STRole): + def create_prompt_input(role): + prompt_input = [role.scratch.get_str_iss(), + role.scratch.get_str_lifestyle(), + role.scratch.get_str_firstname()] + return prompt_input + + prompt_input = create_prompt_input(role) + prompt = self.generate_prompt_with_tmpl_filename(prompt_input, "wake_up_hour_v1.txt") + self.fail_default_resp = self._func_fail_default_resp() + output = self._run_v1(prompt) + return output \ No newline at end of file diff --git a/examples/st_game/prompts/daily_planning_v6.txt b/examples/st_game/prompts/daily_planning_v6.txt new file mode 100644 index 000000000..dea6a28d7 --- /dev/null +++ b/examples/st_game/prompts/daily_planning_v6.txt @@ -0,0 +1,14 @@ +daily_planning_v6.txt + +Variables: +!! -- Commonset +!! -- Lifestyle +!! -- Reverie date time now +!! -- Persona first names +!! -- wake_up_hour + +### +!! + +In general, !! +Today is !!. Here is !!'s plan today in broad-strokes (with the time of the day. e.g., have a lunch at 12:00 pm, watch TV from 7 to 8 pm): 1) wake up and complete the morning routine at !!, 2) \ No newline at end of file diff --git a/examples/st_game/prompts/generate_event_triple_v1.txt b/examples/st_game/prompts/generate_event_triple_v1.txt index 699ce154c..1e9b7d6d5 100644 --- a/examples/st_game/prompts/generate_event_triple_v1.txt +++ b/examples/st_game/prompts/generate_event_triple_v1.txt @@ -27,4 +27,4 @@ Input: Merrie Morris is running on a treadmill. Output: (Merrie Morris, run, treadmill) --- Input: !! is !!. -Output: (!!, \ No newline at end of file +Output: (!!, diff --git a/examples/st_game/prompts/generate_hourly_schedule_v2.txt b/examples/st_game/prompts/generate_hourly_schedule_v2.txt new file mode 100644 index 000000000..2d6f5762c --- /dev/null +++ b/examples/st_game/prompts/generate_hourly_schedule_v2.txt @@ -0,0 +1,18 @@ +generate_hourly_schedule_v2.txt + +Variables: +!! -- Schedule format +!! -- Commonset +!! -- prior_schedule +!! -- intermission_str +!! -- intermission 2 +!! -- prompt_ending + +### +Hourly schedule format: +!! +=== +!! +!! +!!!! +!! \ No newline at end of file diff --git a/examples/st_game/prompts/generate_obj_event_v1.txt b/examples/st_game/prompts/generate_obj_event_v1.txt new file mode 100644 index 000000000..e8d45e638 --- /dev/null +++ b/examples/st_game/prompts/generate_obj_event_v1.txt @@ -0,0 +1,16 @@ +generate_obj_event_v1.txt + +Variables: +!! -- Object name +!! -- Persona name +!! -- Persona action event description +!! -- Object name +!! -- Object name + +### +Task: We want to understand the state of an object that is being used by someone. + +Let's think step by step. +We want to know about !!'s state. +Step 1. !! is at/using the !!. +Step 2. Describe the !!'s state: !! is \ No newline at end of file diff --git a/examples/st_game/prompts/task_decomp_v3.txt b/examples/st_game/prompts/task_decomp_v3.txt new file mode 100644 index 000000000..2ba016c21 --- /dev/null +++ b/examples/st_game/prompts/task_decomp_v3.txt @@ -0,0 +1,39 @@ +task_decomp_v2.txt + +Variables: +!! -- Commonset +!! -- Surrounding schedule description +!! -- Persona first name +!! -- Persona first name +!! -- Current action +!! -- curr time range +!! -- Current action duration in min +!! -- Persona first names + +### +Describe subtasks in 5 min increments. +--- +Name: Kelly Bronson +Age: 35 +Backstory: Kelly always wanted to be a teacher, and now she teaches kindergarten. During the week, she dedicates herself to her students, but on the weekends, she likes to try out new restaurants and hang out with friends. She is very warm and friendly, and loves caring for others. +Personality: sweet, gentle, meticulous +Location: Kelly is in an older condo that has the following areas: {kitchen, bedroom, dining, porch, office, bathroom, living room, hallway}. +Currently: Kelly is a teacher during the school year. She teaches at the school but works on lesson plans at home. She is currently living alone in a single bedroom condo. +Daily plan requirement: Kelly is planning to teach during the morning and work from home in the afternoon.s + +Today is Saturday May 10. From 08:00am ~09:00am, Kelly is planning on having breakfast, from 09:00am ~ 12:00pm, Kelly is planning on working on the next day's kindergarten lesson plan, and from 12:00 ~ 13pm, Kelly is planning on taking a break. +In 5 min increments, list the subtasks Kelly does when Kelly is working on the next day's kindergarten lesson plan from 09:00am ~ 12:00pm (total duration in minutes: 180): +1) Kelly is reviewing the kindergarten curriculum standards. (duration in minutes: 15, minutes left: 165) +2) Kelly is brainstorming ideas for the lesson. (duration in minutes: 30, minutes left: 135) +3) Kelly is creating the lesson plan. (duration in minutes: 30, minutes left: 105) +4) Kelly is creating materials for the lesson. (duration in minutes: 30, minutes left: 75) +5) Kelly is taking a break. (duration in minutes: 15, minutes left: 60) +6) Kelly is reviewing the lesson plan. (duration in minutes: 30, minutes left: 30) +7) Kelly is making final changes to the lesson plan. (duration in minutes: 15, minutes left: 15) +8) Kelly is printing the lesson plan. (duration in minutes: 10, minutes left: 5) +9) Kelly is putting the lesson plan in her bag. (duration in minutes: 5, minutes left: 0) +--- +!! +!! +In 5 min increments, list the subtasks !! does when !! is !! from !! (total duration in minutes !!): +1) !! is \ No newline at end of file diff --git a/examples/st_game/prompts/wake_up_hour_v1.txt b/examples/st_game/prompts/wake_up_hour_v1.txt new file mode 100644 index 000000000..c0a635654 --- /dev/null +++ b/examples/st_game/prompts/wake_up_hour_v1.txt @@ -0,0 +1,12 @@ +wake_up_hour_v1.txt + +Variables: +!! -- Identity Stable Set +!! -- Lifestyle +!! -- Persona first names + +### +!! + +In general, !! +!!'s wake up hour: \ No newline at end of file