{"repo_id":"BOLAA","entity_id":"py:run_webagent","uri":"program://BOLAA/module/run_webagent#L1-L127","kind":"module","name":"run_webagent","path":"run_webagent.py","language":"python","start_line":1,"end_line":127,"context_start_line":1,"context_end_line":127,"code":"import os\nimport sys\nimport json\nimport random\nimport argparse\nfrom concurrent.futures import ThreadPoolExecutor\nimport time\n\nfrom web_run.web_env import webshopEnv\nfrom web_run.llms import get_llm_backend, OPENAI_CHAT_MODELS, OPENAI_LLM_MODELS\nfrom web_run.multi_agent_arch import SearchAgent, ClickAgent, ControlAgent\nimport web_run.agent_arch as agent_arch\nfrom web_run.utils import session_save, get_instruction, get_env_botton\nfrom web_run.evaluate import get_file_sess_idx\nfrom web_run.config import available_agent_names\n\nparser = argparse.ArgumentParser(description='Parsing the input of agents, llms and llm context length.')\nparser.add_argument(\"--agent_name\", type=str, help=\"Name of the agent.\", default=\"React\")\nparser.add_argument(\"--llm_name\", type=str, help=\"Name of the llm\", default=\"gpt-3.5-turbo\")\nparser.add_argument(\"--max_context_len\", type=int, help=\"Maximum context length\", default=1700)\nargs = parser.parse_args()\nagent_name = args.agent_name\nllm_name = args.llm_name\nmax_context_len = args.max_context_len\n\nassert agent_name in available_agent_names, f\"Invalid agent name. Allowed values are {available_agent_names}\"\n\ndef run_one_session(idx, max_steps=50):\n env = webshopEnv()\n llm_backend = get_llm_backend(llm_name)\n llm = llm_backend.run\n if agent_name in [\"React_Webrun_Agent\"]:\n agent = agent_arch.ReactAgent(llm, max_context_len)\n elif agent_name in [\"Zeroshot_Webrun_Agent\"]:\n agent = agent_arch.ZeroshotAgent(llm, max_context_len)\n elif agent_name in [\"ZeroshotThink_Webrun_Agent\"]:\n agent = agent_arch.ZeroshotThinkAgent(llm, max_context_len)\n elif agent_name in [\"Planner_Webrun_Agent\"]:\n agent = agent_arch.PlannerAgent(llm, max_context_len)\n elif agent_name in [\"PlannerReact_Webrun_Agent\"]:\n agent = agent_arch.PlannerReactAgent(llm, max_context_len)\n elif agent_name in [\"Search_Click_Controller_Webrun_Agent\",\"Search_Click_Control_Webrun_Agent\"]:\n search_agent = SearchAgent(llm, max_context_len)\n click_agent = ClickAgent(llm, max_context_len)\n agent = ControlAgent([search_agent, click_agent])\n\n saving_path = f\"./execution_data/{agent.type}_{llm_name}_batch.json\"\n actions = []\n observations = []\n retrieved_items = []\n hulluci = 0\n # reset the environments\n action = 'reset'\n idx = f\"fixed_{idx}\"\n done = False\n observation, reward, done, asins, buttons = env.step(idx, action)\n env_bottons = get_env_botton(buttons)\n actions.append(action)\n observations.append(observation)\n retrieved_items.append(asins)\n inst = get_instruction(observation)\n agent.new_session(idx, inst)\n \n # start planning\n if agent_name in [\"PlannerReact_Webrun_Agent\", \"Planner_Webrun_Agent\"]:\n action = 'planning'\n agent.planning()\n agent.stop = [\"\\n\"]\n observation = agent.plan\n \n # start interaction\n for step in range(max_steps):\n actions.append(action)\n observations.append(observation)\n retrieved_items.append(asins)\n if not done:\n action = agent.forward(observation, env_bottons).lstrip(' ') \n # print(observation)\n print(action)\n if \"No response\" in action: # running too many sessions, end this session\n done = True\n # session_save(idx, actions, observations, retrieved_items, saving_path)\n return 0.0\n try:\n observation, reward, done, asins, buttons = env.step(idx, action)\n if \"Buy Now\" in action:\n print(observation, reward, done, asins, buttons)\n env_bottons = get_env_botton(buttons)\n except AssertionError:\n observation = 'Invalid action!'\n hulluci += 1\n if hulluci > 3:\n reward = 0.0\n done = True\n if \"handle_exception\" in observation: # running too many sessions, end this session\n done = True\n session_save(idx, actions, observations, retrieved_items, saving_path)\n return 0.0\n else:\n time.sleep(1)\n session_save(idx, actions, observations, retrieved_items, saving_path)\n print(\"saved!\")\n return reward\n session_save(idx, actions, observations, retrieved_items, saving_path)\n return 0.0\n\ndef run_episodes(session_list):\n work_num = 4\n if len(session_list) > work_num and not llm_name in (OPENAI_CHAT_MODELS + OPENAI_LLM_MODELS):\n with ThreadPoolExecutor(max_workers=work_num) as executor:\n # executor.map will return a list of tuples in the same order as idxs[:10]\n results = list(executor.map(run_one_session, session_list))\n # print(sum(results)/len(results))\n print(\"Done the session running!\")\n else:\n for sid in session_list:\n run_one_session(sid)\n\nfile_name = f\"./execution_data/webrun/{agent_name}_{llm_name}_batch.json\"\nif os.path.exists(file_name):\n executed_sess = get_file_sess_idx(file_name)\n session_list = [j for j in range(900) if j not in executed_sess]\n run_episodes(session_list)\nelse:\n run_episodes(list(range(0, 900)))\n\n","source_hash":"7881aab9ac9444401897a186b7385bcf5c38985185352d163a0cf452330b326f","truncated":false} {"repo_id":"BOLAA","entity_id":"py:run_webagent.run_one_session","uri":"program://BOLAA/function/run_webagent.run_one_session#L28-L105","kind":"function","name":"run_one_session","path":"run_webagent.py","language":"python","start_line":28,"end_line":105,"context_start_line":8,"context_end_line":125,"code":"\nfrom web_run.web_env import webshopEnv\nfrom web_run.llms import get_llm_backend, OPENAI_CHAT_MODELS, OPENAI_LLM_MODELS\nfrom web_run.multi_agent_arch import SearchAgent, ClickAgent, ControlAgent\nimport web_run.agent_arch as agent_arch\nfrom web_run.utils import session_save, get_instruction, get_env_botton\nfrom web_run.evaluate import get_file_sess_idx\nfrom web_run.config import available_agent_names\n\nparser = argparse.ArgumentParser(description='Parsing the input of agents, llms and llm context length.')\nparser.add_argument(\"--agent_name\", type=str, help=\"Name of the agent.\", default=\"React\")\nparser.add_argument(\"--llm_name\", type=str, help=\"Name of the llm\", default=\"gpt-3.5-turbo\")\nparser.add_argument(\"--max_context_len\", type=int, help=\"Maximum context length\", default=1700)\nargs = parser.parse_args()\nagent_name = args.agent_name\nllm_name = args.llm_name\nmax_context_len = args.max_context_len\n\nassert agent_name in available_agent_names, f\"Invalid agent name. Allowed values are {available_agent_names}\"\n\ndef run_one_session(idx, max_steps=50):\n env = webshopEnv()\n llm_backend = get_llm_backend(llm_name)\n llm = llm_backend.run\n if agent_name in [\"React_Webrun_Agent\"]:\n agent = agent_arch.ReactAgent(llm, max_context_len)\n elif agent_name in [\"Zeroshot_Webrun_Agent\"]:\n agent = agent_arch.ZeroshotAgent(llm, max_context_len)\n elif agent_name in [\"ZeroshotThink_Webrun_Agent\"]:\n agent = agent_arch.ZeroshotThinkAgent(llm, max_context_len)\n elif agent_name in [\"Planner_Webrun_Agent\"]:\n agent = agent_arch.PlannerAgent(llm, max_context_len)\n elif agent_name in [\"PlannerReact_Webrun_Agent\"]:\n agent = agent_arch.PlannerReactAgent(llm, max_context_len)\n elif agent_name in [\"Search_Click_Controller_Webrun_Agent\",\"Search_Click_Control_Webrun_Agent\"]:\n search_agent = SearchAgent(llm, max_context_len)\n click_agent = ClickAgent(llm, max_context_len)\n agent = ControlAgent([search_agent, click_agent])\n\n saving_path = f\"./execution_data/{agent.type}_{llm_name}_batch.json\"\n actions = []\n observations = []\n retrieved_items = []\n hulluci = 0\n # reset the environments\n action = 'reset'\n idx = f\"fixed_{idx}\"\n done = False\n observation, reward, done, asins, buttons = env.step(idx, action)\n env_bottons = get_env_botton(buttons)\n actions.append(action)\n observations.append(observation)\n retrieved_items.append(asins)\n inst = get_instruction(observation)\n agent.new_session(idx, inst)\n \n # start planning\n if agent_name in [\"PlannerReact_Webrun_Agent\", \"Planner_Webrun_Agent\"]:\n action = 'planning'\n agent.planning()\n agent.stop = [\"\\n\"]\n observation = agent.plan\n \n # start interaction\n for step in range(max_steps):\n actions.append(action)\n observations.append(observation)\n retrieved_items.append(asins)\n if not done:\n action = agent.forward(observation, env_bottons).lstrip(' ') \n # print(observation)\n print(action)\n if \"No response\" in action: # running too many sessions, end this session\n done = True\n # session_save(idx, actions, observations, retrieved_items, saving_path)\n return 0.0\n try:\n observation, reward, done, asins, buttons = env.step(idx, action)\n if \"Buy Now\" in action:\n print(observation, reward, done, asins, buttons)\n env_bottons = get_env_botton(buttons)\n except AssertionError:\n observation = 'Invalid action!'\n hulluci += 1\n if hulluci > 3:\n reward = 0.0\n done = True\n if \"handle_exception\" in observation: # running too many sessions, end this session\n done = True\n session_save(idx, actions, observations, retrieved_items, saving_path)\n return 0.0\n else:\n time.sleep(1)\n session_save(idx, actions, observations, retrieved_items, saving_path)\n print(\"saved!\")\n return reward\n session_save(idx, actions, observations, retrieved_items, saving_path)\n return 0.0\n\ndef run_episodes(session_list):\n work_num = 4\n if len(session_list) > work_num and not llm_name in (OPENAI_CHAT_MODELS + OPENAI_LLM_MODELS):\n with ThreadPoolExecutor(max_workers=work_num) as executor:\n # executor.map will return a list of tuples in the same order as idxs[:10]\n results = list(executor.map(run_one_session, session_list))\n # print(sum(results)/len(results))\n print(\"Done the session running!\")\n else:\n for sid in session_list:\n run_one_session(sid)\n\nfile_name = f\"./execution_data/webrun/{agent_name}_{llm_name}_batch.json\"\nif os.path.exists(file_name):\n executed_sess = get_file_sess_idx(file_name)\n session_list = [j for j in range(900) if j not in executed_sess]\n run_episodes(session_list)\nelse:\n run_episodes(list(range(0, 900)))","source_hash":"7881aab9ac9444401897a186b7385bcf5c38985185352d163a0cf452330b326f","truncated":false} {"repo_id":"BOLAA","entity_id":"py:run_webagent.run_episodes","uri":"program://BOLAA/function/run_webagent.run_episodes#L107-L117","kind":"function","name":"run_episodes","path":"run_webagent.py","language":"python","start_line":107,"end_line":117,"context_start_line":87,"context_end_line":127,"code":" print(observation, reward, done, asins, buttons)\n env_bottons = get_env_botton(buttons)\n except AssertionError:\n observation = 'Invalid action!'\n hulluci += 1\n if hulluci > 3:\n reward = 0.0\n done = True\n if \"handle_exception\" in observation: # running too many sessions, end this session\n done = True\n session_save(idx, actions, observations, retrieved_items, saving_path)\n return 0.0\n else:\n time.sleep(1)\n session_save(idx, actions, observations, retrieved_items, saving_path)\n print(\"saved!\")\n return reward\n session_save(idx, actions, observations, retrieved_items, saving_path)\n return 0.0\n\ndef run_episodes(session_list):\n work_num = 4\n if len(session_list) > work_num and not llm_name in (OPENAI_CHAT_MODELS + OPENAI_LLM_MODELS):\n with ThreadPoolExecutor(max_workers=work_num) as executor:\n # executor.map will return a list of tuples in the same order as idxs[:10]\n results = list(executor.map(run_one_session, session_list))\n # print(sum(results)/len(results))\n print(\"Done the session running!\")\n else:\n for sid in session_list:\n run_one_session(sid)\n\nfile_name = f\"./execution_data/webrun/{agent_name}_{llm_name}_batch.json\"\nif os.path.exists(file_name):\n executed_sess = get_file_sess_idx(file_name)\n session_list = [j for j in range(900) if j not in executed_sess]\n run_episodes(session_list)\nelse:\n run_episodes(list(range(0, 900)))\n\n","source_hash":"7881aab9ac9444401897a186b7385bcf5c38985185352d163a0cf452330b326f","truncated":false} {"repo_id":"BOLAA","entity_id":"py:run_hotpotqaagent","uri":"program://BOLAA/module/run_hotpotqaagent#L1-L53","kind":"module","name":"run_hotpotqaagent","path":"run_hotpotqaagent.py","language":"python","start_line":1,"end_line":53,"context_start_line":1,"context_end_line":53,"code":"import os\nimport argparse \nimport numpy as np\nimport pandas as pd\nimport concurrent\nimport joblib\nfrom hotpotqa_run.utils import summarize_trial_detailed, log_trial\nimport hotpotqa_run.utils as utils\nfrom hotpotqa_run.agent_arch import get_agent\nfrom hotpotqa_run.llms import get_llm_backend\nfrom hotpotqa_run.config import available_agent_names\n\n\nparser = argparse.ArgumentParser(description='Parsing the input of agents, llms and llm context length.')\nparser.add_argument(\"--agent_name\", type=str, help=\"Name of the agent.\", default=\"React\")\nparser.add_argument(\"--llm_name\", type=str, help=\"Name of the llm\", default=\"gpt-3.5-turbo\")\nparser.add_argument(\"--max_context_len\", type=int, help=\"Maximum context length\", default=1700)\nargs = parser.parse_args()\n\nagent_name = args.agent_name\nllm_name = args.llm_name\nmax_context_len = args.max_context_len\nassert agent_name in available_agent_names\n\ndef process_agent_run_step(agent):\n agent.run()\n\ndef run_one_complex_level(level=\"easy\"):\n hotpot = joblib.load(f'hotpotqa_run/data/{level}.joblib').reset_index(drop = True)\n agent_save_file = f\"execution_data/hotpotqa/{level}_{agent_name}_{llm_name}.jsonl\"\n task_instructions = [(row['question'], row['answer']) for _, row in hotpot.iterrows()]\n if os.path.exists(agent_save_file):\n sessions = utils.get_all_agent_sessions(agent_save_file)\n completed_tasks = utils.get_non_error_tasks(sessions)\n print(f\"{level}:{len(completed_tasks)}\")\n task_instructions = [task for task in task_instructions if task not in completed_tasks]\n utils.delete_error(agent_save_file)\n llm = get_llm_backend(llm_name).run\n agent_cls = get_agent(agent_name)\n agents = [agent_cls(ques, ans, llm, max_context_len) for ques, ans in task_instructions]\n with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor:\n executor.map(process_agent_run_step, agents)\n for agent in agents:\n utils.log_agent(agent, agent_save_file)\n print(f'Finished Trial. Total: {len(agents)}')\n \ndef main():\n levels = ['easy', 'medium', 'hard']\n for level in levels:\n run_one_complex_level(level)\n \nif __name__ == '__main__':\n main()","source_hash":"8e7b0bd4cfe46479f31447fca04517a6e36531bff1ff8d9ef5aa3fd61d696449","truncated":false} {"repo_id":"BOLAA","entity_id":"py:run_hotpotqaagent.process_agent_run_step","uri":"program://BOLAA/function/run_hotpotqaagent.process_agent_run_step#L25-L26","kind":"function","name":"process_agent_run_step","path":"run_hotpotqaagent.py","language":"python","start_line":25,"end_line":26,"context_start_line":5,"context_end_line":46,"code":"import concurrent\nimport joblib\nfrom hotpotqa_run.utils import summarize_trial_detailed, log_trial\nimport hotpotqa_run.utils as utils\nfrom hotpotqa_run.agent_arch import get_agent\nfrom hotpotqa_run.llms import get_llm_backend\nfrom hotpotqa_run.config import available_agent_names\n\n\nparser = argparse.ArgumentParser(description='Parsing the input of agents, llms and llm context length.')\nparser.add_argument(\"--agent_name\", type=str, help=\"Name of the agent.\", default=\"React\")\nparser.add_argument(\"--llm_name\", type=str, help=\"Name of the llm\", default=\"gpt-3.5-turbo\")\nparser.add_argument(\"--max_context_len\", type=int, help=\"Maximum context length\", default=1700)\nargs = parser.parse_args()\n\nagent_name = args.agent_name\nllm_name = args.llm_name\nmax_context_len = args.max_context_len\nassert agent_name in available_agent_names\n\ndef process_agent_run_step(agent):\n agent.run()\n\ndef run_one_complex_level(level=\"easy\"):\n hotpot = joblib.load(f'hotpotqa_run/data/{level}.joblib').reset_index(drop = True)\n agent_save_file = f\"execution_data/hotpotqa/{level}_{agent_name}_{llm_name}.jsonl\"\n task_instructions = [(row['question'], row['answer']) for _, row in hotpot.iterrows()]\n if os.path.exists(agent_save_file):\n sessions = utils.get_all_agent_sessions(agent_save_file)\n completed_tasks = utils.get_non_error_tasks(sessions)\n print(f\"{level}:{len(completed_tasks)}\")\n task_instructions = [task for task in task_instructions if task not in completed_tasks]\n utils.delete_error(agent_save_file)\n llm = get_llm_backend(llm_name).run\n agent_cls = get_agent(agent_name)\n agents = [agent_cls(ques, ans, llm, max_context_len) for ques, ans in task_instructions]\n with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor:\n executor.map(process_agent_run_step, agents)\n for agent in agents:\n utils.log_agent(agent, agent_save_file)\n print(f'Finished Trial. Total: {len(agents)}')\n ","source_hash":"8e7b0bd4cfe46479f31447fca04517a6e36531bff1ff8d9ef5aa3fd61d696449","truncated":false} {"repo_id":"BOLAA","entity_id":"py:run_hotpotqaagent.run_one_complex_level","uri":"program://BOLAA/function/run_hotpotqaagent.run_one_complex_level#L28-L45","kind":"function","name":"run_one_complex_level","path":"run_hotpotqaagent.py","language":"python","start_line":28,"end_line":45,"context_start_line":8,"context_end_line":53,"code":"import hotpotqa_run.utils as utils\nfrom hotpotqa_run.agent_arch import get_agent\nfrom hotpotqa_run.llms import get_llm_backend\nfrom hotpotqa_run.config import available_agent_names\n\n\nparser = argparse.ArgumentParser(description='Parsing the input of agents, llms and llm context length.')\nparser.add_argument(\"--agent_name\", type=str, help=\"Name of the agent.\", default=\"React\")\nparser.add_argument(\"--llm_name\", type=str, help=\"Name of the llm\", default=\"gpt-3.5-turbo\")\nparser.add_argument(\"--max_context_len\", type=int, help=\"Maximum context length\", default=1700)\nargs = parser.parse_args()\n\nagent_name = args.agent_name\nllm_name = args.llm_name\nmax_context_len = args.max_context_len\nassert agent_name in available_agent_names\n\ndef process_agent_run_step(agent):\n agent.run()\n\ndef run_one_complex_level(level=\"easy\"):\n hotpot = joblib.load(f'hotpotqa_run/data/{level}.joblib').reset_index(drop = True)\n agent_save_file = f\"execution_data/hotpotqa/{level}_{agent_name}_{llm_name}.jsonl\"\n task_instructions = [(row['question'], row['answer']) for _, row in hotpot.iterrows()]\n if os.path.exists(agent_save_file):\n sessions = utils.get_all_agent_sessions(agent_save_file)\n completed_tasks = utils.get_non_error_tasks(sessions)\n print(f\"{level}:{len(completed_tasks)}\")\n task_instructions = [task for task in task_instructions if task not in completed_tasks]\n utils.delete_error(agent_save_file)\n llm = get_llm_backend(llm_name).run\n agent_cls = get_agent(agent_name)\n agents = [agent_cls(ques, ans, llm, max_context_len) for ques, ans in task_instructions]\n with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor:\n executor.map(process_agent_run_step, agents)\n for agent in agents:\n utils.log_agent(agent, agent_save_file)\n print(f'Finished Trial. Total: {len(agents)}')\n \ndef main():\n levels = ['easy', 'medium', 'hard']\n for level in levels:\n run_one_complex_level(level)\n \nif __name__ == '__main__':\n main()","source_hash":"8e7b0bd4cfe46479f31447fca04517a6e36531bff1ff8d9ef5aa3fd61d696449","truncated":false} {"repo_id":"BOLAA","entity_id":"py:run_hotpotqaagent.main","uri":"program://BOLAA/function/run_hotpotqaagent.main#L47-L50","kind":"function","name":"main","path":"run_hotpotqaagent.py","language":"python","start_line":47,"end_line":50,"context_start_line":27,"context_end_line":53,"code":"\ndef run_one_complex_level(level=\"easy\"):\n hotpot = joblib.load(f'hotpotqa_run/data/{level}.joblib').reset_index(drop = True)\n agent_save_file = f\"execution_data/hotpotqa/{level}_{agent_name}_{llm_name}.jsonl\"\n task_instructions = [(row['question'], row['answer']) for _, row in hotpot.iterrows()]\n if os.path.exists(agent_save_file):\n sessions = utils.get_all_agent_sessions(agent_save_file)\n completed_tasks = utils.get_non_error_tasks(sessions)\n print(f\"{level}:{len(completed_tasks)}\")\n task_instructions = [task for task in task_instructions if task not in completed_tasks]\n utils.delete_error(agent_save_file)\n llm = get_llm_backend(llm_name).run\n agent_cls = get_agent(agent_name)\n agents = [agent_cls(ques, ans, llm, max_context_len) for ques, ans in task_instructions]\n with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor:\n executor.map(process_agent_run_step, agents)\n for agent in agents:\n utils.log_agent(agent, agent_save_file)\n print(f'Finished Trial. Total: {len(agents)}')\n \ndef main():\n levels = ['easy', 'medium', 'hard']\n for level in levels:\n run_one_complex_level(level)\n \nif __name__ == '__main__':\n main()","source_hash":"8e7b0bd4cfe46479f31447fca04517a6e36531bff1ff8d9ef5aa3fd61d696449","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.config","uri":"program://BOLAA/module/web_run.config#L1-L11","kind":"module","name":"web_run.config","path":"web_run/config.py","language":"python","start_line":1,"end_line":11,"context_start_line":1,"context_end_line":11,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\navailable_agent_names = [\"Zeroshot_Webrun_Agent\",\"ZeroshotThink_Webrun_Agent\",\n \"React_Webrun_Agent\",\"Planner_Webrun_Agent\",\n \"PlannerReact_Webrun_Agent\",\"Search_Click_Control_Webrun_Agent\"]\nOPENAI_API_KEY = \"\"","source_hash":"963bf61d4596fcacfad502a585d85341e4581ad426a76d7da2f6898a51857722","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.agent_arch","uri":"program://BOLAA/module/web_run.agent_arch#L1-L245","kind":"module","name":"web_run.agent_arch","path":"web_run/agent_arch.py","language":"python","start_line":1,"end_line":245,"context_start_line":1,"context_end_line":245,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport random\nimport re\nimport json \nimport time\nimport os\nimport tiktoken\nimport web_run.pre_prompt as pre_prompt\nfrom web_run.utils import get_query\nfrom web_run.llms import token_enc\n\n\nclass BaseAgent(object):\n def __init__(self, llm, context_len=2000):\n self.type = \"Base_Webrun_Agent\"\n self.life_label = time.time()\n self.name = f\"{self.type}_{self.life_label}\"\n self.task = {}\n self.actions = {}\n self.observations = {}\n self.item_recall = {}\n self.llm = llm\n self.context_len = context_len\n self.cur_session = 0\n \n def new_session(self, idx, task):\n self.cur_session = idx\n self.task[idx] = task\n self.actions[idx] = ['reset']\n self.observations[idx] = []\n self.item_recall[idx] = []\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def get_history(self, session=None):\n if not session:\n session = self.cur_session\n history = \"\"\n for idx in range(1, len(self.actions[session])):\n history += f\"Action: {self.actions[session][idx]}\\n\"\n history += f\"Observation: {self.observations[session][idx]}\\n\\n\"\n return history\n \n def save(self, path):\n file_name = os.path.join(path, self.name+'_'+str(self.life_label))\n with open(file_name, 'a') as f:\n f.write(f\"session_idx:{self.cur_session}\\n\")\n history = self.get_history(self.cur_session)\n f.write(history)\n f.write('\\n')\n \n def action_parser(self, text, available_actions):\n nor_text = text.strip().lower()\n if nor_text.startswith('search'):\n query = get_query(nor_text)\n return f\"search[{query}]\"\n if nor_text.startswith('click'):\n if 'click' in available_actions:\n for a in available_actions['click']:\n if a.lower() in nor_text:\n return f\"click[{a}]\"\n return text\n \n def prompt_layer(self):\n raise NotImplementedError\n \n def forward(self, observation, available_actions=None):\n raise NotImplementedError\n\n\nclass ReactAgent(BaseAgent):\n def __init__(self, llm, context_len=2000):\n super().__init__(llm, context_len)\n self.type = \"React_Webrun_Agent\"\n self.name = f\"{self.type}_{self.life_label}\"\n \n def prompt_layer(self):\n one_shot = pre_prompt.oneshot\n prompt = f\"{one_shot}{self.observations[self.cur_session][0]}\\n\\nAction:\"\n if len(self.actions[self.cur_session]) > 1:\n initial_prompt = f\"{one_shot}{self.observations[self.cur_session][0]}\\n\\n\"\n history = self.get_history()\n remain_context_space = (self.context_len - len(token_enc.encode(initial_prompt)))*3\n history = history[-int(remain_context_space):]\n prompt = f\"{initial_prompt}{history}\\n\\nAction:\"\n return prompt\n \n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n prompt = self.prompt_layer()\n action = self.llm_layer(prompt)\n self.actions[self.cur_session].append(action)\n return action\n \nclass ZeroshotAgent(BaseAgent):\n def __init__(self, llm, context_len=2000, temperature=0.9, stop=['\\n']):\n super().__init__(llm, context_len)\n self.type = \"Zeroshot_Webrun_Agent\"\n self.life_label = time.time()\n self.name = f\"{self.type}_{self.life_label}\"\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def avai_action_prompt(self, available_actions):\n if 'search' in available_actions:\n return \"{search}\"\n elif 'click' in available_actions:\n actions = available_actions['click']\n ac_string = \"\\t\".join(actions)\n return f\"click: [{ac_string}]\"\n \n def prompt_layer(self, available_actions):\n zeroshot = pre_prompt.zeroshot\n actions_prompt = f\"current available action is {self.avai_action_prompt(available_actions)[-3000:]}\"\n prompt = f\"{zeroshot}{self.observations[self.cur_session][0]}{actions_prompt}\\n\\nAction:\"\n if len(self.actions[self.cur_session]) > 1:\n initial_prompt = f\"{zeroshot}{self.observations[self.cur_session][0]}\\n\\n\"\n history = self.get_history()\n remain_context_space = (self.context_len - len(token_enc.encode(f\"{initial_prompt}{actions_prompt}\")))*3\n history = history[-int(remain_context_space):]\n prompt = f\"{initial_prompt}{history}{actions_prompt}\\n\\nAction:\"\n return prompt\n\n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n prompt = self.prompt_layer(available_actions)\n action = self.llm_layer(prompt).lstrip()\n action = self.action_parser(action, available_actions)\n self.actions[self.cur_session].append(action)\n return action\n \nclass ZeroshotThinkAgent(BaseAgent):\n def __init__(self, llm, context_len=2000, temperature=0.9, stop=['\\n']):\n super().__init__(llm, context_len)\n self.type = \"ZeroshotThink_Webrun_Agent\"\n self.life_label = time.time()\n self.name = f\"{self.type}_{self.life_label}\"\n self.temperature = temperature\n self.stop = stop\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def avai_action_prompt(self, available_actions):\n if 'search' in available_actions:\n return \"{search}\"\n elif 'click' in available_actions:\n actions = available_actions['click']\n ac_string = \"\\t\".join(actions)\n return f\"click: [{ac_string}]\"\n \n def prompt_layer(self, available_actions):\n zeroshot = pre_prompt.zeroshot_think\n actions_prompt = f\"current available action is {self.avai_action_prompt(available_actions)[-3000:]}\"\n prompt = f\"{zeroshot}{self.observations[self.cur_session][0]}{actions_prompt}\\n\\nAction:\"\n if len(self.actions[self.cur_session]) > 1:\n initial_prompt = f\"{zeroshot}{self.observations[self.cur_session][0]}\\n\\n\"\n history = self.get_history()\n remain_context_space = (self.context_len - len(token_enc.encode(initial_prompt+actions_prompt)))*3\n history = history[-int(remain_context_space):]\n prompt = f\"{initial_prompt}{history}{actions_prompt}\\n\\nAction:\"\n return prompt\n\n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n prompt = self.prompt_layer(available_actions)\n action = self.llm_layer(prompt, temperature=self.temperature, stop=self.stop).lstrip()\n action = self.action_parser(action, available_actions)\n self.actions[self.cur_session].append(action)\n return action\n \nclass PlannerAgent(BaseAgent):\n def __init__(self, llm, context_len=2000, temperature=0.9, stop=['\\n']):\n super().__init__(llm, context_len)\n self.type = \"Planner_Webrun_Agent\"\n self.name = f\"{self.type}_{self.life_label}\"\n self.temperature = temperature\n self.stop = stop\n self.max_plan_token_len = 256\n self.plan = None\n \n def planning(self):\n plan_prompt = f\"{pre_prompt.plan}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan:\"\n self.plan = self.llm(plan_prompt, temperature=self.temperature, stop=[\"\\n\"], \n max_tokens=self.max_plan_token_len)\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n\n def prompt_layer(self, available_actions):\n oneshot = pre_prompt.oneshot_plan \n prompt = f\"{oneshot}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan: {self.plan}\\n\\nAction:\"\n if len(self.actions[self.cur_session]) > 1:\n initial_prompt = f\"{oneshot}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan: {self.plan}\\n\\n\"\n history = self.get_history()\n remain_context_space = (self.context_len - len(token_enc.encode(initial_prompt)))*3\n history = history[-remain_context_space:]\n prompt = f\"{initial_prompt}{history}Action:\"\n return prompt\n \n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n prompt = self.prompt_layer(available_actions)\n action = self.llm_layer(prompt).lstrip(' ')\n action = self.action_parser(action, available_actions)\n self.actions[self.cur_session].append(action)\n return action\n\nclass PlannerReactAgent(PlannerAgent):\n def __init__(self, llm, context_len=2000, temperature=0.9, stop=['\\n']):\n super().__init__(llm, context_len, temperature, stop)\n self.type = \"PlannerReact_Webrun_Agent\"\n self.name = f\"{self.type}_{self.life_label}\"\n \n def planning(self):\n plan_prompt = f\"{pre_prompt.plan_react}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan:\"\n self.plan = self.llm(plan_prompt, temperature=self.temperature, stop=[\"\\n\"], \n max_tokens=self.max_plan_token_len)\n \n def prompt_layer(self, available_actions=None):\n oneshot = pre_prompt.oneshot_plan_react \n prompt = f\"{oneshot}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan: {self.plan}\\n\\nAction:\"\n if len(self.actions[self.cur_session]) > 1:\n initial_prompt = f\"{oneshot}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan: {self.plan}\\n\\n\"\n history = self.get_history()\n remain_context_space = (self.context_len - len(token_enc.encode(initial_prompt)))*3\n history = history[-remain_context_space:]\n prompt = f\"{initial_prompt}{history}Action:\"\n return prompt\n \n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n prompt = self.prompt_layer(available_actions)\n action = self.llm_layer(prompt).lstrip(' ')\n action = self.action_parser(action, available_actions)\n self.actions[self.cur_session].append(action)\n return action","source_hash":"8fca5841f4c2d805f5ace23a7168cbfb78d9436776779a88549101ffd96df94d","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.agent_arch.BaseAgent","uri":"program://BOLAA/class/web_run.agent_arch.BaseAgent#L19-L75","kind":"class","name":"BaseAgent","path":"web_run/agent_arch.py","language":"python","start_line":19,"end_line":75,"context_start_line":1,"context_end_line":95,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport random\nimport re\nimport json \nimport time\nimport os\nimport tiktoken\nimport web_run.pre_prompt as pre_prompt\nfrom web_run.utils import get_query\nfrom web_run.llms import token_enc\n\n\nclass BaseAgent(object):\n def __init__(self, llm, context_len=2000):\n self.type = \"Base_Webrun_Agent\"\n self.life_label = time.time()\n self.name = f\"{self.type}_{self.life_label}\"\n self.task = {}\n self.actions = {}\n self.observations = {}\n self.item_recall = {}\n self.llm = llm\n self.context_len = context_len\n self.cur_session = 0\n \n def new_session(self, idx, task):\n self.cur_session = idx\n self.task[idx] = task\n self.actions[idx] = ['reset']\n self.observations[idx] = []\n self.item_recall[idx] = []\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def get_history(self, session=None):\n if not session:\n session = self.cur_session\n history = \"\"\n for idx in range(1, len(self.actions[session])):\n history += f\"Action: {self.actions[session][idx]}\\n\"\n history += f\"Observation: {self.observations[session][idx]}\\n\\n\"\n return history\n \n def save(self, path):\n file_name = os.path.join(path, self.name+'_'+str(self.life_label))\n with open(file_name, 'a') as f:\n f.write(f\"session_idx:{self.cur_session}\\n\")\n history = self.get_history(self.cur_session)\n f.write(history)\n f.write('\\n')\n \n def action_parser(self, text, available_actions):\n nor_text = text.strip().lower()\n if nor_text.startswith('search'):\n query = get_query(nor_text)\n return f\"search[{query}]\"\n if nor_text.startswith('click'):\n if 'click' in available_actions:\n for a in available_actions['click']:\n if a.lower() in nor_text:\n return f\"click[{a}]\"\n return text\n \n def prompt_layer(self):\n raise NotImplementedError\n \n def forward(self, observation, available_actions=None):\n raise NotImplementedError\n\n\nclass ReactAgent(BaseAgent):\n def __init__(self, llm, context_len=2000):\n super().__init__(llm, context_len)\n self.type = \"React_Webrun_Agent\"\n self.name = f\"{self.type}_{self.life_label}\"\n \n def prompt_layer(self):\n one_shot = pre_prompt.oneshot\n prompt = f\"{one_shot}{self.observations[self.cur_session][0]}\\n\\nAction:\"\n if len(self.actions[self.cur_session]) > 1:\n initial_prompt = f\"{one_shot}{self.observations[self.cur_session][0]}\\n\\n\"\n history = self.get_history()\n remain_context_space = (self.context_len - len(token_enc.encode(initial_prompt)))*3\n history = history[-int(remain_context_space):]\n prompt = f\"{initial_prompt}{history}\\n\\nAction:\"\n return prompt\n \n def forward(self, observation, available_actions=None):","source_hash":"8fca5841f4c2d805f5ace23a7168cbfb78d9436776779a88549101ffd96df94d","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.agent_arch.ReactAgent","uri":"program://BOLAA/class/web_run.agent_arch.ReactAgent#L78-L100","kind":"class","name":"ReactAgent","path":"web_run/agent_arch.py","language":"python","start_line":78,"end_line":100,"context_start_line":58,"context_end_line":120,"code":" \n def action_parser(self, text, available_actions):\n nor_text = text.strip().lower()\n if nor_text.startswith('search'):\n query = get_query(nor_text)\n return f\"search[{query}]\"\n if nor_text.startswith('click'):\n if 'click' in available_actions:\n for a in available_actions['click']:\n if a.lower() in nor_text:\n return f\"click[{a}]\"\n return text\n \n def prompt_layer(self):\n raise NotImplementedError\n \n def forward(self, observation, available_actions=None):\n raise NotImplementedError\n\n\nclass ReactAgent(BaseAgent):\n def __init__(self, llm, context_len=2000):\n super().__init__(llm, context_len)\n self.type = \"React_Webrun_Agent\"\n self.name = f\"{self.type}_{self.life_label}\"\n \n def prompt_layer(self):\n one_shot = pre_prompt.oneshot\n prompt = f\"{one_shot}{self.observations[self.cur_session][0]}\\n\\nAction:\"\n if len(self.actions[self.cur_session]) > 1:\n initial_prompt = f\"{one_shot}{self.observations[self.cur_session][0]}\\n\\n\"\n history = self.get_history()\n remain_context_space = (self.context_len - len(token_enc.encode(initial_prompt)))*3\n history = history[-int(remain_context_space):]\n prompt = f\"{initial_prompt}{history}\\n\\nAction:\"\n return prompt\n \n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n prompt = self.prompt_layer()\n action = self.llm_layer(prompt)\n self.actions[self.cur_session].append(action)\n return action\n \nclass ZeroshotAgent(BaseAgent):\n def __init__(self, llm, context_len=2000, temperature=0.9, stop=['\\n']):\n super().__init__(llm, context_len)\n self.type = \"Zeroshot_Webrun_Agent\"\n self.life_label = time.time()\n self.name = f\"{self.type}_{self.life_label}\"\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def avai_action_prompt(self, available_actions):\n if 'search' in available_actions:\n return \"{search}\"\n elif 'click' in available_actions:\n actions = available_actions['click']\n ac_string = \"\\t\".join(actions)\n return f\"click: [{ac_string}]\"\n \n def prompt_layer(self, available_actions):","source_hash":"8fca5841f4c2d805f5ace23a7168cbfb78d9436776779a88549101ffd96df94d","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.agent_arch.ZeroshotAgent","uri":"program://BOLAA/class/web_run.agent_arch.ZeroshotAgent#L102-L138","kind":"class","name":"ZeroshotAgent","path":"web_run/agent_arch.py","language":"python","start_line":102,"end_line":138,"context_start_line":82,"context_end_line":158,"code":" self.name = f\"{self.type}_{self.life_label}\"\n \n def prompt_layer(self):\n one_shot = pre_prompt.oneshot\n prompt = f\"{one_shot}{self.observations[self.cur_session][0]}\\n\\nAction:\"\n if len(self.actions[self.cur_session]) > 1:\n initial_prompt = f\"{one_shot}{self.observations[self.cur_session][0]}\\n\\n\"\n history = self.get_history()\n remain_context_space = (self.context_len - len(token_enc.encode(initial_prompt)))*3\n history = history[-int(remain_context_space):]\n prompt = f\"{initial_prompt}{history}\\n\\nAction:\"\n return prompt\n \n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n prompt = self.prompt_layer()\n action = self.llm_layer(prompt)\n self.actions[self.cur_session].append(action)\n return action\n \nclass ZeroshotAgent(BaseAgent):\n def __init__(self, llm, context_len=2000, temperature=0.9, stop=['\\n']):\n super().__init__(llm, context_len)\n self.type = \"Zeroshot_Webrun_Agent\"\n self.life_label = time.time()\n self.name = f\"{self.type}_{self.life_label}\"\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def avai_action_prompt(self, available_actions):\n if 'search' in available_actions:\n return \"{search}\"\n elif 'click' in available_actions:\n actions = available_actions['click']\n ac_string = \"\\t\".join(actions)\n return f\"click: [{ac_string}]\"\n \n def prompt_layer(self, available_actions):\n zeroshot = pre_prompt.zeroshot\n actions_prompt = f\"current available action is {self.avai_action_prompt(available_actions)[-3000:]}\"\n prompt = f\"{zeroshot}{self.observations[self.cur_session][0]}{actions_prompt}\\n\\nAction:\"\n if len(self.actions[self.cur_session]) > 1:\n initial_prompt = f\"{zeroshot}{self.observations[self.cur_session][0]}\\n\\n\"\n history = self.get_history()\n remain_context_space = (self.context_len - len(token_enc.encode(f\"{initial_prompt}{actions_prompt}\")))*3\n history = history[-int(remain_context_space):]\n prompt = f\"{initial_prompt}{history}{actions_prompt}\\n\\nAction:\"\n return prompt\n\n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n prompt = self.prompt_layer(available_actions)\n action = self.llm_layer(prompt).lstrip()\n action = self.action_parser(action, available_actions)\n self.actions[self.cur_session].append(action)\n return action\n \nclass ZeroshotThinkAgent(BaseAgent):\n def __init__(self, llm, context_len=2000, temperature=0.9, stop=['\\n']):\n super().__init__(llm, context_len)\n self.type = \"ZeroshotThink_Webrun_Agent\"\n self.life_label = time.time()\n self.name = f\"{self.type}_{self.life_label}\"\n self.temperature = temperature\n self.stop = stop\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def avai_action_prompt(self, available_actions):\n if 'search' in available_actions:\n return \"{search}\"\n elif 'click' in available_actions:\n actions = available_actions['click']\n ac_string = \"\\t\".join(actions)\n return f\"click: [{ac_string}]\"","source_hash":"8fca5841f4c2d805f5ace23a7168cbfb78d9436776779a88549101ffd96df94d","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.agent_arch.ZeroshotThinkAgent","uri":"program://BOLAA/class/web_run.agent_arch.ZeroshotThinkAgent#L140-L178","kind":"class","name":"ZeroshotThinkAgent","path":"web_run/agent_arch.py","language":"python","start_line":140,"end_line":178,"context_start_line":120,"context_end_line":198,"code":" def prompt_layer(self, available_actions):\n zeroshot = pre_prompt.zeroshot\n actions_prompt = f\"current available action is {self.avai_action_prompt(available_actions)[-3000:]}\"\n prompt = f\"{zeroshot}{self.observations[self.cur_session][0]}{actions_prompt}\\n\\nAction:\"\n if len(self.actions[self.cur_session]) > 1:\n initial_prompt = f\"{zeroshot}{self.observations[self.cur_session][0]}\\n\\n\"\n history = self.get_history()\n remain_context_space = (self.context_len - len(token_enc.encode(f\"{initial_prompt}{actions_prompt}\")))*3\n history = history[-int(remain_context_space):]\n prompt = f\"{initial_prompt}{history}{actions_prompt}\\n\\nAction:\"\n return prompt\n\n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n prompt = self.prompt_layer(available_actions)\n action = self.llm_layer(prompt).lstrip()\n action = self.action_parser(action, available_actions)\n self.actions[self.cur_session].append(action)\n return action\n \nclass ZeroshotThinkAgent(BaseAgent):\n def __init__(self, llm, context_len=2000, temperature=0.9, stop=['\\n']):\n super().__init__(llm, context_len)\n self.type = \"ZeroshotThink_Webrun_Agent\"\n self.life_label = time.time()\n self.name = f\"{self.type}_{self.life_label}\"\n self.temperature = temperature\n self.stop = stop\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def avai_action_prompt(self, available_actions):\n if 'search' in available_actions:\n return \"{search}\"\n elif 'click' in available_actions:\n actions = available_actions['click']\n ac_string = \"\\t\".join(actions)\n return f\"click: [{ac_string}]\"\n \n def prompt_layer(self, available_actions):\n zeroshot = pre_prompt.zeroshot_think\n actions_prompt = f\"current available action is {self.avai_action_prompt(available_actions)[-3000:]}\"\n prompt = f\"{zeroshot}{self.observations[self.cur_session][0]}{actions_prompt}\\n\\nAction:\"\n if len(self.actions[self.cur_session]) > 1:\n initial_prompt = f\"{zeroshot}{self.observations[self.cur_session][0]}\\n\\n\"\n history = self.get_history()\n remain_context_space = (self.context_len - len(token_enc.encode(initial_prompt+actions_prompt)))*3\n history = history[-int(remain_context_space):]\n prompt = f\"{initial_prompt}{history}{actions_prompt}\\n\\nAction:\"\n return prompt\n\n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n prompt = self.prompt_layer(available_actions)\n action = self.llm_layer(prompt, temperature=self.temperature, stop=self.stop).lstrip()\n action = self.action_parser(action, available_actions)\n self.actions[self.cur_session].append(action)\n return action\n \nclass PlannerAgent(BaseAgent):\n def __init__(self, llm, context_len=2000, temperature=0.9, stop=['\\n']):\n super().__init__(llm, context_len)\n self.type = \"Planner_Webrun_Agent\"\n self.name = f\"{self.type}_{self.life_label}\"\n self.temperature = temperature\n self.stop = stop\n self.max_plan_token_len = 256\n self.plan = None\n \n def planning(self):\n plan_prompt = f\"{pre_prompt.plan}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan:\"\n self.plan = self.llm(plan_prompt, temperature=self.temperature, stop=[\"\\n\"], \n max_tokens=self.max_plan_token_len)\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n\n def prompt_layer(self, available_actions):","source_hash":"8fca5841f4c2d805f5ace23a7168cbfb78d9436776779a88549101ffd96df94d","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.agent_arch.PlannerAgent","uri":"program://BOLAA/class/web_run.agent_arch.PlannerAgent#L180-L215","kind":"class","name":"PlannerAgent","path":"web_run/agent_arch.py","language":"python","start_line":180,"end_line":215,"context_start_line":160,"context_end_line":235,"code":" def prompt_layer(self, available_actions):\n zeroshot = pre_prompt.zeroshot_think\n actions_prompt = f\"current available action is {self.avai_action_prompt(available_actions)[-3000:]}\"\n prompt = f\"{zeroshot}{self.observations[self.cur_session][0]}{actions_prompt}\\n\\nAction:\"\n if len(self.actions[self.cur_session]) > 1:\n initial_prompt = f\"{zeroshot}{self.observations[self.cur_session][0]}\\n\\n\"\n history = self.get_history()\n remain_context_space = (self.context_len - len(token_enc.encode(initial_prompt+actions_prompt)))*3\n history = history[-int(remain_context_space):]\n prompt = f\"{initial_prompt}{history}{actions_prompt}\\n\\nAction:\"\n return prompt\n\n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n prompt = self.prompt_layer(available_actions)\n action = self.llm_layer(prompt, temperature=self.temperature, stop=self.stop).lstrip()\n action = self.action_parser(action, available_actions)\n self.actions[self.cur_session].append(action)\n return action\n \nclass PlannerAgent(BaseAgent):\n def __init__(self, llm, context_len=2000, temperature=0.9, stop=['\\n']):\n super().__init__(llm, context_len)\n self.type = \"Planner_Webrun_Agent\"\n self.name = f\"{self.type}_{self.life_label}\"\n self.temperature = temperature\n self.stop = stop\n self.max_plan_token_len = 256\n self.plan = None\n \n def planning(self):\n plan_prompt = f\"{pre_prompt.plan}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan:\"\n self.plan = self.llm(plan_prompt, temperature=self.temperature, stop=[\"\\n\"], \n max_tokens=self.max_plan_token_len)\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n\n def prompt_layer(self, available_actions):\n oneshot = pre_prompt.oneshot_plan \n prompt = f\"{oneshot}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan: {self.plan}\\n\\nAction:\"\n if len(self.actions[self.cur_session]) > 1:\n initial_prompt = f\"{oneshot}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan: {self.plan}\\n\\n\"\n history = self.get_history()\n remain_context_space = (self.context_len - len(token_enc.encode(initial_prompt)))*3\n history = history[-remain_context_space:]\n prompt = f\"{initial_prompt}{history}Action:\"\n return prompt\n \n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n prompt = self.prompt_layer(available_actions)\n action = self.llm_layer(prompt).lstrip(' ')\n action = self.action_parser(action, available_actions)\n self.actions[self.cur_session].append(action)\n return action\n\nclass PlannerReactAgent(PlannerAgent):\n def __init__(self, llm, context_len=2000, temperature=0.9, stop=['\\n']):\n super().__init__(llm, context_len, temperature, stop)\n self.type = \"PlannerReact_Webrun_Agent\"\n self.name = f\"{self.type}_{self.life_label}\"\n \n def planning(self):\n plan_prompt = f\"{pre_prompt.plan_react}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan:\"\n self.plan = self.llm(plan_prompt, temperature=self.temperature, stop=[\"\\n\"], \n max_tokens=self.max_plan_token_len)\n \n def prompt_layer(self, available_actions=None):\n oneshot = pre_prompt.oneshot_plan_react \n prompt = f\"{oneshot}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan: {self.plan}\\n\\nAction:\"\n if len(self.actions[self.cur_session]) > 1:\n initial_prompt = f\"{oneshot}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan: {self.plan}\\n\\n\"\n history = self.get_history()\n remain_context_space = (self.context_len - len(token_enc.encode(initial_prompt)))*3\n history = history[-remain_context_space:]","source_hash":"8fca5841f4c2d805f5ace23a7168cbfb78d9436776779a88549101ffd96df94d","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.agent_arch.PlannerReactAgent","uri":"program://BOLAA/class/web_run.agent_arch.PlannerReactAgent#L217-L245","kind":"class","name":"PlannerReactAgent","path":"web_run/agent_arch.py","language":"python","start_line":217,"end_line":245,"context_start_line":197,"context_end_line":245,"code":"\n def prompt_layer(self, available_actions):\n oneshot = pre_prompt.oneshot_plan \n prompt = f\"{oneshot}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan: {self.plan}\\n\\nAction:\"\n if len(self.actions[self.cur_session]) > 1:\n initial_prompt = f\"{oneshot}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan: {self.plan}\\n\\n\"\n history = self.get_history()\n remain_context_space = (self.context_len - len(token_enc.encode(initial_prompt)))*3\n history = history[-remain_context_space:]\n prompt = f\"{initial_prompt}{history}Action:\"\n return prompt\n \n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n prompt = self.prompt_layer(available_actions)\n action = self.llm_layer(prompt).lstrip(' ')\n action = self.action_parser(action, available_actions)\n self.actions[self.cur_session].append(action)\n return action\n\nclass PlannerReactAgent(PlannerAgent):\n def __init__(self, llm, context_len=2000, temperature=0.9, stop=['\\n']):\n super().__init__(llm, context_len, temperature, stop)\n self.type = \"PlannerReact_Webrun_Agent\"\n self.name = f\"{self.type}_{self.life_label}\"\n \n def planning(self):\n plan_prompt = f\"{pre_prompt.plan_react}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan:\"\n self.plan = self.llm(plan_prompt, temperature=self.temperature, stop=[\"\\n\"], \n max_tokens=self.max_plan_token_len)\n \n def prompt_layer(self, available_actions=None):\n oneshot = pre_prompt.oneshot_plan_react \n prompt = f\"{oneshot}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan: {self.plan}\\n\\nAction:\"\n if len(self.actions[self.cur_session]) > 1:\n initial_prompt = f\"{oneshot}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan: {self.plan}\\n\\n\"\n history = self.get_history()\n remain_context_space = (self.context_len - len(token_enc.encode(initial_prompt)))*3\n history = history[-remain_context_space:]\n prompt = f\"{initial_prompt}{history}Action:\"\n return prompt\n \n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n prompt = self.prompt_layer(available_actions)\n action = self.llm_layer(prompt).lstrip(' ')\n action = self.action_parser(action, available_actions)\n self.actions[self.cur_session].append(action)\n return action","source_hash":"8fca5841f4c2d805f5ace23a7168cbfb78d9436776779a88549101ffd96df94d","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.agent_arch.__init__","uri":"program://BOLAA/function/web_run.agent_arch.__init__#L218-L221","kind":"function","name":"__init__","path":"web_run/agent_arch.py","language":"python","start_line":218,"end_line":221,"context_start_line":198,"context_end_line":241,"code":" def prompt_layer(self, available_actions):\n oneshot = pre_prompt.oneshot_plan \n prompt = f\"{oneshot}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan: {self.plan}\\n\\nAction:\"\n if len(self.actions[self.cur_session]) > 1:\n initial_prompt = f\"{oneshot}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan: {self.plan}\\n\\n\"\n history = self.get_history()\n remain_context_space = (self.context_len - len(token_enc.encode(initial_prompt)))*3\n history = history[-remain_context_space:]\n prompt = f\"{initial_prompt}{history}Action:\"\n return prompt\n \n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n prompt = self.prompt_layer(available_actions)\n action = self.llm_layer(prompt).lstrip(' ')\n action = self.action_parser(action, available_actions)\n self.actions[self.cur_session].append(action)\n return action\n\nclass PlannerReactAgent(PlannerAgent):\n def __init__(self, llm, context_len=2000, temperature=0.9, stop=['\\n']):\n super().__init__(llm, context_len, temperature, stop)\n self.type = \"PlannerReact_Webrun_Agent\"\n self.name = f\"{self.type}_{self.life_label}\"\n \n def planning(self):\n plan_prompt = f\"{pre_prompt.plan_react}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan:\"\n self.plan = self.llm(plan_prompt, temperature=self.temperature, stop=[\"\\n\"], \n max_tokens=self.max_plan_token_len)\n \n def prompt_layer(self, available_actions=None):\n oneshot = pre_prompt.oneshot_plan_react \n prompt = f\"{oneshot}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan: {self.plan}\\n\\nAction:\"\n if len(self.actions[self.cur_session]) > 1:\n initial_prompt = f\"{oneshot}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan: {self.plan}\\n\\n\"\n history = self.get_history()\n remain_context_space = (self.context_len - len(token_enc.encode(initial_prompt)))*3\n history = history[-remain_context_space:]\n prompt = f\"{initial_prompt}{history}Action:\"\n return prompt\n \n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n prompt = self.prompt_layer(available_actions)","source_hash":"8fca5841f4c2d805f5ace23a7168cbfb78d9436776779a88549101ffd96df94d","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.agent_arch.new_session","uri":"program://BOLAA/function/web_run.agent_arch.new_session#L32-L37","kind":"function","name":"new_session","path":"web_run/agent_arch.py","language":"python","start_line":32,"end_line":37,"context_start_line":12,"context_end_line":57,"code":"import os\nimport tiktoken\nimport web_run.pre_prompt as pre_prompt\nfrom web_run.utils import get_query\nfrom web_run.llms import token_enc\n\n\nclass BaseAgent(object):\n def __init__(self, llm, context_len=2000):\n self.type = \"Base_Webrun_Agent\"\n self.life_label = time.time()\n self.name = f\"{self.type}_{self.life_label}\"\n self.task = {}\n self.actions = {}\n self.observations = {}\n self.item_recall = {}\n self.llm = llm\n self.context_len = context_len\n self.cur_session = 0\n \n def new_session(self, idx, task):\n self.cur_session = idx\n self.task[idx] = task\n self.actions[idx] = ['reset']\n self.observations[idx] = []\n self.item_recall[idx] = []\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def get_history(self, session=None):\n if not session:\n session = self.cur_session\n history = \"\"\n for idx in range(1, len(self.actions[session])):\n history += f\"Action: {self.actions[session][idx]}\\n\"\n history += f\"Observation: {self.observations[session][idx]}\\n\\n\"\n return history\n \n def save(self, path):\n file_name = os.path.join(path, self.name+'_'+str(self.life_label))\n with open(file_name, 'a') as f:\n f.write(f\"session_idx:{self.cur_session}\\n\")\n history = self.get_history(self.cur_session)\n f.write(history)\n f.write('\\n')","source_hash":"8fca5841f4c2d805f5ace23a7168cbfb78d9436776779a88549101ffd96df94d","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.agent_arch.llm_layer","uri":"program://BOLAA/function/web_run.agent_arch.llm_layer#L195-L196","kind":"function","name":"llm_layer","path":"web_run/agent_arch.py","language":"python","start_line":195,"end_line":196,"context_start_line":175,"context_end_line":216,"code":" action = self.llm_layer(prompt, temperature=self.temperature, stop=self.stop).lstrip()\n action = self.action_parser(action, available_actions)\n self.actions[self.cur_session].append(action)\n return action\n \nclass PlannerAgent(BaseAgent):\n def __init__(self, llm, context_len=2000, temperature=0.9, stop=['\\n']):\n super().__init__(llm, context_len)\n self.type = \"Planner_Webrun_Agent\"\n self.name = f\"{self.type}_{self.life_label}\"\n self.temperature = temperature\n self.stop = stop\n self.max_plan_token_len = 256\n self.plan = None\n \n def planning(self):\n plan_prompt = f\"{pre_prompt.plan}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan:\"\n self.plan = self.llm(plan_prompt, temperature=self.temperature, stop=[\"\\n\"], \n max_tokens=self.max_plan_token_len)\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n\n def prompt_layer(self, available_actions):\n oneshot = pre_prompt.oneshot_plan \n prompt = f\"{oneshot}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan: {self.plan}\\n\\nAction:\"\n if len(self.actions[self.cur_session]) > 1:\n initial_prompt = f\"{oneshot}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan: {self.plan}\\n\\n\"\n history = self.get_history()\n remain_context_space = (self.context_len - len(token_enc.encode(initial_prompt)))*3\n history = history[-remain_context_space:]\n prompt = f\"{initial_prompt}{history}Action:\"\n return prompt\n \n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n prompt = self.prompt_layer(available_actions)\n action = self.llm_layer(prompt).lstrip(' ')\n action = self.action_parser(action, available_actions)\n self.actions[self.cur_session].append(action)\n return action\n","source_hash":"8fca5841f4c2d805f5ace23a7168cbfb78d9436776779a88549101ffd96df94d","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.agent_arch.get_history","uri":"program://BOLAA/function/web_run.agent_arch.get_history#L42-L49","kind":"function","name":"get_history","path":"web_run/agent_arch.py","language":"python","start_line":42,"end_line":49,"context_start_line":22,"context_end_line":69,"code":" self.life_label = time.time()\n self.name = f\"{self.type}_{self.life_label}\"\n self.task = {}\n self.actions = {}\n self.observations = {}\n self.item_recall = {}\n self.llm = llm\n self.context_len = context_len\n self.cur_session = 0\n \n def new_session(self, idx, task):\n self.cur_session = idx\n self.task[idx] = task\n self.actions[idx] = ['reset']\n self.observations[idx] = []\n self.item_recall[idx] = []\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def get_history(self, session=None):\n if not session:\n session = self.cur_session\n history = \"\"\n for idx in range(1, len(self.actions[session])):\n history += f\"Action: {self.actions[session][idx]}\\n\"\n history += f\"Observation: {self.observations[session][idx]}\\n\\n\"\n return history\n \n def save(self, path):\n file_name = os.path.join(path, self.name+'_'+str(self.life_label))\n with open(file_name, 'a') as f:\n f.write(f\"session_idx:{self.cur_session}\\n\")\n history = self.get_history(self.cur_session)\n f.write(history)\n f.write('\\n')\n \n def action_parser(self, text, available_actions):\n nor_text = text.strip().lower()\n if nor_text.startswith('search'):\n query = get_query(nor_text)\n return f\"search[{query}]\"\n if nor_text.startswith('click'):\n if 'click' in available_actions:\n for a in available_actions['click']:\n if a.lower() in nor_text:\n return f\"click[{a}]\"\n return text","source_hash":"8fca5841f4c2d805f5ace23a7168cbfb78d9436776779a88549101ffd96df94d","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.agent_arch.save","uri":"program://BOLAA/function/web_run.agent_arch.save#L51-L57","kind":"function","name":"save","path":"web_run/agent_arch.py","language":"python","start_line":51,"end_line":57,"context_start_line":31,"context_end_line":77,"code":" \n def new_session(self, idx, task):\n self.cur_session = idx\n self.task[idx] = task\n self.actions[idx] = ['reset']\n self.observations[idx] = []\n self.item_recall[idx] = []\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def get_history(self, session=None):\n if not session:\n session = self.cur_session\n history = \"\"\n for idx in range(1, len(self.actions[session])):\n history += f\"Action: {self.actions[session][idx]}\\n\"\n history += f\"Observation: {self.observations[session][idx]}\\n\\n\"\n return history\n \n def save(self, path):\n file_name = os.path.join(path, self.name+'_'+str(self.life_label))\n with open(file_name, 'a') as f:\n f.write(f\"session_idx:{self.cur_session}\\n\")\n history = self.get_history(self.cur_session)\n f.write(history)\n f.write('\\n')\n \n def action_parser(self, text, available_actions):\n nor_text = text.strip().lower()\n if nor_text.startswith('search'):\n query = get_query(nor_text)\n return f\"search[{query}]\"\n if nor_text.startswith('click'):\n if 'click' in available_actions:\n for a in available_actions['click']:\n if a.lower() in nor_text:\n return f\"click[{a}]\"\n return text\n \n def prompt_layer(self):\n raise NotImplementedError\n \n def forward(self, observation, available_actions=None):\n raise NotImplementedError\n\n","source_hash":"8fca5841f4c2d805f5ace23a7168cbfb78d9436776779a88549101ffd96df94d","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.agent_arch.action_parser","uri":"program://BOLAA/function/web_run.agent_arch.action_parser#L59-L69","kind":"function","name":"action_parser","path":"web_run/agent_arch.py","language":"python","start_line":59,"end_line":69,"context_start_line":39,"context_end_line":89,"code":" def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def get_history(self, session=None):\n if not session:\n session = self.cur_session\n history = \"\"\n for idx in range(1, len(self.actions[session])):\n history += f\"Action: {self.actions[session][idx]}\\n\"\n history += f\"Observation: {self.observations[session][idx]}\\n\\n\"\n return history\n \n def save(self, path):\n file_name = os.path.join(path, self.name+'_'+str(self.life_label))\n with open(file_name, 'a') as f:\n f.write(f\"session_idx:{self.cur_session}\\n\")\n history = self.get_history(self.cur_session)\n f.write(history)\n f.write('\\n')\n \n def action_parser(self, text, available_actions):\n nor_text = text.strip().lower()\n if nor_text.startswith('search'):\n query = get_query(nor_text)\n return f\"search[{query}]\"\n if nor_text.startswith('click'):\n if 'click' in available_actions:\n for a in available_actions['click']:\n if a.lower() in nor_text:\n return f\"click[{a}]\"\n return text\n \n def prompt_layer(self):\n raise NotImplementedError\n \n def forward(self, observation, available_actions=None):\n raise NotImplementedError\n\n\nclass ReactAgent(BaseAgent):\n def __init__(self, llm, context_len=2000):\n super().__init__(llm, context_len)\n self.type = \"React_Webrun_Agent\"\n self.name = f\"{self.type}_{self.life_label}\"\n \n def prompt_layer(self):\n one_shot = pre_prompt.oneshot\n prompt = f\"{one_shot}{self.observations[self.cur_session][0]}\\n\\nAction:\"\n if len(self.actions[self.cur_session]) > 1:\n initial_prompt = f\"{one_shot}{self.observations[self.cur_session][0]}\\n\\n\"\n history = self.get_history()","source_hash":"8fca5841f4c2d805f5ace23a7168cbfb78d9436776779a88549101ffd96df94d","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.agent_arch.prompt_layer","uri":"program://BOLAA/function/web_run.agent_arch.prompt_layer#L228-L237","kind":"function","name":"prompt_layer","path":"web_run/agent_arch.py","language":"python","start_line":228,"end_line":237,"context_start_line":208,"context_end_line":245,"code":" \n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n prompt = self.prompt_layer(available_actions)\n action = self.llm_layer(prompt).lstrip(' ')\n action = self.action_parser(action, available_actions)\n self.actions[self.cur_session].append(action)\n return action\n\nclass PlannerReactAgent(PlannerAgent):\n def __init__(self, llm, context_len=2000, temperature=0.9, stop=['\\n']):\n super().__init__(llm, context_len, temperature, stop)\n self.type = \"PlannerReact_Webrun_Agent\"\n self.name = f\"{self.type}_{self.life_label}\"\n \n def planning(self):\n plan_prompt = f\"{pre_prompt.plan_react}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan:\"\n self.plan = self.llm(plan_prompt, temperature=self.temperature, stop=[\"\\n\"], \n max_tokens=self.max_plan_token_len)\n \n def prompt_layer(self, available_actions=None):\n oneshot = pre_prompt.oneshot_plan_react \n prompt = f\"{oneshot}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan: {self.plan}\\n\\nAction:\"\n if len(self.actions[self.cur_session]) > 1:\n initial_prompt = f\"{oneshot}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan: {self.plan}\\n\\n\"\n history = self.get_history()\n remain_context_space = (self.context_len - len(token_enc.encode(initial_prompt)))*3\n history = history[-remain_context_space:]\n prompt = f\"{initial_prompt}{history}Action:\"\n return prompt\n \n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n prompt = self.prompt_layer(available_actions)\n action = self.llm_layer(prompt).lstrip(' ')\n action = self.action_parser(action, available_actions)\n self.actions[self.cur_session].append(action)\n return action","source_hash":"8fca5841f4c2d805f5ace23a7168cbfb78d9436776779a88549101ffd96df94d","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.agent_arch.forward","uri":"program://BOLAA/function/web_run.agent_arch.forward#L239-L245","kind":"function","name":"forward","path":"web_run/agent_arch.py","language":"python","start_line":239,"end_line":245,"context_start_line":219,"context_end_line":245,"code":" super().__init__(llm, context_len, temperature, stop)\n self.type = \"PlannerReact_Webrun_Agent\"\n self.name = f\"{self.type}_{self.life_label}\"\n \n def planning(self):\n plan_prompt = f\"{pre_prompt.plan_react}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan:\"\n self.plan = self.llm(plan_prompt, temperature=self.temperature, stop=[\"\\n\"], \n max_tokens=self.max_plan_token_len)\n \n def prompt_layer(self, available_actions=None):\n oneshot = pre_prompt.oneshot_plan_react \n prompt = f\"{oneshot}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan: {self.plan}\\n\\nAction:\"\n if len(self.actions[self.cur_session]) > 1:\n initial_prompt = f\"{oneshot}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan: {self.plan}\\n\\n\"\n history = self.get_history()\n remain_context_space = (self.context_len - len(token_enc.encode(initial_prompt)))*3\n history = history[-remain_context_space:]\n prompt = f\"{initial_prompt}{history}Action:\"\n return prompt\n \n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n prompt = self.prompt_layer(available_actions)\n action = self.llm_layer(prompt).lstrip(' ')\n action = self.action_parser(action, available_actions)\n self.actions[self.cur_session].append(action)\n return action","source_hash":"8fca5841f4c2d805f5ace23a7168cbfb78d9436776779a88549101ffd96df94d","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.agent_arch.avai_action_prompt","uri":"program://BOLAA/function/web_run.agent_arch.avai_action_prompt#L152-L158","kind":"function","name":"avai_action_prompt","path":"web_run/agent_arch.py","language":"python","start_line":152,"end_line":158,"context_start_line":132,"context_end_line":178,"code":" def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n prompt = self.prompt_layer(available_actions)\n action = self.llm_layer(prompt).lstrip()\n action = self.action_parser(action, available_actions)\n self.actions[self.cur_session].append(action)\n return action\n \nclass ZeroshotThinkAgent(BaseAgent):\n def __init__(self, llm, context_len=2000, temperature=0.9, stop=['\\n']):\n super().__init__(llm, context_len)\n self.type = \"ZeroshotThink_Webrun_Agent\"\n self.life_label = time.time()\n self.name = f\"{self.type}_{self.life_label}\"\n self.temperature = temperature\n self.stop = stop\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def avai_action_prompt(self, available_actions):\n if 'search' in available_actions:\n return \"{search}\"\n elif 'click' in available_actions:\n actions = available_actions['click']\n ac_string = \"\\t\".join(actions)\n return f\"click: [{ac_string}]\"\n \n def prompt_layer(self, available_actions):\n zeroshot = pre_prompt.zeroshot_think\n actions_prompt = f\"current available action is {self.avai_action_prompt(available_actions)[-3000:]}\"\n prompt = f\"{zeroshot}{self.observations[self.cur_session][0]}{actions_prompt}\\n\\nAction:\"\n if len(self.actions[self.cur_session]) > 1:\n initial_prompt = f\"{zeroshot}{self.observations[self.cur_session][0]}\\n\\n\"\n history = self.get_history()\n remain_context_space = (self.context_len - len(token_enc.encode(initial_prompt+actions_prompt)))*3\n history = history[-int(remain_context_space):]\n prompt = f\"{initial_prompt}{history}{actions_prompt}\\n\\nAction:\"\n return prompt\n\n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n prompt = self.prompt_layer(available_actions)\n action = self.llm_layer(prompt, temperature=self.temperature, stop=self.stop).lstrip()\n action = self.action_parser(action, available_actions)\n self.actions[self.cur_session].append(action)\n return action","source_hash":"8fca5841f4c2d805f5ace23a7168cbfb78d9436776779a88549101ffd96df94d","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.agent_arch.planning","uri":"program://BOLAA/function/web_run.agent_arch.planning#L223-L226","kind":"function","name":"planning","path":"web_run/agent_arch.py","language":"python","start_line":223,"end_line":226,"context_start_line":203,"context_end_line":245,"code":" history = self.get_history()\n remain_context_space = (self.context_len - len(token_enc.encode(initial_prompt)))*3\n history = history[-remain_context_space:]\n prompt = f\"{initial_prompt}{history}Action:\"\n return prompt\n \n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n prompt = self.prompt_layer(available_actions)\n action = self.llm_layer(prompt).lstrip(' ')\n action = self.action_parser(action, available_actions)\n self.actions[self.cur_session].append(action)\n return action\n\nclass PlannerReactAgent(PlannerAgent):\n def __init__(self, llm, context_len=2000, temperature=0.9, stop=['\\n']):\n super().__init__(llm, context_len, temperature, stop)\n self.type = \"PlannerReact_Webrun_Agent\"\n self.name = f\"{self.type}_{self.life_label}\"\n \n def planning(self):\n plan_prompt = f\"{pre_prompt.plan_react}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan:\"\n self.plan = self.llm(plan_prompt, temperature=self.temperature, stop=[\"\\n\"], \n max_tokens=self.max_plan_token_len)\n \n def prompt_layer(self, available_actions=None):\n oneshot = pre_prompt.oneshot_plan_react \n prompt = f\"{oneshot}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan: {self.plan}\\n\\nAction:\"\n if len(self.actions[self.cur_session]) > 1:\n initial_prompt = f\"{oneshot}\\n\\nInstruction: {self.task[self.cur_session]}\\nPlan: {self.plan}\\n\\n\"\n history = self.get_history()\n remain_context_space = (self.context_len - len(token_enc.encode(initial_prompt)))*3\n history = history[-remain_context_space:]\n prompt = f\"{initial_prompt}{history}Action:\"\n return prompt\n \n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n prompt = self.prompt_layer(available_actions)\n action = self.llm_layer(prompt).lstrip(' ')\n action = self.action_parser(action, available_actions)\n self.actions[self.cur_session].append(action)\n return action","source_hash":"8fca5841f4c2d805f5ace23a7168cbfb78d9436776779a88549101ffd96df94d","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.web_env","uri":"program://BOLAA/module/web_run.web_env#L1-L178","kind":"module","name":"web_run.web_env","path":"web_run/web_env.py","language":"python","start_line":1,"end_line":178,"context_start_line":1,"context_end_line":178,"code":"import requests\nfrom bs4 import BeautifulSoup\nfrom bs4.element import Comment\n\nWEBSHOP_URL = \"http://127.0.0.1:3000\"\nACTION_TO_TEMPLATE = {\n 'Description': 'description_page.html',\n 'Features': 'features_page.html',\n 'Reviews': 'review_page.html',\n 'Attributes': 'attributes_page.html',\n}\nMAX_PRO_OB = 8 \n\ndef clean_str(p):\n return p.encode().decode(\"unicode-escape\").encode(\"latin1\").decode(\"utf-8\")\n\n\ndef tag_visible(element):\n ignore = {'style', 'script', 'head', 'title', 'meta', '[document]'}\n return (\n element.parent.name not in ignore and not isinstance(element, Comment)\n )\n\ndef webshop_text(session, page_type, query_string='', page_num=1, asin='', options={}, subpage='', **kwargs):\n if page_type == 'init':\n url = (\n f'{WEBSHOP_URL}/{session}'\n )\n if page_type == 'search':\n url = (\n f'{WEBSHOP_URL}/search_results/{session}/'\n f'{query_string}/{page_num}'\n )\n elif page_type == 'item':\n url = (\n f'{WEBSHOP_URL}/item_page/{session}/'\n f'{asin}/{query_string}/{page_num}/{options}'\n )\n elif page_type == 'item_sub':\n url = (\n f'{WEBSHOP_URL}/item_sub_page/{session}/'\n f'{asin}/{query_string}/{page_num}/{subpage}/{options}'\n )\n elif page_type == 'end':\n url = (\n f'{WEBSHOP_URL}/done/{session}/'\n f'{asin}/{options}'\n )\n # print(url)\n html = requests.get(url).text\n html_obj = BeautifulSoup(html, 'html.parser')\n texts = html_obj.findAll(text=True)\n visible_texts = list(filter(tag_visible, texts))\n # visible_texts = [str(text).strip().strip('\\\\n') for text in visible_texts]\n # if page_type == 'end': import pdb; pdb.set_trace()\n if False:\n # For `simple` mode, return just [SEP] separators\n return ' [SEP] '.join(t.strip() for t in visible_texts if t != '\\n')\n else:\n # Otherwise, return an observation with tags mapped to specific, unique separators\n observation = ''\n option_type = ''\n options = {}\n asins = []\n cnt = 0\n prod_cnt = 0\n just_prod = 0\n clickable = []\n for t in visible_texts:\n if t == '\\n': continue\n if t.replace('\\n', '').replace('\\\\n', '').replace(' ', '') == '': continue\n # if t.startswith('Instruction:') and page_type != 'init': continue\n # print(t.parent.name, t)\n if t.parent.name == 'button': # button\n processed_t = f'\\n[{t}] '\n clickable.append(t)\n elif t.parent.name == 'label': # options\n if f\"'{t}'\" in url:\n processed_t = f'[[{t}]]'\n # observation = f'You have clicked {t}.\\n' + observation\n else:\n processed_t = f'[{t}]'\n options[str(t)] = option_type\n # options[option_type] = options.get(option_type, []) + [str(t)]\n elif t.parent.get('class') == [\"product-link\"]: # product asins\n processed_t = f'\\n[{t}] '\n if prod_cnt >= MAX_PRO_OB:\n processed_t = ''\n prod_cnt += 1\n asins.append(str(t))\n just_prod = 0\n else: # regular, unclickable text\n processed_t = '\\n' + str(t) + ' '\n if cnt < 2 and page_type != 'init': processed_t = ''\n if just_prod <= 2 and prod_cnt > MAX_PRO_OB: processed_t = ''\n option_type = str(t)\n cnt += 1\n just_prod += 1\n observation += processed_t\n info = {}\n if options:\n info['option_types'] = options\n if asins:\n info['asins'] = asins\n if 'Your score (min 0.0, max 1.0)' in visible_texts:\n idx = visible_texts.index('Your score (min 0.0, max 1.0)')\n info['reward'] = float(visible_texts[idx + 1])\n observation = 'Your score (min 0.0, max 1.0): ' + (visible_texts[idx + 1])\n clickable.extend(asins)\n # merging option buttons\n clickable.extend(options)\n return clean_str(observation), info, clickable\n\nclass webshopEnv:\n def __init__(self):\n self.sessions = {}\n \n def step(self, session, action):\n done = False\n observation_ = None\n if action == 'reset':\n self.sessions[session] = {'session': session, 'page_type': 'init'}\n elif action.startswith('think['):\n observation = 'OK.'\n elif action.startswith('search['):\n assert self.sessions[session]['page_type'] == 'init'\n query = action[7:-1]\n self.sessions[session] = {'session': session, 'page_type': 'search',\n 'query_string': query, 'page_num': 1}\n elif action.startswith('click['):\n button = action[6:-1]\n if button == 'Buy Now':\n assert self.sessions[session]['page_type'] == 'item'\n self.sessions[session]['page_type'] = 'end'\n done = True\n elif button == 'Back to Search':\n assert self.sessions[session]['page_type'] in ['search', 'item_sub', 'item']\n self.sessions[session] = {'session': session, 'page_type': 'init'}\n elif button == 'Next >':\n assert False # ad hoc page limitation\n assert self.sessions[session]['page_type'] == 'search'\n self.sessions[session]['page_num'] += 1\n elif button == '< Prev':\n assert self.sessions[session]['page_type'] in ['search', 'item_sub', 'item']\n if self.sessions[session]['page_type'] == 'search':\n assert False\n self.sessions[session]['page_num'] -= 1\n elif self.sessions[session]['page_type'] == 'item_sub':\n self.sessions[session]['page_type'] = 'item'\n elif self.sessions[session]['page_type'] == 'item':\n self.sessions[session]['page_type'] = 'search'\n self.sessions[session]['options'] = {}\n elif button in ACTION_TO_TEMPLATE:\n assert self.sessions[session]['page_type'] == 'item'\n self.sessions[session]['page_type'] = 'item_sub'\n self.sessions[session]['subpage'] = button\n else:\n if self.sessions[session]['page_type'] == 'search':\n assert button in self.sessions[session].get('asins', []) # must be asins\n self.sessions[session]['page_type'] = 'item'\n self.sessions[session]['asin'] = button\n elif self.sessions[session]['page_type'] == 'item':\n assert 'option_types' in self.sessions[session]\n assert button in self.sessions[session]['option_types'], (button, self.sessions[session]['option_types']) # must be options\n option_type = self.sessions[session]['option_types'][button]\n if not 'options' in self.sessions[session]:\n self.sessions[session]['options'] = {}\n self.sessions[session]['options'][option_type] = button\n observation_ = f'You have clicked {button}.'\n else:\n assert False\n observation, info, clickable = webshop_text(**self.sessions[session])\n if observation_:\n observation = observation_\n self.sessions[session].update(info)\n reward = info.get('reward', 0.0)\n asins = info.get('asins', [])\n return observation, reward, done, asins, clickable","source_hash":"c39b484c4e3c701814c5dd5fb5f2722e36e78f39b59b5ee4b90ed6b45fb81cbb","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.web_env.clean_str","uri":"program://BOLAA/function/web_run.web_env.clean_str#L14-L15","kind":"function","name":"clean_str","path":"web_run/web_env.py","language":"python","start_line":14,"end_line":15,"context_start_line":1,"context_end_line":35,"code":"import requests\nfrom bs4 import BeautifulSoup\nfrom bs4.element import Comment\n\nWEBSHOP_URL = \"http://127.0.0.1:3000\"\nACTION_TO_TEMPLATE = {\n 'Description': 'description_page.html',\n 'Features': 'features_page.html',\n 'Reviews': 'review_page.html',\n 'Attributes': 'attributes_page.html',\n}\nMAX_PRO_OB = 8 \n\ndef clean_str(p):\n return p.encode().decode(\"unicode-escape\").encode(\"latin1\").decode(\"utf-8\")\n\n\ndef tag_visible(element):\n ignore = {'style', 'script', 'head', 'title', 'meta', '[document]'}\n return (\n element.parent.name not in ignore and not isinstance(element, Comment)\n )\n\ndef webshop_text(session, page_type, query_string='', page_num=1, asin='', options={}, subpage='', **kwargs):\n if page_type == 'init':\n url = (\n f'{WEBSHOP_URL}/{session}'\n )\n if page_type == 'search':\n url = (\n f'{WEBSHOP_URL}/search_results/{session}/'\n f'{query_string}/{page_num}'\n )\n elif page_type == 'item':\n url = (","source_hash":"c39b484c4e3c701814c5dd5fb5f2722e36e78f39b59b5ee4b90ed6b45fb81cbb","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.web_env.tag_visible","uri":"program://BOLAA/function/web_run.web_env.tag_visible#L18-L22","kind":"function","name":"tag_visible","path":"web_run/web_env.py","language":"python","start_line":18,"end_line":22,"context_start_line":1,"context_end_line":42,"code":"import requests\nfrom bs4 import BeautifulSoup\nfrom bs4.element import Comment\n\nWEBSHOP_URL = \"http://127.0.0.1:3000\"\nACTION_TO_TEMPLATE = {\n 'Description': 'description_page.html',\n 'Features': 'features_page.html',\n 'Reviews': 'review_page.html',\n 'Attributes': 'attributes_page.html',\n}\nMAX_PRO_OB = 8 \n\ndef clean_str(p):\n return p.encode().decode(\"unicode-escape\").encode(\"latin1\").decode(\"utf-8\")\n\n\ndef tag_visible(element):\n ignore = {'style', 'script', 'head', 'title', 'meta', '[document]'}\n return (\n element.parent.name not in ignore and not isinstance(element, Comment)\n )\n\ndef webshop_text(session, page_type, query_string='', page_num=1, asin='', options={}, subpage='', **kwargs):\n if page_type == 'init':\n url = (\n f'{WEBSHOP_URL}/{session}'\n )\n if page_type == 'search':\n url = (\n f'{WEBSHOP_URL}/search_results/{session}/'\n f'{query_string}/{page_num}'\n )\n elif page_type == 'item':\n url = (\n f'{WEBSHOP_URL}/item_page/{session}/'\n f'{asin}/{query_string}/{page_num}/{options}'\n )\n elif page_type == 'item_sub':\n url = (\n f'{WEBSHOP_URL}/item_sub_page/{session}/'\n f'{asin}/{query_string}/{page_num}/{subpage}/{options}'","source_hash":"c39b484c4e3c701814c5dd5fb5f2722e36e78f39b59b5ee4b90ed6b45fb81cbb","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.web_env.webshop_text","uri":"program://BOLAA/function/web_run.web_env.webshop_text#L24-L112","kind":"function","name":"webshop_text","path":"web_run/web_env.py","language":"python","start_line":24,"end_line":112,"context_start_line":4,"context_end_line":132,"code":"\nWEBSHOP_URL = \"http://127.0.0.1:3000\"\nACTION_TO_TEMPLATE = {\n 'Description': 'description_page.html',\n 'Features': 'features_page.html',\n 'Reviews': 'review_page.html',\n 'Attributes': 'attributes_page.html',\n}\nMAX_PRO_OB = 8 \n\ndef clean_str(p):\n return p.encode().decode(\"unicode-escape\").encode(\"latin1\").decode(\"utf-8\")\n\n\ndef tag_visible(element):\n ignore = {'style', 'script', 'head', 'title', 'meta', '[document]'}\n return (\n element.parent.name not in ignore and not isinstance(element, Comment)\n )\n\ndef webshop_text(session, page_type, query_string='', page_num=1, asin='', options={}, subpage='', **kwargs):\n if page_type == 'init':\n url = (\n f'{WEBSHOP_URL}/{session}'\n )\n if page_type == 'search':\n url = (\n f'{WEBSHOP_URL}/search_results/{session}/'\n f'{query_string}/{page_num}'\n )\n elif page_type == 'item':\n url = (\n f'{WEBSHOP_URL}/item_page/{session}/'\n f'{asin}/{query_string}/{page_num}/{options}'\n )\n elif page_type == 'item_sub':\n url = (\n f'{WEBSHOP_URL}/item_sub_page/{session}/'\n f'{asin}/{query_string}/{page_num}/{subpage}/{options}'\n )\n elif page_type == 'end':\n url = (\n f'{WEBSHOP_URL}/done/{session}/'\n f'{asin}/{options}'\n )\n # print(url)\n html = requests.get(url).text\n html_obj = BeautifulSoup(html, 'html.parser')\n texts = html_obj.findAll(text=True)\n visible_texts = list(filter(tag_visible, texts))\n # visible_texts = [str(text).strip().strip('\\\\n') for text in visible_texts]\n # if page_type == 'end': import pdb; pdb.set_trace()\n if False:\n # For `simple` mode, return just [SEP] separators\n return ' [SEP] '.join(t.strip() for t in visible_texts if t != '\\n')\n else:\n # Otherwise, return an observation with tags mapped to specific, unique separators\n observation = ''\n option_type = ''\n options = {}\n asins = []\n cnt = 0\n prod_cnt = 0\n just_prod = 0\n clickable = []\n for t in visible_texts:\n if t == '\\n': continue\n if t.replace('\\n', '').replace('\\\\n', '').replace(' ', '') == '': continue\n # if t.startswith('Instruction:') and page_type != 'init': continue\n # print(t.parent.name, t)\n if t.parent.name == 'button': # button\n processed_t = f'\\n[{t}] '\n clickable.append(t)\n elif t.parent.name == 'label': # options\n if f\"'{t}'\" in url:\n processed_t = f'[[{t}]]'\n # observation = f'You have clicked {t}.\\n' + observation\n else:\n processed_t = f'[{t}]'\n options[str(t)] = option_type\n # options[option_type] = options.get(option_type, []) + [str(t)]\n elif t.parent.get('class') == [\"product-link\"]: # product asins\n processed_t = f'\\n[{t}] '\n if prod_cnt >= MAX_PRO_OB:\n processed_t = ''\n prod_cnt += 1\n asins.append(str(t))\n just_prod = 0\n else: # regular, unclickable text\n processed_t = '\\n' + str(t) + ' '\n if cnt < 2 and page_type != 'init': processed_t = ''\n if just_prod <= 2 and prod_cnt > MAX_PRO_OB: processed_t = ''\n option_type = str(t)\n cnt += 1\n just_prod += 1\n observation += processed_t\n info = {}\n if options:\n info['option_types'] = options\n if asins:\n info['asins'] = asins\n if 'Your score (min 0.0, max 1.0)' in visible_texts:\n idx = visible_texts.index('Your score (min 0.0, max 1.0)')\n info['reward'] = float(visible_texts[idx + 1])\n observation = 'Your score (min 0.0, max 1.0): ' + (visible_texts[idx + 1])\n clickable.extend(asins)\n # merging option buttons\n clickable.extend(options)\n return clean_str(observation), info, clickable\n\nclass webshopEnv:\n def __init__(self):\n self.sessions = {}\n \n def step(self, session, action):\n done = False\n observation_ = None\n if action == 'reset':\n self.sessions[session] = {'session': session, 'page_type': 'init'}\n elif action.startswith('think['):\n observation = 'OK.'\n elif action.startswith('search['):\n assert self.sessions[session]['page_type'] == 'init'\n query = action[7:-1]\n self.sessions[session] = {'session': session, 'page_type': 'search',\n 'query_string': query, 'page_num': 1}\n elif action.startswith('click['):\n button = action[6:-1]\n if button == 'Buy Now':","source_hash":"c39b484c4e3c701814c5dd5fb5f2722e36e78f39b59b5ee4b90ed6b45fb81cbb","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.web_env.webshopEnv","uri":"program://BOLAA/class/web_run.web_env.webshopEnv#L114-L178","kind":"class","name":"webshopEnv","path":"web_run/web_env.py","language":"python","start_line":114,"end_line":178,"context_start_line":94,"context_end_line":178,"code":" if cnt < 2 and page_type != 'init': processed_t = ''\n if just_prod <= 2 and prod_cnt > MAX_PRO_OB: processed_t = ''\n option_type = str(t)\n cnt += 1\n just_prod += 1\n observation += processed_t\n info = {}\n if options:\n info['option_types'] = options\n if asins:\n info['asins'] = asins\n if 'Your score (min 0.0, max 1.0)' in visible_texts:\n idx = visible_texts.index('Your score (min 0.0, max 1.0)')\n info['reward'] = float(visible_texts[idx + 1])\n observation = 'Your score (min 0.0, max 1.0): ' + (visible_texts[idx + 1])\n clickable.extend(asins)\n # merging option buttons\n clickable.extend(options)\n return clean_str(observation), info, clickable\n\nclass webshopEnv:\n def __init__(self):\n self.sessions = {}\n \n def step(self, session, action):\n done = False\n observation_ = None\n if action == 'reset':\n self.sessions[session] = {'session': session, 'page_type': 'init'}\n elif action.startswith('think['):\n observation = 'OK.'\n elif action.startswith('search['):\n assert self.sessions[session]['page_type'] == 'init'\n query = action[7:-1]\n self.sessions[session] = {'session': session, 'page_type': 'search',\n 'query_string': query, 'page_num': 1}\n elif action.startswith('click['):\n button = action[6:-1]\n if button == 'Buy Now':\n assert self.sessions[session]['page_type'] == 'item'\n self.sessions[session]['page_type'] = 'end'\n done = True\n elif button == 'Back to Search':\n assert self.sessions[session]['page_type'] in ['search', 'item_sub', 'item']\n self.sessions[session] = {'session': session, 'page_type': 'init'}\n elif button == 'Next >':\n assert False # ad hoc page limitation\n assert self.sessions[session]['page_type'] == 'search'\n self.sessions[session]['page_num'] += 1\n elif button == '< Prev':\n assert self.sessions[session]['page_type'] in ['search', 'item_sub', 'item']\n if self.sessions[session]['page_type'] == 'search':\n assert False\n self.sessions[session]['page_num'] -= 1\n elif self.sessions[session]['page_type'] == 'item_sub':\n self.sessions[session]['page_type'] = 'item'\n elif self.sessions[session]['page_type'] == 'item':\n self.sessions[session]['page_type'] = 'search'\n self.sessions[session]['options'] = {}\n elif button in ACTION_TO_TEMPLATE:\n assert self.sessions[session]['page_type'] == 'item'\n self.sessions[session]['page_type'] = 'item_sub'\n self.sessions[session]['subpage'] = button\n else:\n if self.sessions[session]['page_type'] == 'search':\n assert button in self.sessions[session].get('asins', []) # must be asins\n self.sessions[session]['page_type'] = 'item'\n self.sessions[session]['asin'] = button\n elif self.sessions[session]['page_type'] == 'item':\n assert 'option_types' in self.sessions[session]\n assert button in self.sessions[session]['option_types'], (button, self.sessions[session]['option_types']) # must be options\n option_type = self.sessions[session]['option_types'][button]\n if not 'options' in self.sessions[session]:\n self.sessions[session]['options'] = {}\n self.sessions[session]['options'][option_type] = button\n observation_ = f'You have clicked {button}.'\n else:\n assert False\n observation, info, clickable = webshop_text(**self.sessions[session])\n if observation_:\n observation = observation_\n self.sessions[session].update(info)\n reward = info.get('reward', 0.0)\n asins = info.get('asins', [])\n return observation, reward, done, asins, clickable","source_hash":"c39b484c4e3c701814c5dd5fb5f2722e36e78f39b59b5ee4b90ed6b45fb81cbb","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.web_env.__init__","uri":"program://BOLAA/function/web_run.web_env.__init__#L115-L116","kind":"function","name":"__init__","path":"web_run/web_env.py","language":"python","start_line":115,"end_line":116,"context_start_line":95,"context_end_line":136,"code":" if just_prod <= 2 and prod_cnt > MAX_PRO_OB: processed_t = ''\n option_type = str(t)\n cnt += 1\n just_prod += 1\n observation += processed_t\n info = {}\n if options:\n info['option_types'] = options\n if asins:\n info['asins'] = asins\n if 'Your score (min 0.0, max 1.0)' in visible_texts:\n idx = visible_texts.index('Your score (min 0.0, max 1.0)')\n info['reward'] = float(visible_texts[idx + 1])\n observation = 'Your score (min 0.0, max 1.0): ' + (visible_texts[idx + 1])\n clickable.extend(asins)\n # merging option buttons\n clickable.extend(options)\n return clean_str(observation), info, clickable\n\nclass webshopEnv:\n def __init__(self):\n self.sessions = {}\n \n def step(self, session, action):\n done = False\n observation_ = None\n if action == 'reset':\n self.sessions[session] = {'session': session, 'page_type': 'init'}\n elif action.startswith('think['):\n observation = 'OK.'\n elif action.startswith('search['):\n assert self.sessions[session]['page_type'] == 'init'\n query = action[7:-1]\n self.sessions[session] = {'session': session, 'page_type': 'search',\n 'query_string': query, 'page_num': 1}\n elif action.startswith('click['):\n button = action[6:-1]\n if button == 'Buy Now':\n assert self.sessions[session]['page_type'] == 'item'\n self.sessions[session]['page_type'] = 'end'\n done = True\n elif button == 'Back to Search':","source_hash":"c39b484c4e3c701814c5dd5fb5f2722e36e78f39b59b5ee4b90ed6b45fb81cbb","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.web_env.step","uri":"program://BOLAA/function/web_run.web_env.step#L118-L178","kind":"function","name":"step","path":"web_run/web_env.py","language":"python","start_line":118,"end_line":178,"context_start_line":98,"context_end_line":178,"code":" just_prod += 1\n observation += processed_t\n info = {}\n if options:\n info['option_types'] = options\n if asins:\n info['asins'] = asins\n if 'Your score (min 0.0, max 1.0)' in visible_texts:\n idx = visible_texts.index('Your score (min 0.0, max 1.0)')\n info['reward'] = float(visible_texts[idx + 1])\n observation = 'Your score (min 0.0, max 1.0): ' + (visible_texts[idx + 1])\n clickable.extend(asins)\n # merging option buttons\n clickable.extend(options)\n return clean_str(observation), info, clickable\n\nclass webshopEnv:\n def __init__(self):\n self.sessions = {}\n \n def step(self, session, action):\n done = False\n observation_ = None\n if action == 'reset':\n self.sessions[session] = {'session': session, 'page_type': 'init'}\n elif action.startswith('think['):\n observation = 'OK.'\n elif action.startswith('search['):\n assert self.sessions[session]['page_type'] == 'init'\n query = action[7:-1]\n self.sessions[session] = {'session': session, 'page_type': 'search',\n 'query_string': query, 'page_num': 1}\n elif action.startswith('click['):\n button = action[6:-1]\n if button == 'Buy Now':\n assert self.sessions[session]['page_type'] == 'item'\n self.sessions[session]['page_type'] = 'end'\n done = True\n elif button == 'Back to Search':\n assert self.sessions[session]['page_type'] in ['search', 'item_sub', 'item']\n self.sessions[session] = {'session': session, 'page_type': 'init'}\n elif button == 'Next >':\n assert False # ad hoc page limitation\n assert self.sessions[session]['page_type'] == 'search'\n self.sessions[session]['page_num'] += 1\n elif button == '< Prev':\n assert self.sessions[session]['page_type'] in ['search', 'item_sub', 'item']\n if self.sessions[session]['page_type'] == 'search':\n assert False\n self.sessions[session]['page_num'] -= 1\n elif self.sessions[session]['page_type'] == 'item_sub':\n self.sessions[session]['page_type'] = 'item'\n elif self.sessions[session]['page_type'] == 'item':\n self.sessions[session]['page_type'] = 'search'\n self.sessions[session]['options'] = {}\n elif button in ACTION_TO_TEMPLATE:\n assert self.sessions[session]['page_type'] == 'item'\n self.sessions[session]['page_type'] = 'item_sub'\n self.sessions[session]['subpage'] = button\n else:\n if self.sessions[session]['page_type'] == 'search':\n assert button in self.sessions[session].get('asins', []) # must be asins\n self.sessions[session]['page_type'] = 'item'\n self.sessions[session]['asin'] = button\n elif self.sessions[session]['page_type'] == 'item':\n assert 'option_types' in self.sessions[session]\n assert button in self.sessions[session]['option_types'], (button, self.sessions[session]['option_types']) # must be options\n option_type = self.sessions[session]['option_types'][button]\n if not 'options' in self.sessions[session]:\n self.sessions[session]['options'] = {}\n self.sessions[session]['options'][option_type] = button\n observation_ = f'You have clicked {button}.'\n else:\n assert False\n observation, info, clickable = webshop_text(**self.sessions[session])\n if observation_:\n observation = observation_\n self.sessions[session].update(info)\n reward = info.get('reward', 0.0)\n asins = info.get('asins', [])\n return observation, reward, done, asins, clickable","source_hash":"c39b484c4e3c701814c5dd5fb5f2722e36e78f39b59b5ee4b90ed6b45fb81cbb","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.utils","uri":"program://BOLAA/module/web_run.utils#L1-L78","kind":"module","name":"web_run.utils","path":"web_run/utils.py","language":"python","start_line":1,"end_line":78,"context_start_line":1,"context_end_line":78,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport json \nimport re\n\ndef obser_parser(observation, instruction_text):\n obs = observation.encode().decode(\"unicode-escape\").encode(\"latin1\").decode(\"utf-8\")\n # obs = obs.replace(\"[SEP]\",'|')\n obs = obs.replace(\"[button]\",\"[\")\n obs = obs.replace(\"[button_]\",\"]\")\n if obs.startswith('Instruction:'):\n obs = obs.replace(instruction_text,\"\")\n obs = obs.replace('Instruction:',\"\")\n if obs.startswith('You have clicked'):\n obs = obs.split('\\n')[0]\n obs = obs.lstrip()\n return obs\n\ndef instruction_parser(ins):\n ins = ins.encode().decode(\"unicode-escape\").encode(\"latin1\").decode(\"utf-8\")\n ins = ins[13:].lstrip()\n return ins\n\ndef get_instruction(obs):\n obs = obs.split('\\n')\n for idx, ob in enumerate(obs):\n if \"Instruction:\" in ob:\n return obs[idx+1].strip()\n\ndef get_buttons(obs):\n pattern = r\"\\[(.*?)\\]\"\n matches = re.findall(pattern, obs)\n return matches\n\ndef get_query(search):\n pattern = r\"\\[(.*?)\\]\"\n matches = re.findall(pattern, search)\n if matches:\n return matches[0]\n else:\n return search.replace('search', '')\n\ndef get_actions(obs):\n if \"[Search]\" in obs:\n avai_actions = {'search':[]}\n else:\n avai_actions = {'click':get_buttons(obs)}\n return avai_actions\n\ndef get_env_botton(bottons):\n if \"Search\" in bottons:\n avai_actions = {'search':[]}\n else:\n avai_actions = {'click':bottons}\n return avai_actions\n\ndef session_save(session_idx, actions, observations, retrieved_items, file_path):\n save_dict_list = []\n for idx in range(len(actions)):\n save_dict = {\"step_id\": f\"session_{session_idx}_step_{idx}\", \"action\": actions[idx], \"observation\":observations[idx], \"retrieved_items\": retrieved_items[idx]}\n save_dict_list.append(save_dict)\n # get goal\n goal_file_name = f\"./webshop/user_session_logs/mturk/{session_idx}.jsonl\"\n with open(goal_file_name) as f:\n for line in f:\n page = json.loads(line)\n break\n goal = page[\"goal\"]\n # saving\n save_dict_list = [goal] + save_dict_list\n with open(file_path, 'a') as f:\n json.dump(save_dict_list, f)\n f.write('\\n')","source_hash":"2bc09f067188fefd5df691b231661b58410a43feb62a2b1c5ce244b2bdcbef34","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.utils.obser_parser","uri":"program://BOLAA/function/web_run.utils.obser_parser#L11-L22","kind":"function","name":"obser_parser","path":"web_run/utils.py","language":"python","start_line":11,"end_line":22,"context_start_line":1,"context_end_line":42,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport json \nimport re\n\ndef obser_parser(observation, instruction_text):\n obs = observation.encode().decode(\"unicode-escape\").encode(\"latin1\").decode(\"utf-8\")\n # obs = obs.replace(\"[SEP]\",'|')\n obs = obs.replace(\"[button]\",\"[\")\n obs = obs.replace(\"[button_]\",\"]\")\n if obs.startswith('Instruction:'):\n obs = obs.replace(instruction_text,\"\")\n obs = obs.replace('Instruction:',\"\")\n if obs.startswith('You have clicked'):\n obs = obs.split('\\n')[0]\n obs = obs.lstrip()\n return obs\n\ndef instruction_parser(ins):\n ins = ins.encode().decode(\"unicode-escape\").encode(\"latin1\").decode(\"utf-8\")\n ins = ins[13:].lstrip()\n return ins\n\ndef get_instruction(obs):\n obs = obs.split('\\n')\n for idx, ob in enumerate(obs):\n if \"Instruction:\" in ob:\n return obs[idx+1].strip()\n\ndef get_buttons(obs):\n pattern = r\"\\[(.*?)\\]\"\n matches = re.findall(pattern, obs)\n return matches\n\ndef get_query(search):\n pattern = r\"\\[(.*?)\\]\"\n matches = re.findall(pattern, search)","source_hash":"2bc09f067188fefd5df691b231661b58410a43feb62a2b1c5ce244b2bdcbef34","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.utils.instruction_parser","uri":"program://BOLAA/function/web_run.utils.instruction_parser#L24-L27","kind":"function","name":"instruction_parser","path":"web_run/utils.py","language":"python","start_line":24,"end_line":27,"context_start_line":4,"context_end_line":47,"code":" SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport json \nimport re\n\ndef obser_parser(observation, instruction_text):\n obs = observation.encode().decode(\"unicode-escape\").encode(\"latin1\").decode(\"utf-8\")\n # obs = obs.replace(\"[SEP]\",'|')\n obs = obs.replace(\"[button]\",\"[\")\n obs = obs.replace(\"[button_]\",\"]\")\n if obs.startswith('Instruction:'):\n obs = obs.replace(instruction_text,\"\")\n obs = obs.replace('Instruction:',\"\")\n if obs.startswith('You have clicked'):\n obs = obs.split('\\n')[0]\n obs = obs.lstrip()\n return obs\n\ndef instruction_parser(ins):\n ins = ins.encode().decode(\"unicode-escape\").encode(\"latin1\").decode(\"utf-8\")\n ins = ins[13:].lstrip()\n return ins\n\ndef get_instruction(obs):\n obs = obs.split('\\n')\n for idx, ob in enumerate(obs):\n if \"Instruction:\" in ob:\n return obs[idx+1].strip()\n\ndef get_buttons(obs):\n pattern = r\"\\[(.*?)\\]\"\n matches = re.findall(pattern, obs)\n return matches\n\ndef get_query(search):\n pattern = r\"\\[(.*?)\\]\"\n matches = re.findall(pattern, search)\n if matches:\n return matches[0]\n else:\n return search.replace('search', '')\n","source_hash":"2bc09f067188fefd5df691b231661b58410a43feb62a2b1c5ce244b2bdcbef34","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.utils.get_instruction","uri":"program://BOLAA/function/web_run.utils.get_instruction#L29-L33","kind":"function","name":"get_instruction","path":"web_run/utils.py","language":"python","start_line":29,"end_line":33,"context_start_line":9,"context_end_line":53,"code":"import re\n\ndef obser_parser(observation, instruction_text):\n obs = observation.encode().decode(\"unicode-escape\").encode(\"latin1\").decode(\"utf-8\")\n # obs = obs.replace(\"[SEP]\",'|')\n obs = obs.replace(\"[button]\",\"[\")\n obs = obs.replace(\"[button_]\",\"]\")\n if obs.startswith('Instruction:'):\n obs = obs.replace(instruction_text,\"\")\n obs = obs.replace('Instruction:',\"\")\n if obs.startswith('You have clicked'):\n obs = obs.split('\\n')[0]\n obs = obs.lstrip()\n return obs\n\ndef instruction_parser(ins):\n ins = ins.encode().decode(\"unicode-escape\").encode(\"latin1\").decode(\"utf-8\")\n ins = ins[13:].lstrip()\n return ins\n\ndef get_instruction(obs):\n obs = obs.split('\\n')\n for idx, ob in enumerate(obs):\n if \"Instruction:\" in ob:\n return obs[idx+1].strip()\n\ndef get_buttons(obs):\n pattern = r\"\\[(.*?)\\]\"\n matches = re.findall(pattern, obs)\n return matches\n\ndef get_query(search):\n pattern = r\"\\[(.*?)\\]\"\n matches = re.findall(pattern, search)\n if matches:\n return matches[0]\n else:\n return search.replace('search', '')\n\ndef get_actions(obs):\n if \"[Search]\" in obs:\n avai_actions = {'search':[]}\n else:\n avai_actions = {'click':get_buttons(obs)}\n return avai_actions","source_hash":"2bc09f067188fefd5df691b231661b58410a43feb62a2b1c5ce244b2bdcbef34","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.utils.get_buttons","uri":"program://BOLAA/function/web_run.utils.get_buttons#L35-L38","kind":"function","name":"get_buttons","path":"web_run/utils.py","language":"python","start_line":35,"end_line":38,"context_start_line":15,"context_end_line":58,"code":" obs = obs.replace(\"[button_]\",\"]\")\n if obs.startswith('Instruction:'):\n obs = obs.replace(instruction_text,\"\")\n obs = obs.replace('Instruction:',\"\")\n if obs.startswith('You have clicked'):\n obs = obs.split('\\n')[0]\n obs = obs.lstrip()\n return obs\n\ndef instruction_parser(ins):\n ins = ins.encode().decode(\"unicode-escape\").encode(\"latin1\").decode(\"utf-8\")\n ins = ins[13:].lstrip()\n return ins\n\ndef get_instruction(obs):\n obs = obs.split('\\n')\n for idx, ob in enumerate(obs):\n if \"Instruction:\" in ob:\n return obs[idx+1].strip()\n\ndef get_buttons(obs):\n pattern = r\"\\[(.*?)\\]\"\n matches = re.findall(pattern, obs)\n return matches\n\ndef get_query(search):\n pattern = r\"\\[(.*?)\\]\"\n matches = re.findall(pattern, search)\n if matches:\n return matches[0]\n else:\n return search.replace('search', '')\n\ndef get_actions(obs):\n if \"[Search]\" in obs:\n avai_actions = {'search':[]}\n else:\n avai_actions = {'click':get_buttons(obs)}\n return avai_actions\n\ndef get_env_botton(bottons):\n if \"Search\" in bottons:\n avai_actions = {'search':[]}\n else:","source_hash":"2bc09f067188fefd5df691b231661b58410a43feb62a2b1c5ce244b2bdcbef34","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.utils.get_query","uri":"program://BOLAA/function/web_run.utils.get_query#L40-L46","kind":"function","name":"get_query","path":"web_run/utils.py","language":"python","start_line":40,"end_line":46,"context_start_line":20,"context_end_line":66,"code":" obs = obs.split('\\n')[0]\n obs = obs.lstrip()\n return obs\n\ndef instruction_parser(ins):\n ins = ins.encode().decode(\"unicode-escape\").encode(\"latin1\").decode(\"utf-8\")\n ins = ins[13:].lstrip()\n return ins\n\ndef get_instruction(obs):\n obs = obs.split('\\n')\n for idx, ob in enumerate(obs):\n if \"Instruction:\" in ob:\n return obs[idx+1].strip()\n\ndef get_buttons(obs):\n pattern = r\"\\[(.*?)\\]\"\n matches = re.findall(pattern, obs)\n return matches\n\ndef get_query(search):\n pattern = r\"\\[(.*?)\\]\"\n matches = re.findall(pattern, search)\n if matches:\n return matches[0]\n else:\n return search.replace('search', '')\n\ndef get_actions(obs):\n if \"[Search]\" in obs:\n avai_actions = {'search':[]}\n else:\n avai_actions = {'click':get_buttons(obs)}\n return avai_actions\n\ndef get_env_botton(bottons):\n if \"Search\" in bottons:\n avai_actions = {'search':[]}\n else:\n avai_actions = {'click':bottons}\n return avai_actions\n\ndef session_save(session_idx, actions, observations, retrieved_items, file_path):\n save_dict_list = []\n for idx in range(len(actions)):\n save_dict = {\"step_id\": f\"session_{session_idx}_step_{idx}\", \"action\": actions[idx], \"observation\":observations[idx], \"retrieved_items\": retrieved_items[idx]}\n save_dict_list.append(save_dict)","source_hash":"2bc09f067188fefd5df691b231661b58410a43feb62a2b1c5ce244b2bdcbef34","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.utils.get_actions","uri":"program://BOLAA/function/web_run.utils.get_actions#L48-L53","kind":"function","name":"get_actions","path":"web_run/utils.py","language":"python","start_line":48,"end_line":53,"context_start_line":28,"context_end_line":73,"code":"\ndef get_instruction(obs):\n obs = obs.split('\\n')\n for idx, ob in enumerate(obs):\n if \"Instruction:\" in ob:\n return obs[idx+1].strip()\n\ndef get_buttons(obs):\n pattern = r\"\\[(.*?)\\]\"\n matches = re.findall(pattern, obs)\n return matches\n\ndef get_query(search):\n pattern = r\"\\[(.*?)\\]\"\n matches = re.findall(pattern, search)\n if matches:\n return matches[0]\n else:\n return search.replace('search', '')\n\ndef get_actions(obs):\n if \"[Search]\" in obs:\n avai_actions = {'search':[]}\n else:\n avai_actions = {'click':get_buttons(obs)}\n return avai_actions\n\ndef get_env_botton(bottons):\n if \"Search\" in bottons:\n avai_actions = {'search':[]}\n else:\n avai_actions = {'click':bottons}\n return avai_actions\n\ndef session_save(session_idx, actions, observations, retrieved_items, file_path):\n save_dict_list = []\n for idx in range(len(actions)):\n save_dict = {\"step_id\": f\"session_{session_idx}_step_{idx}\", \"action\": actions[idx], \"observation\":observations[idx], \"retrieved_items\": retrieved_items[idx]}\n save_dict_list.append(save_dict)\n # get goal\n goal_file_name = f\"./webshop/user_session_logs/mturk/{session_idx}.jsonl\"\n with open(goal_file_name) as f:\n for line in f:\n page = json.loads(line)\n break\n goal = page[\"goal\"]","source_hash":"2bc09f067188fefd5df691b231661b58410a43feb62a2b1c5ce244b2bdcbef34","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.utils.get_env_botton","uri":"program://BOLAA/function/web_run.utils.get_env_botton#L55-L60","kind":"function","name":"get_env_botton","path":"web_run/utils.py","language":"python","start_line":55,"end_line":60,"context_start_line":35,"context_end_line":78,"code":"def get_buttons(obs):\n pattern = r\"\\[(.*?)\\]\"\n matches = re.findall(pattern, obs)\n return matches\n\ndef get_query(search):\n pattern = r\"\\[(.*?)\\]\"\n matches = re.findall(pattern, search)\n if matches:\n return matches[0]\n else:\n return search.replace('search', '')\n\ndef get_actions(obs):\n if \"[Search]\" in obs:\n avai_actions = {'search':[]}\n else:\n avai_actions = {'click':get_buttons(obs)}\n return avai_actions\n\ndef get_env_botton(bottons):\n if \"Search\" in bottons:\n avai_actions = {'search':[]}\n else:\n avai_actions = {'click':bottons}\n return avai_actions\n\ndef session_save(session_idx, actions, observations, retrieved_items, file_path):\n save_dict_list = []\n for idx in range(len(actions)):\n save_dict = {\"step_id\": f\"session_{session_idx}_step_{idx}\", \"action\": actions[idx], \"observation\":observations[idx], \"retrieved_items\": retrieved_items[idx]}\n save_dict_list.append(save_dict)\n # get goal\n goal_file_name = f\"./webshop/user_session_logs/mturk/{session_idx}.jsonl\"\n with open(goal_file_name) as f:\n for line in f:\n page = json.loads(line)\n break\n goal = page[\"goal\"]\n # saving\n save_dict_list = [goal] + save_dict_list\n with open(file_path, 'a') as f:\n json.dump(save_dict_list, f)\n f.write('\\n')","source_hash":"2bc09f067188fefd5df691b231661b58410a43feb62a2b1c5ce244b2bdcbef34","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.utils.session_save","uri":"program://BOLAA/function/web_run.utils.session_save#L62-L78","kind":"function","name":"session_save","path":"web_run/utils.py","language":"python","start_line":62,"end_line":78,"context_start_line":42,"context_end_line":78,"code":" matches = re.findall(pattern, search)\n if matches:\n return matches[0]\n else:\n return search.replace('search', '')\n\ndef get_actions(obs):\n if \"[Search]\" in obs:\n avai_actions = {'search':[]}\n else:\n avai_actions = {'click':get_buttons(obs)}\n return avai_actions\n\ndef get_env_botton(bottons):\n if \"Search\" in bottons:\n avai_actions = {'search':[]}\n else:\n avai_actions = {'click':bottons}\n return avai_actions\n\ndef session_save(session_idx, actions, observations, retrieved_items, file_path):\n save_dict_list = []\n for idx in range(len(actions)):\n save_dict = {\"step_id\": f\"session_{session_idx}_step_{idx}\", \"action\": actions[idx], \"observation\":observations[idx], \"retrieved_items\": retrieved_items[idx]}\n save_dict_list.append(save_dict)\n # get goal\n goal_file_name = f\"./webshop/user_session_logs/mturk/{session_idx}.jsonl\"\n with open(goal_file_name) as f:\n for line in f:\n page = json.loads(line)\n break\n goal = page[\"goal\"]\n # saving\n save_dict_list = [goal] + save_dict_list\n with open(file_path, 'a') as f:\n json.dump(save_dict_list, f)\n f.write('\\n')","source_hash":"2bc09f067188fefd5df691b231661b58410a43feb62a2b1c5ce244b2bdcbef34","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.multi_agent_arch","uri":"program://BOLAA/module/web_run.multi_agent_arch#L1-L227","kind":"module","name":"web_run.multi_agent_arch","path":"web_run/multi_agent_arch.py","language":"python","start_line":1,"end_line":227,"context_start_line":1,"context_end_line":227,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport time\nimport os\nimport web_run.pre_prompt as pre_prompt\nfrom web_run.utils import get_query\nfrom web_run.llms import token_enc\n\n\ncontrol_dict = {\"Search_Webrun_Agent\":\"search\",\n \"Think_Webrun_Agent\":\"think\",\n \"Click_Webrun_Agent\":\"click\"}\n \nclass ClickAgent:\n def __init__(self, llm, context_len=2000):\n self.type = \"Click_Webrun_Agent\"\n self.life_label = time.time()\n self.name = f\"{self.type}_{self.life_label}\"\n self.llm = llm \n self.context_len = context_len\n self.task = None\n \n def action_parser(self, text, available_actions):\n nor_text = text.strip().lower()\n if nor_text.startswith('search'):\n query = get_query(nor_text)\n return f\"search[{query}]\"\n if nor_text.startswith('click'):\n if 'click' in available_actions:\n for a in available_actions['click']:\n if a.lower() in nor_text:\n return f\"click[{a}]\"\n return text\n \n def avai_action_prompt(self, available_actions):\n if 'search' in available_actions:\n return \"{search}\"\n elif 'click' in available_actions:\n actions = available_actions['click']\n ac_string = \"\\t\".join(actions)\n return f\"click:[{ac_string}]\"\n \n def prompt_layer(self, control_prompt, available_actions):\n one_shot = pre_prompt.click\n initial = f\"Instruction:\\n{self.task}\"\n actions_prompt = f\"current available action is {self.avai_action_prompt(available_actions)[:3000]}\"\n remain_context_space = (self.context_len - len(token_enc.encode(initial+one_shot+actions_prompt)))*3\n prompt = f\"{one_shot}\\n{initial}\\n{control_prompt[-int(remain_context_space):]}\\n{actions_prompt}\\n\\nAction:\"\n if len(token_enc.encode(prompt)) > self.context_len:\n print(\"this prompt may be over context length requirements:\")\n print(\"---------\\n\")\n print(prompt)\n print(\"\\n---------\")\n return prompt\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def forward(self, control_prompt, available_actions):\n prompt = self.prompt_layer(control_prompt, available_actions)\n action = self.llm_layer(prompt).lstrip(' ')\n action = self.action_parser(action, available_actions)\n return action\n\nclass SearchAgent:\n def __init__(self, llm, context_len=2000):\n self.type = \"Search_Webrun_Agent\"\n self.life_label = time.time()\n self.name = f\"{self.type}_{self.life_label}\"\n self.llm = llm \n self.context_len = context_len\n self.task = None\n \n def action_parser(self, text, available_actions):\n nor_text = text.strip().lower()\n if nor_text.startswith('search'):\n query = get_query(nor_text)\n return f\"search[{query}]\"\n return text\n \n def prompt_layer(self, control_prompt, available_actions):\n one_shot = pre_prompt.search\n remain_context_space = (self.context_len - len(token_enc.encode(one_shot)))*3\n prompt = f\"{one_shot}{control_prompt[-int(remain_context_space):]}\\n\\nAction:\"\n if len(token_enc.encode(prompt)) > self.context_len:\n print(\"this prompt may be over context length requirements:\")\n print(\"---------\\n\")\n print(prompt)\n print(\"\\n---------\")\n return prompt\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def forward(self, control_prompt, available_actions):\n prompt = self.prompt_layer(control_prompt, available_actions)\n action = self.llm_layer(prompt).lstrip(' ')\n action = self.action_parser(action, available_actions)\n return action\n \nclass ThinkAgent:\n def __init__(self, llm, context_len=2000):\n self.type = \"Think_Webrun_Agent\"\n self.name = f\"{self.type}_{self.life_label}\"\n self.llm = llm \n self.context_len = context_len\n self.task = None\n \n def action_parser(self, text):\n nor_text = text.strip().lower()\n if nor_text.startswith('think'):\n query = get_query(nor_text)\n return f\"think[{query}]\"\n return text\n \n def prompt_layer(self, agent, available_actions):\n one_shot = pre_prompt.click\n prompt = f\"{one_shot}{self.observations[self.cur_session][0]}\\n\\nAction:\"\n actions_prompt = f\"current available action is {self.avai_action_prompt(available_actions)}\"\n prompt = f\"\\n\\nAction:\"\n return prompt\n \n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def forward(self, control_prompt, available_actions):\n prompt = self.prompt_layer(control_prompt, available_actions)\n action = self.llm_layer(prompt).lstrip(' ')\n action = self.action_parser(action, available_actions)\n return action\n \nclass ControlAgent:\n def __init__(self, agents):\n self.type = \"Search_Click_Control_Webrun_Agent\"\n self.agents = agents\n self.task = {}\n self.actions = {}\n self.observations = {}\n self.agent_calls = {} # saving the agents types in sessions\n self.item_recall = {}\n self.cur_session = 0\n self.agents = agents\n self.control_dict = control_dict\n \n def new_session(self, idx, task):\n self.cur_session = idx\n self.task[idx] = task\n self.actions[idx] = ['reset']\n self.observations[idx] = []\n self.item_recall[idx] = []\n self.agent_calls[idx] = [\"Search_Click_Controller\"]\n self.task_assign(task)\n \n def task_assign(self, task):\n for agent in self.agents:\n agent.task = task\n\n def action_parser(self, text, available_actions):\n nor_text = text.strip().lower()\n if nor_text.startswith('search'):\n query = get_query(nor_text)\n return f\"search[{query}]\"\n if nor_text.startswith('click'):\n if 'click' in available_actions:\n for a in available_actions['click']:\n if a.lower() in nor_text:\n return f\"click[{a}]\"\n return text\n \n def get_agents_types(self):\n return [a.type for a in self.agents]\n \n def prompt_layer(self, agent, available_actions):\n if agent.type == \"Search_Webrun_Agent\":\n return self.ask_search_agent()\n if agent.type == \"Click_Webrun_Agent\":\n return self.ask_click_agent()\n return 0\n \n def ask_search_agent(self):\n initial = self.task[self.cur_session]\n prompt = f\"Instruction:\\n{initial}\\n\"\n search_label = False\n for idx, agent_type in enumerate(self.agent_calls[self.cur_session]):\n if agent_type == \"Search_Webrun_Agent\":\n search_label = True\n action = self.actions[self.cur_session][idx]\n prompt += f\"You have already {action}.\\n\"\n if search_label:\n prompt += \"Can you change your search query?\"\n return prompt\n \n def ask_click_agent(self):\n prompt = \"\"\n for idx in range(1, len(self.actions[self.cur_session])):\n agent_type = self.agent_calls[self.cur_session][idx]\n action = self.actions[self.cur_session][idx]\n observation = self.observations[self.cur_session][idx]\n if agent_type == \"Click_Webrun_Agent\":\n prompt += f\"\\n\\nAction:{action}\\nObservation:{observation}\"\n else:\n prompt += f\"\\n\\n{agent_type}:{action}\\nObservation:{observation}\"\n return prompt\n \n def call_agent(self, observation, available_actions):\n for agent in self.agents:\n if self.control_dict[agent.type] in available_actions:\n return agent\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n agent = self.call_agent(observation, available_actions)\n prompt = self.prompt_layer(agent, available_actions)\n action = agent.forward(prompt, available_actions).lstrip()\n action = self.action_parser(action, available_actions)\n self.actions[self.cur_session].append(action)\n self.agent_calls[self.cur_session].append(agent.type)\n return action","source_hash":"7b928fb475294d6ea91a0c633556165d1f7fdb0295081748a6fadb3a94184233","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.multi_agent_arch.ClickAgent","uri":"program://BOLAA/class/web_run.multi_agent_arch.ClickAgent#L19-L68","kind":"class","name":"ClickAgent","path":"web_run/multi_agent_arch.py","language":"python","start_line":19,"end_line":68,"context_start_line":1,"context_end_line":88,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport time\nimport os\nimport web_run.pre_prompt as pre_prompt\nfrom web_run.utils import get_query\nfrom web_run.llms import token_enc\n\n\ncontrol_dict = {\"Search_Webrun_Agent\":\"search\",\n \"Think_Webrun_Agent\":\"think\",\n \"Click_Webrun_Agent\":\"click\"}\n \nclass ClickAgent:\n def __init__(self, llm, context_len=2000):\n self.type = \"Click_Webrun_Agent\"\n self.life_label = time.time()\n self.name = f\"{self.type}_{self.life_label}\"\n self.llm = llm \n self.context_len = context_len\n self.task = None\n \n def action_parser(self, text, available_actions):\n nor_text = text.strip().lower()\n if nor_text.startswith('search'):\n query = get_query(nor_text)\n return f\"search[{query}]\"\n if nor_text.startswith('click'):\n if 'click' in available_actions:\n for a in available_actions['click']:\n if a.lower() in nor_text:\n return f\"click[{a}]\"\n return text\n \n def avai_action_prompt(self, available_actions):\n if 'search' in available_actions:\n return \"{search}\"\n elif 'click' in available_actions:\n actions = available_actions['click']\n ac_string = \"\\t\".join(actions)\n return f\"click:[{ac_string}]\"\n \n def prompt_layer(self, control_prompt, available_actions):\n one_shot = pre_prompt.click\n initial = f\"Instruction:\\n{self.task}\"\n actions_prompt = f\"current available action is {self.avai_action_prompt(available_actions)[:3000]}\"\n remain_context_space = (self.context_len - len(token_enc.encode(initial+one_shot+actions_prompt)))*3\n prompt = f\"{one_shot}\\n{initial}\\n{control_prompt[-int(remain_context_space):]}\\n{actions_prompt}\\n\\nAction:\"\n if len(token_enc.encode(prompt)) > self.context_len:\n print(\"this prompt may be over context length requirements:\")\n print(\"---------\\n\")\n print(prompt)\n print(\"\\n---------\")\n return prompt\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def forward(self, control_prompt, available_actions):\n prompt = self.prompt_layer(control_prompt, available_actions)\n action = self.llm_layer(prompt).lstrip(' ')\n action = self.action_parser(action, available_actions)\n return action\n\nclass SearchAgent:\n def __init__(self, llm, context_len=2000):\n self.type = \"Search_Webrun_Agent\"\n self.life_label = time.time()\n self.name = f\"{self.type}_{self.life_label}\"\n self.llm = llm \n self.context_len = context_len\n self.task = None\n \n def action_parser(self, text, available_actions):\n nor_text = text.strip().lower()\n if nor_text.startswith('search'):\n query = get_query(nor_text)\n return f\"search[{query}]\"\n return text\n \n def prompt_layer(self, control_prompt, available_actions):\n one_shot = pre_prompt.search\n remain_context_space = (self.context_len - len(token_enc.encode(one_shot)))*3","source_hash":"7b928fb475294d6ea91a0c633556165d1f7fdb0295081748a6fadb3a94184233","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.multi_agent_arch.SearchAgent","uri":"program://BOLAA/class/web_run.multi_agent_arch.SearchAgent#L70-L104","kind":"class","name":"SearchAgent","path":"web_run/multi_agent_arch.py","language":"python","start_line":70,"end_line":104,"context_start_line":50,"context_end_line":124,"code":" initial = f\"Instruction:\\n{self.task}\"\n actions_prompt = f\"current available action is {self.avai_action_prompt(available_actions)[:3000]}\"\n remain_context_space = (self.context_len - len(token_enc.encode(initial+one_shot+actions_prompt)))*3\n prompt = f\"{one_shot}\\n{initial}\\n{control_prompt[-int(remain_context_space):]}\\n{actions_prompt}\\n\\nAction:\"\n if len(token_enc.encode(prompt)) > self.context_len:\n print(\"this prompt may be over context length requirements:\")\n print(\"---------\\n\")\n print(prompt)\n print(\"\\n---------\")\n return prompt\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def forward(self, control_prompt, available_actions):\n prompt = self.prompt_layer(control_prompt, available_actions)\n action = self.llm_layer(prompt).lstrip(' ')\n action = self.action_parser(action, available_actions)\n return action\n\nclass SearchAgent:\n def __init__(self, llm, context_len=2000):\n self.type = \"Search_Webrun_Agent\"\n self.life_label = time.time()\n self.name = f\"{self.type}_{self.life_label}\"\n self.llm = llm \n self.context_len = context_len\n self.task = None\n \n def action_parser(self, text, available_actions):\n nor_text = text.strip().lower()\n if nor_text.startswith('search'):\n query = get_query(nor_text)\n return f\"search[{query}]\"\n return text\n \n def prompt_layer(self, control_prompt, available_actions):\n one_shot = pre_prompt.search\n remain_context_space = (self.context_len - len(token_enc.encode(one_shot)))*3\n prompt = f\"{one_shot}{control_prompt[-int(remain_context_space):]}\\n\\nAction:\"\n if len(token_enc.encode(prompt)) > self.context_len:\n print(\"this prompt may be over context length requirements:\")\n print(\"---------\\n\")\n print(prompt)\n print(\"\\n---------\")\n return prompt\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def forward(self, control_prompt, available_actions):\n prompt = self.prompt_layer(control_prompt, available_actions)\n action = self.llm_layer(prompt).lstrip(' ')\n action = self.action_parser(action, available_actions)\n return action\n \nclass ThinkAgent:\n def __init__(self, llm, context_len=2000):\n self.type = \"Think_Webrun_Agent\"\n self.name = f\"{self.type}_{self.life_label}\"\n self.llm = llm \n self.context_len = context_len\n self.task = None\n \n def action_parser(self, text):\n nor_text = text.strip().lower()\n if nor_text.startswith('think'):\n query = get_query(nor_text)\n return f\"think[{query}]\"\n return text\n \n def prompt_layer(self, agent, available_actions):\n one_shot = pre_prompt.click\n prompt = f\"{one_shot}{self.observations[self.cur_session][0]}\\n\\nAction:\"\n actions_prompt = f\"current available action is {self.avai_action_prompt(available_actions)}\"","source_hash":"7b928fb475294d6ea91a0c633556165d1f7fdb0295081748a6fadb3a94184233","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.multi_agent_arch.ThinkAgent","uri":"program://BOLAA/class/web_run.multi_agent_arch.ThinkAgent#L106-L136","kind":"class","name":"ThinkAgent","path":"web_run/multi_agent_arch.py","language":"python","start_line":106,"end_line":136,"context_start_line":86,"context_end_line":156,"code":" def prompt_layer(self, control_prompt, available_actions):\n one_shot = pre_prompt.search\n remain_context_space = (self.context_len - len(token_enc.encode(one_shot)))*3\n prompt = f\"{one_shot}{control_prompt[-int(remain_context_space):]}\\n\\nAction:\"\n if len(token_enc.encode(prompt)) > self.context_len:\n print(\"this prompt may be over context length requirements:\")\n print(\"---------\\n\")\n print(prompt)\n print(\"\\n---------\")\n return prompt\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def forward(self, control_prompt, available_actions):\n prompt = self.prompt_layer(control_prompt, available_actions)\n action = self.llm_layer(prompt).lstrip(' ')\n action = self.action_parser(action, available_actions)\n return action\n \nclass ThinkAgent:\n def __init__(self, llm, context_len=2000):\n self.type = \"Think_Webrun_Agent\"\n self.name = f\"{self.type}_{self.life_label}\"\n self.llm = llm \n self.context_len = context_len\n self.task = None\n \n def action_parser(self, text):\n nor_text = text.strip().lower()\n if nor_text.startswith('think'):\n query = get_query(nor_text)\n return f\"think[{query}]\"\n return text\n \n def prompt_layer(self, agent, available_actions):\n one_shot = pre_prompt.click\n prompt = f\"{one_shot}{self.observations[self.cur_session][0]}\\n\\nAction:\"\n actions_prompt = f\"current available action is {self.avai_action_prompt(available_actions)}\"\n prompt = f\"\\n\\nAction:\"\n return prompt\n \n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def forward(self, control_prompt, available_actions):\n prompt = self.prompt_layer(control_prompt, available_actions)\n action = self.llm_layer(prompt).lstrip(' ')\n action = self.action_parser(action, available_actions)\n return action\n \nclass ControlAgent:\n def __init__(self, agents):\n self.type = \"Search_Click_Control_Webrun_Agent\"\n self.agents = agents\n self.task = {}\n self.actions = {}\n self.observations = {}\n self.agent_calls = {} # saving the agents types in sessions\n self.item_recall = {}\n self.cur_session = 0\n self.agents = agents\n self.control_dict = control_dict\n \n def new_session(self, idx, task):\n self.cur_session = idx\n self.task[idx] = task\n self.actions[idx] = ['reset']\n self.observations[idx] = []\n self.item_recall[idx] = []","source_hash":"7b928fb475294d6ea91a0c633556165d1f7fdb0295081748a6fadb3a94184233","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.multi_agent_arch.ControlAgent","uri":"program://BOLAA/class/web_run.multi_agent_arch.ControlAgent#L138-L227","kind":"class","name":"ControlAgent","path":"web_run/multi_agent_arch.py","language":"python","start_line":138,"end_line":227,"context_start_line":118,"context_end_line":227,"code":" return f\"think[{query}]\"\n return text\n \n def prompt_layer(self, agent, available_actions):\n one_shot = pre_prompt.click\n prompt = f\"{one_shot}{self.observations[self.cur_session][0]}\\n\\nAction:\"\n actions_prompt = f\"current available action is {self.avai_action_prompt(available_actions)}\"\n prompt = f\"\\n\\nAction:\"\n return prompt\n \n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def forward(self, control_prompt, available_actions):\n prompt = self.prompt_layer(control_prompt, available_actions)\n action = self.llm_layer(prompt).lstrip(' ')\n action = self.action_parser(action, available_actions)\n return action\n \nclass ControlAgent:\n def __init__(self, agents):\n self.type = \"Search_Click_Control_Webrun_Agent\"\n self.agents = agents\n self.task = {}\n self.actions = {}\n self.observations = {}\n self.agent_calls = {} # saving the agents types in sessions\n self.item_recall = {}\n self.cur_session = 0\n self.agents = agents\n self.control_dict = control_dict\n \n def new_session(self, idx, task):\n self.cur_session = idx\n self.task[idx] = task\n self.actions[idx] = ['reset']\n self.observations[idx] = []\n self.item_recall[idx] = []\n self.agent_calls[idx] = [\"Search_Click_Controller\"]\n self.task_assign(task)\n \n def task_assign(self, task):\n for agent in self.agents:\n agent.task = task\n\n def action_parser(self, text, available_actions):\n nor_text = text.strip().lower()\n if nor_text.startswith('search'):\n query = get_query(nor_text)\n return f\"search[{query}]\"\n if nor_text.startswith('click'):\n if 'click' in available_actions:\n for a in available_actions['click']:\n if a.lower() in nor_text:\n return f\"click[{a}]\"\n return text\n \n def get_agents_types(self):\n return [a.type for a in self.agents]\n \n def prompt_layer(self, agent, available_actions):\n if agent.type == \"Search_Webrun_Agent\":\n return self.ask_search_agent()\n if agent.type == \"Click_Webrun_Agent\":\n return self.ask_click_agent()\n return 0\n \n def ask_search_agent(self):\n initial = self.task[self.cur_session]\n prompt = f\"Instruction:\\n{initial}\\n\"\n search_label = False\n for idx, agent_type in enumerate(self.agent_calls[self.cur_session]):\n if agent_type == \"Search_Webrun_Agent\":\n search_label = True\n action = self.actions[self.cur_session][idx]\n prompt += f\"You have already {action}.\\n\"\n if search_label:\n prompt += \"Can you change your search query?\"\n return prompt\n \n def ask_click_agent(self):\n prompt = \"\"\n for idx in range(1, len(self.actions[self.cur_session])):\n agent_type = self.agent_calls[self.cur_session][idx]\n action = self.actions[self.cur_session][idx]\n observation = self.observations[self.cur_session][idx]\n if agent_type == \"Click_Webrun_Agent\":\n prompt += f\"\\n\\nAction:{action}\\nObservation:{observation}\"\n else:\n prompt += f\"\\n\\n{agent_type}:{action}\\nObservation:{observation}\"\n return prompt\n \n def call_agent(self, observation, available_actions):\n for agent in self.agents:\n if self.control_dict[agent.type] in available_actions:\n return agent\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n agent = self.call_agent(observation, available_actions)\n prompt = self.prompt_layer(agent, available_actions)\n action = agent.forward(prompt, available_actions).lstrip()\n action = self.action_parser(action, available_actions)\n self.actions[self.cur_session].append(action)\n self.agent_calls[self.cur_session].append(agent.type)\n return action","source_hash":"7b928fb475294d6ea91a0c633556165d1f7fdb0295081748a6fadb3a94184233","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.multi_agent_arch.__init__","uri":"program://BOLAA/function/web_run.multi_agent_arch.__init__#L139-L149","kind":"function","name":"__init__","path":"web_run/multi_agent_arch.py","language":"python","start_line":139,"end_line":149,"context_start_line":119,"context_end_line":169,"code":" return text\n \n def prompt_layer(self, agent, available_actions):\n one_shot = pre_prompt.click\n prompt = f\"{one_shot}{self.observations[self.cur_session][0]}\\n\\nAction:\"\n actions_prompt = f\"current available action is {self.avai_action_prompt(available_actions)}\"\n prompt = f\"\\n\\nAction:\"\n return prompt\n \n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def forward(self, control_prompt, available_actions):\n prompt = self.prompt_layer(control_prompt, available_actions)\n action = self.llm_layer(prompt).lstrip(' ')\n action = self.action_parser(action, available_actions)\n return action\n \nclass ControlAgent:\n def __init__(self, agents):\n self.type = \"Search_Click_Control_Webrun_Agent\"\n self.agents = agents\n self.task = {}\n self.actions = {}\n self.observations = {}\n self.agent_calls = {} # saving the agents types in sessions\n self.item_recall = {}\n self.cur_session = 0\n self.agents = agents\n self.control_dict = control_dict\n \n def new_session(self, idx, task):\n self.cur_session = idx\n self.task[idx] = task\n self.actions[idx] = ['reset']\n self.observations[idx] = []\n self.item_recall[idx] = []\n self.agent_calls[idx] = [\"Search_Click_Controller\"]\n self.task_assign(task)\n \n def task_assign(self, task):\n for agent in self.agents:\n agent.task = task\n\n def action_parser(self, text, available_actions):\n nor_text = text.strip().lower()\n if nor_text.startswith('search'):\n query = get_query(nor_text)\n return f\"search[{query}]\"\n if nor_text.startswith('click'):","source_hash":"7b928fb475294d6ea91a0c633556165d1f7fdb0295081748a6fadb3a94184233","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.multi_agent_arch.action_parser","uri":"program://BOLAA/function/web_run.multi_agent_arch.action_parser#L164-L174","kind":"function","name":"action_parser","path":"web_run/multi_agent_arch.py","language":"python","start_line":164,"end_line":174,"context_start_line":144,"context_end_line":194,"code":" self.observations = {}\n self.agent_calls = {} # saving the agents types in sessions\n self.item_recall = {}\n self.cur_session = 0\n self.agents = agents\n self.control_dict = control_dict\n \n def new_session(self, idx, task):\n self.cur_session = idx\n self.task[idx] = task\n self.actions[idx] = ['reset']\n self.observations[idx] = []\n self.item_recall[idx] = []\n self.agent_calls[idx] = [\"Search_Click_Controller\"]\n self.task_assign(task)\n \n def task_assign(self, task):\n for agent in self.agents:\n agent.task = task\n\n def action_parser(self, text, available_actions):\n nor_text = text.strip().lower()\n if nor_text.startswith('search'):\n query = get_query(nor_text)\n return f\"search[{query}]\"\n if nor_text.startswith('click'):\n if 'click' in available_actions:\n for a in available_actions['click']:\n if a.lower() in nor_text:\n return f\"click[{a}]\"\n return text\n \n def get_agents_types(self):\n return [a.type for a in self.agents]\n \n def prompt_layer(self, agent, available_actions):\n if agent.type == \"Search_Webrun_Agent\":\n return self.ask_search_agent()\n if agent.type == \"Click_Webrun_Agent\":\n return self.ask_click_agent()\n return 0\n \n def ask_search_agent(self):\n initial = self.task[self.cur_session]\n prompt = f\"Instruction:\\n{initial}\\n\"\n search_label = False\n for idx, agent_type in enumerate(self.agent_calls[self.cur_session]):\n if agent_type == \"Search_Webrun_Agent\":\n search_label = True\n action = self.actions[self.cur_session][idx]\n prompt += f\"You have already {action}.\\n\"","source_hash":"7b928fb475294d6ea91a0c633556165d1f7fdb0295081748a6fadb3a94184233","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.multi_agent_arch.avai_action_prompt","uri":"program://BOLAA/function/web_run.multi_agent_arch.avai_action_prompt#L40-L46","kind":"function","name":"avai_action_prompt","path":"web_run/multi_agent_arch.py","language":"python","start_line":40,"end_line":46,"context_start_line":20,"context_end_line":66,"code":" def __init__(self, llm, context_len=2000):\n self.type = \"Click_Webrun_Agent\"\n self.life_label = time.time()\n self.name = f\"{self.type}_{self.life_label}\"\n self.llm = llm \n self.context_len = context_len\n self.task = None\n \n def action_parser(self, text, available_actions):\n nor_text = text.strip().lower()\n if nor_text.startswith('search'):\n query = get_query(nor_text)\n return f\"search[{query}]\"\n if nor_text.startswith('click'):\n if 'click' in available_actions:\n for a in available_actions['click']:\n if a.lower() in nor_text:\n return f\"click[{a}]\"\n return text\n \n def avai_action_prompt(self, available_actions):\n if 'search' in available_actions:\n return \"{search}\"\n elif 'click' in available_actions:\n actions = available_actions['click']\n ac_string = \"\\t\".join(actions)\n return f\"click:[{ac_string}]\"\n \n def prompt_layer(self, control_prompt, available_actions):\n one_shot = pre_prompt.click\n initial = f\"Instruction:\\n{self.task}\"\n actions_prompt = f\"current available action is {self.avai_action_prompt(available_actions)[:3000]}\"\n remain_context_space = (self.context_len - len(token_enc.encode(initial+one_shot+actions_prompt)))*3\n prompt = f\"{one_shot}\\n{initial}\\n{control_prompt[-int(remain_context_space):]}\\n{actions_prompt}\\n\\nAction:\"\n if len(token_enc.encode(prompt)) > self.context_len:\n print(\"this prompt may be over context length requirements:\")\n print(\"---------\\n\")\n print(prompt)\n print(\"\\n---------\")\n return prompt\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def forward(self, control_prompt, available_actions):\n prompt = self.prompt_layer(control_prompt, available_actions)\n action = self.llm_layer(prompt).lstrip(' ')","source_hash":"7b928fb475294d6ea91a0c633556165d1f7fdb0295081748a6fadb3a94184233","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.multi_agent_arch.prompt_layer","uri":"program://BOLAA/function/web_run.multi_agent_arch.prompt_layer#L179-L184","kind":"function","name":"prompt_layer","path":"web_run/multi_agent_arch.py","language":"python","start_line":179,"end_line":184,"context_start_line":159,"context_end_line":204,"code":" \n def task_assign(self, task):\n for agent in self.agents:\n agent.task = task\n\n def action_parser(self, text, available_actions):\n nor_text = text.strip().lower()\n if nor_text.startswith('search'):\n query = get_query(nor_text)\n return f\"search[{query}]\"\n if nor_text.startswith('click'):\n if 'click' in available_actions:\n for a in available_actions['click']:\n if a.lower() in nor_text:\n return f\"click[{a}]\"\n return text\n \n def get_agents_types(self):\n return [a.type for a in self.agents]\n \n def prompt_layer(self, agent, available_actions):\n if agent.type == \"Search_Webrun_Agent\":\n return self.ask_search_agent()\n if agent.type == \"Click_Webrun_Agent\":\n return self.ask_click_agent()\n return 0\n \n def ask_search_agent(self):\n initial = self.task[self.cur_session]\n prompt = f\"Instruction:\\n{initial}\\n\"\n search_label = False\n for idx, agent_type in enumerate(self.agent_calls[self.cur_session]):\n if agent_type == \"Search_Webrun_Agent\":\n search_label = True\n action = self.actions[self.cur_session][idx]\n prompt += f\"You have already {action}.\\n\"\n if search_label:\n prompt += \"Can you change your search query?\"\n return prompt\n \n def ask_click_agent(self):\n prompt = \"\"\n for idx in range(1, len(self.actions[self.cur_session])):\n agent_type = self.agent_calls[self.cur_session][idx]\n action = self.actions[self.cur_session][idx]\n observation = self.observations[self.cur_session][idx]","source_hash":"7b928fb475294d6ea91a0c633556165d1f7fdb0295081748a6fadb3a94184233","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.multi_agent_arch.llm_layer","uri":"program://BOLAA/function/web_run.multi_agent_arch.llm_layer#L216-L217","kind":"function","name":"llm_layer","path":"web_run/multi_agent_arch.py","language":"python","start_line":216,"end_line":217,"context_start_line":196,"context_end_line":227,"code":" prompt += \"Can you change your search query?\"\n return prompt\n \n def ask_click_agent(self):\n prompt = \"\"\n for idx in range(1, len(self.actions[self.cur_session])):\n agent_type = self.agent_calls[self.cur_session][idx]\n action = self.actions[self.cur_session][idx]\n observation = self.observations[self.cur_session][idx]\n if agent_type == \"Click_Webrun_Agent\":\n prompt += f\"\\n\\nAction:{action}\\nObservation:{observation}\"\n else:\n prompt += f\"\\n\\n{agent_type}:{action}\\nObservation:{observation}\"\n return prompt\n \n def call_agent(self, observation, available_actions):\n for agent in self.agents:\n if self.control_dict[agent.type] in available_actions:\n return agent\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n agent = self.call_agent(observation, available_actions)\n prompt = self.prompt_layer(agent, available_actions)\n action = agent.forward(prompt, available_actions).lstrip()\n action = self.action_parser(action, available_actions)\n self.actions[self.cur_session].append(action)\n self.agent_calls[self.cur_session].append(agent.type)\n return action","source_hash":"7b928fb475294d6ea91a0c633556165d1f7fdb0295081748a6fadb3a94184233","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.multi_agent_arch.forward","uri":"program://BOLAA/function/web_run.multi_agent_arch.forward#L219-L227","kind":"function","name":"forward","path":"web_run/multi_agent_arch.py","language":"python","start_line":219,"end_line":227,"context_start_line":199,"context_end_line":227,"code":" def ask_click_agent(self):\n prompt = \"\"\n for idx in range(1, len(self.actions[self.cur_session])):\n agent_type = self.agent_calls[self.cur_session][idx]\n action = self.actions[self.cur_session][idx]\n observation = self.observations[self.cur_session][idx]\n if agent_type == \"Click_Webrun_Agent\":\n prompt += f\"\\n\\nAction:{action}\\nObservation:{observation}\"\n else:\n prompt += f\"\\n\\n{agent_type}:{action}\\nObservation:{observation}\"\n return prompt\n \n def call_agent(self, observation, available_actions):\n for agent in self.agents:\n if self.control_dict[agent.type] in available_actions:\n return agent\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n agent = self.call_agent(observation, available_actions)\n prompt = self.prompt_layer(agent, available_actions)\n action = agent.forward(prompt, available_actions).lstrip()\n action = self.action_parser(action, available_actions)\n self.actions[self.cur_session].append(action)\n self.agent_calls[self.cur_session].append(agent.type)\n return action","source_hash":"7b928fb475294d6ea91a0c633556165d1f7fdb0295081748a6fadb3a94184233","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.multi_agent_arch.new_session","uri":"program://BOLAA/function/web_run.multi_agent_arch.new_session#L151-L158","kind":"function","name":"new_session","path":"web_run/multi_agent_arch.py","language":"python","start_line":151,"end_line":158,"context_start_line":131,"context_end_line":178,"code":" \n def forward(self, control_prompt, available_actions):\n prompt = self.prompt_layer(control_prompt, available_actions)\n action = self.llm_layer(prompt).lstrip(' ')\n action = self.action_parser(action, available_actions)\n return action\n \nclass ControlAgent:\n def __init__(self, agents):\n self.type = \"Search_Click_Control_Webrun_Agent\"\n self.agents = agents\n self.task = {}\n self.actions = {}\n self.observations = {}\n self.agent_calls = {} # saving the agents types in sessions\n self.item_recall = {}\n self.cur_session = 0\n self.agents = agents\n self.control_dict = control_dict\n \n def new_session(self, idx, task):\n self.cur_session = idx\n self.task[idx] = task\n self.actions[idx] = ['reset']\n self.observations[idx] = []\n self.item_recall[idx] = []\n self.agent_calls[idx] = [\"Search_Click_Controller\"]\n self.task_assign(task)\n \n def task_assign(self, task):\n for agent in self.agents:\n agent.task = task\n\n def action_parser(self, text, available_actions):\n nor_text = text.strip().lower()\n if nor_text.startswith('search'):\n query = get_query(nor_text)\n return f\"search[{query}]\"\n if nor_text.startswith('click'):\n if 'click' in available_actions:\n for a in available_actions['click']:\n if a.lower() in nor_text:\n return f\"click[{a}]\"\n return text\n \n def get_agents_types(self):\n return [a.type for a in self.agents]\n ","source_hash":"7b928fb475294d6ea91a0c633556165d1f7fdb0295081748a6fadb3a94184233","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.multi_agent_arch.task_assign","uri":"program://BOLAA/function/web_run.multi_agent_arch.task_assign#L160-L162","kind":"function","name":"task_assign","path":"web_run/multi_agent_arch.py","language":"python","start_line":160,"end_line":162,"context_start_line":140,"context_end_line":182,"code":" self.type = \"Search_Click_Control_Webrun_Agent\"\n self.agents = agents\n self.task = {}\n self.actions = {}\n self.observations = {}\n self.agent_calls = {} # saving the agents types in sessions\n self.item_recall = {}\n self.cur_session = 0\n self.agents = agents\n self.control_dict = control_dict\n \n def new_session(self, idx, task):\n self.cur_session = idx\n self.task[idx] = task\n self.actions[idx] = ['reset']\n self.observations[idx] = []\n self.item_recall[idx] = []\n self.agent_calls[idx] = [\"Search_Click_Controller\"]\n self.task_assign(task)\n \n def task_assign(self, task):\n for agent in self.agents:\n agent.task = task\n\n def action_parser(self, text, available_actions):\n nor_text = text.strip().lower()\n if nor_text.startswith('search'):\n query = get_query(nor_text)\n return f\"search[{query}]\"\n if nor_text.startswith('click'):\n if 'click' in available_actions:\n for a in available_actions['click']:\n if a.lower() in nor_text:\n return f\"click[{a}]\"\n return text\n \n def get_agents_types(self):\n return [a.type for a in self.agents]\n \n def prompt_layer(self, agent, available_actions):\n if agent.type == \"Search_Webrun_Agent\":\n return self.ask_search_agent()\n if agent.type == \"Click_Webrun_Agent\":","source_hash":"7b928fb475294d6ea91a0c633556165d1f7fdb0295081748a6fadb3a94184233","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.multi_agent_arch.get_agents_types","uri":"program://BOLAA/function/web_run.multi_agent_arch.get_agents_types#L176-L177","kind":"function","name":"get_agents_types","path":"web_run/multi_agent_arch.py","language":"python","start_line":176,"end_line":177,"context_start_line":156,"context_end_line":197,"code":" self.item_recall[idx] = []\n self.agent_calls[idx] = [\"Search_Click_Controller\"]\n self.task_assign(task)\n \n def task_assign(self, task):\n for agent in self.agents:\n agent.task = task\n\n def action_parser(self, text, available_actions):\n nor_text = text.strip().lower()\n if nor_text.startswith('search'):\n query = get_query(nor_text)\n return f\"search[{query}]\"\n if nor_text.startswith('click'):\n if 'click' in available_actions:\n for a in available_actions['click']:\n if a.lower() in nor_text:\n return f\"click[{a}]\"\n return text\n \n def get_agents_types(self):\n return [a.type for a in self.agents]\n \n def prompt_layer(self, agent, available_actions):\n if agent.type == \"Search_Webrun_Agent\":\n return self.ask_search_agent()\n if agent.type == \"Click_Webrun_Agent\":\n return self.ask_click_agent()\n return 0\n \n def ask_search_agent(self):\n initial = self.task[self.cur_session]\n prompt = f\"Instruction:\\n{initial}\\n\"\n search_label = False\n for idx, agent_type in enumerate(self.agent_calls[self.cur_session]):\n if agent_type == \"Search_Webrun_Agent\":\n search_label = True\n action = self.actions[self.cur_session][idx]\n prompt += f\"You have already {action}.\\n\"\n if search_label:\n prompt += \"Can you change your search query?\"\n return prompt","source_hash":"7b928fb475294d6ea91a0c633556165d1f7fdb0295081748a6fadb3a94184233","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.multi_agent_arch.ask_search_agent","uri":"program://BOLAA/function/web_run.multi_agent_arch.ask_search_agent#L186-L197","kind":"function","name":"ask_search_agent","path":"web_run/multi_agent_arch.py","language":"python","start_line":186,"end_line":197,"context_start_line":166,"context_end_line":217,"code":" if nor_text.startswith('search'):\n query = get_query(nor_text)\n return f\"search[{query}]\"\n if nor_text.startswith('click'):\n if 'click' in available_actions:\n for a in available_actions['click']:\n if a.lower() in nor_text:\n return f\"click[{a}]\"\n return text\n \n def get_agents_types(self):\n return [a.type for a in self.agents]\n \n def prompt_layer(self, agent, available_actions):\n if agent.type == \"Search_Webrun_Agent\":\n return self.ask_search_agent()\n if agent.type == \"Click_Webrun_Agent\":\n return self.ask_click_agent()\n return 0\n \n def ask_search_agent(self):\n initial = self.task[self.cur_session]\n prompt = f\"Instruction:\\n{initial}\\n\"\n search_label = False\n for idx, agent_type in enumerate(self.agent_calls[self.cur_session]):\n if agent_type == \"Search_Webrun_Agent\":\n search_label = True\n action = self.actions[self.cur_session][idx]\n prompt += f\"You have already {action}.\\n\"\n if search_label:\n prompt += \"Can you change your search query?\"\n return prompt\n \n def ask_click_agent(self):\n prompt = \"\"\n for idx in range(1, len(self.actions[self.cur_session])):\n agent_type = self.agent_calls[self.cur_session][idx]\n action = self.actions[self.cur_session][idx]\n observation = self.observations[self.cur_session][idx]\n if agent_type == \"Click_Webrun_Agent\":\n prompt += f\"\\n\\nAction:{action}\\nObservation:{observation}\"\n else:\n prompt += f\"\\n\\n{agent_type}:{action}\\nObservation:{observation}\"\n return prompt\n \n def call_agent(self, observation, available_actions):\n for agent in self.agents:\n if self.control_dict[agent.type] in available_actions:\n return agent\n \n def llm_layer(self, prompt):\n return self.llm(prompt)","source_hash":"7b928fb475294d6ea91a0c633556165d1f7fdb0295081748a6fadb3a94184233","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.multi_agent_arch.ask_click_agent","uri":"program://BOLAA/function/web_run.multi_agent_arch.ask_click_agent#L199-L209","kind":"function","name":"ask_click_agent","path":"web_run/multi_agent_arch.py","language":"python","start_line":199,"end_line":209,"context_start_line":179,"context_end_line":227,"code":" def prompt_layer(self, agent, available_actions):\n if agent.type == \"Search_Webrun_Agent\":\n return self.ask_search_agent()\n if agent.type == \"Click_Webrun_Agent\":\n return self.ask_click_agent()\n return 0\n \n def ask_search_agent(self):\n initial = self.task[self.cur_session]\n prompt = f\"Instruction:\\n{initial}\\n\"\n search_label = False\n for idx, agent_type in enumerate(self.agent_calls[self.cur_session]):\n if agent_type == \"Search_Webrun_Agent\":\n search_label = True\n action = self.actions[self.cur_session][idx]\n prompt += f\"You have already {action}.\\n\"\n if search_label:\n prompt += \"Can you change your search query?\"\n return prompt\n \n def ask_click_agent(self):\n prompt = \"\"\n for idx in range(1, len(self.actions[self.cur_session])):\n agent_type = self.agent_calls[self.cur_session][idx]\n action = self.actions[self.cur_session][idx]\n observation = self.observations[self.cur_session][idx]\n if agent_type == \"Click_Webrun_Agent\":\n prompt += f\"\\n\\nAction:{action}\\nObservation:{observation}\"\n else:\n prompt += f\"\\n\\n{agent_type}:{action}\\nObservation:{observation}\"\n return prompt\n \n def call_agent(self, observation, available_actions):\n for agent in self.agents:\n if self.control_dict[agent.type] in available_actions:\n return agent\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n agent = self.call_agent(observation, available_actions)\n prompt = self.prompt_layer(agent, available_actions)\n action = agent.forward(prompt, available_actions).lstrip()\n action = self.action_parser(action, available_actions)\n self.actions[self.cur_session].append(action)\n self.agent_calls[self.cur_session].append(agent.type)\n return action","source_hash":"7b928fb475294d6ea91a0c633556165d1f7fdb0295081748a6fadb3a94184233","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.multi_agent_arch.call_agent","uri":"program://BOLAA/function/web_run.multi_agent_arch.call_agent#L211-L214","kind":"function","name":"call_agent","path":"web_run/multi_agent_arch.py","language":"python","start_line":211,"end_line":214,"context_start_line":191,"context_end_line":227,"code":" if agent_type == \"Search_Webrun_Agent\":\n search_label = True\n action = self.actions[self.cur_session][idx]\n prompt += f\"You have already {action}.\\n\"\n if search_label:\n prompt += \"Can you change your search query?\"\n return prompt\n \n def ask_click_agent(self):\n prompt = \"\"\n for idx in range(1, len(self.actions[self.cur_session])):\n agent_type = self.agent_calls[self.cur_session][idx]\n action = self.actions[self.cur_session][idx]\n observation = self.observations[self.cur_session][idx]\n if agent_type == \"Click_Webrun_Agent\":\n prompt += f\"\\n\\nAction:{action}\\nObservation:{observation}\"\n else:\n prompt += f\"\\n\\n{agent_type}:{action}\\nObservation:{observation}\"\n return prompt\n \n def call_agent(self, observation, available_actions):\n for agent in self.agents:\n if self.control_dict[agent.type] in available_actions:\n return agent\n \n def llm_layer(self, prompt):\n return self.llm(prompt)\n \n def forward(self, observation, available_actions=None):\n self.observations[self.cur_session].append(observation)\n agent = self.call_agent(observation, available_actions)\n prompt = self.prompt_layer(agent, available_actions)\n action = agent.forward(prompt, available_actions).lstrip()\n action = self.action_parser(action, available_actions)\n self.actions[self.cur_session].append(action)\n self.agent_calls[self.cur_session].append(agent.type)\n return action","source_hash":"7b928fb475294d6ea91a0c633556165d1f7fdb0295081748a6fadb3a94184233","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.pre_prompt","uri":"program://BOLAA/module/web_run.pre_prompt#L1-L234","kind":"module","name":"web_run.pre_prompt","path":"web_run/pre_prompt.py","language":"python","start_line":1,"end_line":234,"context_start_line":1,"context_end_line":234,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nzeroshot = \"\"\"Following the instruction to simulate the web shopping. Based on your observation, you may operate one of the following actions\nsearch: using this action to search products.\nclick: click observed [button], the clickable buttons are in [], for example click [Back to Search] can return back to research.\nUse your best knowledge and take actions. You response should follow action[detail] format, such as search[3 ounce bright citrus deodorant sensitive skin], click[B078GWRC1J], click[bright citrus].\n\"\"\"\n\nzeroshot_think = \"\"\"You are simulating web shopping. Based on your observation, you may operate one of the following actions:\nsearch: using this action to search products.\nthink: using this action to plan your actions and reasoning.\nclick: using this action to click observed [button], the clickable buttons are in [], for example click [Back to Search] can return back to research.\nUse your best knowledge and take actions. You response should follow action[detail] format, such as search[3 ounce bright citrus deodorant sensitive skin], think[B078GWRC1J and B078GTKVXY are bright citrus deodorant less then 50 dollars. I can check B078GWRC1J first.], click[B078GWRC1J], click[bright citrus].\n\"\"\"\n\noneshot = \"\"\"Webshop \nInstruction: \ni would like a 3 ounce bottle of bright citrus deodorant for sensitive skin, and price lower than 50.00 dollars \n[Search] \n\nAction: search[3 ounce bright citrus deodorant sensitive skin]\nObservation: \n[Back to Search] \nPage 1 (Total results: 50) \n[Next >] \n[B078GWRC1J] \nBright Citrus Deodorant by Earth Mama | Natural and Safe for Sensitive Skin, Pregnancy and Breastfeeding, Contains Organic Calendula 3-Ounce \n$10.99 \n[B078GTKVXY] \nGinger Fresh Deodorant by Earth Mama | Natural and Safe for Sensitive Skin, Pregnancy and Breastfeeding, Contains Organic Calendula 3-Ounce \n$10.99 \n[B08KBVJ4XN] \nBarrel and Oak - Aluminum-Free Deodorant, Deodorant for Men, Essential Oil-Based Scent, 24-Hour Odor Protection, Cedar & Patchouli Blend, Gentle on Sensitive Skin (Mountain Sage, 2.7 oz, 2-Pack) \n$15.95 \n\nAction: think[B078GWRC1J and B078GTKVXY are bright citrus deodorant less then 50 dollars. I can check B078GWRC1J first.]\nObservation: OK.\n\nAction: click[B078GWRC1J]\nObservation: \n[Back to Search] \n[< Prev] \nscent [assorted scents][bright citrus][calming lavender][ginger fresh][simply non-scents]\nsize [travel set (4-pack)][3 ounce (pack of 1)][3-ounce (2-pack)]\nBright Citrus Deodorant by Earth Mama | Natural and Safe for Sensitive Skin, Pregnancy and Breastfeeding, Contains Organic Calendula 3-Ounce \nPrice: $10.99 \nRating: N.A. \n[Description] \n[Features] \n[Reviews] \n[Buy Now] \n\nAction: think[For 3 ounce bottle of bright citrus deodorant for sensitive skin, the item has options 'bright citrus' and '3 ounce (pack of 1)' and seems good to buy.]\nObservation: OK.\n\nAction: click[bright citrus]\nObservation: You have clicked bright citrus. \n\nAction: click[3 ounce (pack of 1)]\nObservation: You have clicked 3 ounce (pack of 1). \n\nAction: click[Buy Now]\n\"\"\"\n\nplan = \"\"\"Webshop \nInstruction: i would like a 3 ounce bottle of bright citrus deodorant for sensitive skin, and price lower than 50.00 dollars. \nPlan: First, I need to search[3 ounce bright citrus deodorant sensitive skin]. Next, I need to click the most relevant item to get more details, e.g. click[B078GWRC1J]. Next, if this item is not what I want, I will click[< Prev] to check other searching results or I can click[Back to Search] to search with different keywords. If I find one item meets the instruction requirements, I will click necessary options, such as click[bright citrus] and click[3 ounce (pack of 1)]. Finally, I will click[Buy Now] to complete the shopping.\n\"\"\"\n\noneshot_plan = \"\"\"Webshop \nInstruction: i would like a 3 ounce bottle of bright citrus deodorant for sensitive skin, and price lower than 50.00 dollars. \nPlan: First, I need to search[3 ounce bright citrus deodorant sensitive skin]. Next, I need to click the most relevant item to get more details, e.g. click[B078GWRC1J]. Next, if this item is not what I want, I will click[< Prev] to check other searching results or I can click[Back to Search] to search with different keywords. If I find one item meets the instruction requirements, I will click necessary options, such as click[bright citrus] and click[3 ounce (pack of 1)]. Finally, I will click[Buy Now] to complete the shopping.\n\nAction: search[3 ounce bright citrus deodorant sensitive skin]\nObservation: \n[Back to Search] \nPage 1 (Total results: 50) \n[Next >] \n[B078GWRC1J] \nBright Citrus Deodorant by Earth Mama | Natural and Safe for Sensitive Skin, Pregnancy and Breastfeeding, Contains Organic Calendula 3-Ounce \n$10.99 \n[B078GTKVXY] \nGinger Fresh Deodorant by Earth Mama | Natural and Safe for Sensitive Skin, Pregnancy and Breastfeeding, Contains Organic Calendula 3-Ounce \n$10.99 \n[B08KBVJ4XN] \nBarrel and Oak - Aluminum-Free Deodorant, Deodorant for Men, Essential Oil-Based Scent, 24-Hour Odor Protection, Cedar & Patchouli Blend, Gentle on Sensitive Skin (Mountain Sage, 2.7 oz, 2-Pack) \n$15.95 \n\nAction: click[B078GWRC1J]\nObservation:\n[Back to Search]\n[< Prev]\nscent [assorted scents][bright citrus][calming lavender][ginger fresh][simply non-scents]\nsize [travel set (4-pack)][3 ounce (pack of 1)][3-ounce (2-pack)]\nBright Citrus Deodorant by Earth Mama | Natural and Safe for Sensitive Skin, Pregnancy and Breastfeeding, Contains Organic Calendula 3-Ounce \nPrice: $10.99\nRating: N.A.\n[Description]\n[Features]\n[Reviews]\n[Buy Now]\n\nAction: click[bright citrus]\nObservation: You have clicked bright citrus.\n\nAction: click[3 ounce (pack of 1)]\nObservation: You have clicked 3 ounce (pack of 1). \n\nAction: click[Buy Now]\n\"\"\"\n\nplan_react = \"\"\"Webshop \nInstruction: i would like a 3 ounce bottle of bright citrus deodorant for sensitive skin, and price lower than 50.00 dollars. \nPlan: First, I need to search[3 ounce bright citrus deodorant sensitive skin]. Next, I need to think[some items are bright citrus deodorant less then 50 dollars. I can check one first.]. Next, I need to click the most relevant item to get more details, e.g. click[B078GWRC1J]. If I need think whether this item meets the requirements, e.g. think[For 3 ounce bottle of bright citrus deodorant for sensitive skin, the item has options 'bright citrus' and '3 ounce (pack of 1)' and seems good to buy.]. Then, I will click necessary options, such as click[bright citrus] and click[3 ounce (pack of 1)]. Finally, I will click[Buy Now] to complete the shopping.\n\"\"\"\n\noneshot_plan_react = \"\"\"Webshop \nInstruction: \ni would like a 3 ounce bottle of bright citrus deodorant for sensitive skin, and price lower than 50.00 dollars \n[Search] \n\nAction: search[3 ounce bright citrus deodorant sensitive skin]\nObservation: \n[Back to Search] \nPage 1 (Total results: 50) \n[Next >] \n[B078GWRC1J] \nBright Citrus Deodorant by Earth Mama | Natural and Safe for Sensitive Skin, Pregnancy and Breastfeeding, Contains Organic Calendula 3-Ounce \n$10.99 \n[B078GTKVXY] \nGinger Fresh Deodorant by Earth Mama | Natural and Safe for Sensitive Skin, Pregnancy and Breastfeeding, Contains Organic Calendula 3-Ounce \n$10.99 \n[B08KBVJ4XN] \nBarrel and Oak - Aluminum-Free Deodorant, Deodorant for Men, Essential Oil-Based Scent, 24-Hour Odor Protection, Cedar & Patchouli Blend, Gentle on Sensitive Skin (Mountain Sage, 2.7 oz, 2-Pack) \n$15.95 \n\nAction: think[B078GWRC1J and B078GTKVXY are bright citrus deodorant less then 50 dollars. I can check B078GWRC1J first.]\nObservation: OK.\n\nAction: click[B078GWRC1J]\nObservation: \n[Back to Search] \n[< Prev] \nscent [assorted scents][bright citrus][calming lavender][ginger fresh][simply non-scents]\nsize [travel set (4-pack)][3 ounce (pack of 1)][3-ounce (2-pack)]\nBright Citrus Deodorant by Earth Mama | Natural and Safe for Sensitive Skin, Pregnancy and Breastfeeding, Contains Organic Calendula 3-Ounce \nPrice: $10.99 \nRating: N.A. \n[Description] \n[Features] \n[Reviews] \n[Buy Now] \n\nAction: think[For 3 ounce bottle of bright citrus deodorant for sensitive skin, the item has options 'bright citrus' and '3 ounce (pack of 1)' and seems good to buy.]\nObservation: OK.\n\nAction: click[bright citrus]\nObservation: You have clicked bright citrus. \n\nAction: click[3 ounce (pack of 1)]\nObservation: You have clicked 3 ounce (pack of 1). \n\nAction: click[Buy Now]\n\"\"\"\n\nsearch = \"\"\"Webshop \nInstruction:\ni'm looking for a yellow hair styling product that is made from natural ingredients and easy to use, and price lower than 40.00 dollars\nYou have already search[yellow hair styling product made from natural ingredients easy to use price < 40.00 dollars]. Could you please change your search query?\n\nAction: search[yellow hair styling natural ingredients]\n\nInstruction: \ni would like a 3 ounce bottle of bright citrus deodorant for sensitive skin, and price lower than 50.00 dollars \n\nAction: search[3 ounce bright citrus deodorant sensitive skin]\n\nInstruction:\ni am looking for black pull-out organizers with nickel finish and size must be 15\\\" wide, and price lower than 90.00 dollars\n\nAction: search[black pull-out organizers with nickel finish, 15\\\" wide]\n\"\"\"\n\nclick = \"\"\"Webshop \nInstruction: \ni would like a 3 ounce bottle of bright citrus deodorant for sensitive skin, and price lower than 50.00 dollars \n[Search] \n\nsearch[3 ounce bright citrus deodorant sensitive skin]\nObservation: \n[Back to Search] \nPage 1 (Total results: 50) \n[Next >] \n[B078GWRC1J] \nBright Citrus Deodorant by Earth Mama | Natural and Safe for Sensitive Skin, Pregnancy and Breastfeeding, Contains Organic Calendula 3-Ounce \n$10.99 \n[B078GTKVXY] \nGinger Fresh Deodorant by Earth Mama | Natural and Safe for Sensitive Skin, Pregnancy and Breastfeeding, Contains Organic Calendula 3-Ounce \n$10.99 \n[B08KBVJ4XN] \nBarrel and Oak - Aluminum-Free Deodorant, Deodorant for Men, Essential Oil-Based Scent, 24-Hour Odor Protection, Cedar & Patchouli Blend, Gentle on Sensitive Skin (Mountain Sage, 2.7 oz, 2-Pack) \n$15.95\ncurrent available action is click:[Back to Search\\tB078GWRC1J\\tB078GTKVXY\\tB08KBVJ4XN]\n\nAction: click[B078GWRC1J]\nObservation: \n[Back to Search] \n[< Prev] \nscent [assorted scents][bright citrus][calming lavender][ginger fresh][simply non-scents]\nsize [travel set (4-pack)][3 ounce (pack of 1)][3-ounce (2-pack)]\nBright Citrus Deodorant by Earth Mama | Natural and Safe for Sensitive Skin, Pregnancy and Breastfeeding, Contains Organic Calendula 3-Ounce \nPrice: $10.99 \nRating: N.A. \n[Description] \n[Features] \n[Reviews]\n[Buy Now]\ncurrent available action is click:[Back to Search\\t< Prev\\tassorted scents\\tbright citrus\\tcalming lavender\\tginger fresh\\tsimply non-scents\\ttravel set (4-pack)\\t3 ounce (pack of 1)\\t3-ounce (2-pack)\\tDescription\\tFeatures\\tReviews\\tBuy Now]\n\nAction: click[bright citrus]\nObservation: You have clicked bright citrus.\ncurrent available action is click:[Back to Search\\t< Prev\\tassorted scents\\tbright citrus\\tcalming lavender\\tginger fresh\\tsimply non-scents\\ttravel set (4-pack)\\t3 ounce (pack of 1)\\t3-ounce (2-pack)\\tDescription\\tFeatures\\tReviews\\tBuy Now]\n\nAction: click[3 ounce (pack of 1)]\nObservation: You have clicked 3 ounce (pack of 1). \ncurrent available action is click:[Back to Search\\t< Prev\\tassorted scents\\tbright citrus\\tcalming lavender\\tginger fresh\\tsimply non-scents\\ttravel set (4-pack)\\t3 ounce (pack of 1)\\t3-ounce (2-pack)\\tDescription\\tFeatures\\tReviews\\tBuy Now]\n\nAction: click[Buy Now]\n\"\"\"","source_hash":"586b9a596752820d653c8c3b3e6cc7b2f5787443a00ec644b935198442c7cffe","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate","uri":"program://BOLAA/module/web_run.evaluate#L1-L265","kind":"module","name":"web_run.evaluate","path":"web_run/evaluate.py","language":"python","start_line":1,"end_line":265,"context_start_line":1,"context_end_line":265,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport json\nimport os\nimport re \nfrom collections import defaultdict\nfrom web_run.config import available_agent_names\n\ndef get_complexity(ins_attr_file=\"../webshop/data/items_human_ins_new.json\"):\n with open(ins_attr_file) as f:\n human_attr = json.load(f)\n complexity_dict = {}\n for asin in human_attr:\n for ins in human_attr[asin]:\n instruction = ins[\"instruction\"]\n attribute_complexity = len(ins[\"instruction_attributes\"])\n option_complexity = len(ins[\"instruction_options\"])\n key = instruction.strip('.') \n complexity_dict[key] = [attribute_complexity, option_complexity]\n return complexity_dict\n\ndef get_reward(session):\n last_session = session[-1]\n observation = last_session['observation']\n if observation.startswith('Your score'):\n tokens = observation.split(':')\n for idx, token in enumerate(tokens):\n if \"Your score (min 0.0, max 1.0)\" in token:\n cur_idx = idx+1\n reward = tokens[cur_idx].strip()\n return float(reward)\n return 0.0\n\ndef get_sess_ins(session):\n instruction = session[0]['instruction_text']\n return instruction\n\ndef get_sess_step(session):\n step_id = session[-1][\"step_id\"]\n numbers = re.findall(r'\\d+', step_id)\n sess_idx, step_len = numbers\n return int(step_len)\n\ndef filter_results(file_name):\n sessions = get_file_sess(file_name)\n original = len(sessions)\n new_sessions = []\n with open(file_name + '.back', 'a') as f:\n for _, sess in enumerate(sessions):\n json.dump(sess, f)\n f.write('\\n')\n saving_label = True\n for step in sess: \n if \"action\" in step: # checking whether it is a action step\n if \"No response\" in step[\"action\"]: # checking whether it is No response due to LLM \n saving_label = False\n if \"observation\" in step:\n if \"Your score (min 0.0, max 1.0):\" in step[\"observation\"]:\n saving_label = True\n if saving_label:\n new_sessions.append(sess) \n after_filtering = len(new_sessions)\n if original - after_filtering > 0:\n print(f\"{original - after_filtering} session contain No response\")\n with open(file_name, 'w') as f:\n for sess in new_sessions:\n json.dump(sess, f)\n f.write('\\n')\n\ndef delete_repeat(file_name):\n sessions = get_file_sess(file_name)\n idx_score = {}\n idx_ref = {}\n with open(file_name + '.repeat', 'a') as f: # only saving highest score\n for sess in sessions:\n json.dump(sess, f)\n f.write('\\n')\n sess_idx = get_sess_idx(sess)\n reward = get_reward(sess)\n if sess_idx in idx_score:\n if reward < idx_score[sess_idx]:\n continue\n idx_score[sess_idx] = reward\n idx_ref[sess_idx] = sess\n with open(file_name, 'w') as f:\n sort_idx = sorted(idx_ref.keys())\n for sess_idx in sort_idx:\n sess = idx_ref[sess_idx]\n json.dump(sess, f)\n f.write('\\n')\n \ndef get_file_sess(file_name):\n sessions = []\n with open(file_name) as f:\n for line in f:\n session = json.loads(line)\n sessions.append(session)\n return sessions\n\ndef get_sess_idx(session):\n step_id = session[-1][\"step_id\"]\n numbers = re.findall(r'\\d+', step_id)\n sess_idx, step_len = numbers\n return int(sess_idx)\n\ndef get_file_sess_idx(file_name):\n session_idx = []\n with open(file_name) as f:\n for line in f:\n session = json.loads(line)\n session_idx.append(get_sess_idx(session))\n return set(session_idx)\n\ndef get_goal_item(session):\n goal = session[0]\n asin = goal['asin']\n return asin \n\ndef get_session_items(session):\n items = []\n for step in session:\n if \"retrieved_items\" in step:\n items += step[\"retrieved_items\"]\n return items\n\ndef merge_sessions_by_llm(model_name, path = \"./execution_data/\"):\n file_list = []\n sessions = []\n for root, _, files in os.walk(path):\n for file_name in files:\n if model_name in file_name:\n file_list.append(os.path.join(root, file_name))\n for f_name in file_list:\n with open(f_name) as f:\n for line in f:\n session = json.loads(line)\n sessions.append(session)\n return sessions\n\ndef get_recall(sess):\n goal_item = get_goal_item(sess)\n retri_items = get_session_items(sess)\n if goal_item in retri_items:\n return 1\n else:\n return 0\n \ndef get_precision(sess):\n goal_item = get_goal_item(sess)\n retri_items = get_session_items(sess)\n if goal_item in retri_items:\n return 1/len(retri_items)\n else:\n return 0\n\ndef get_fail(sess):\n if \"observation\" in sess[-1]:\n if \"Your score (min 0.0, max 1.0):\" in sess[-1][\"observation\"]:\n return 0\n return 1\n\ndef get_halluci(sess):\n halluci_step_idx = []\n for step in sess:\n if \"step_id\" in step:\n step_id = step[\"step_id\"]\n numbers = re.findall(r'\\d+', step_id)\n sess_idx, step_idx = numbers\n if \"observation\" in step:\n if \"Invalid action!\" in step[\"observation\"]:\n halluci_step_idx.append(step_idx)\n return halluci_step_idx\n \ndef eval_complexity(sessions, complexity_dict):\n complexity = []\n for sess in sessions:\n instruction = get_sess_ins(sess)\n if instruction.find(\", and price lower\") > 0:\n ins_key = instruction[:instruction.find(\", and price lower\")]\n else:\n ins_key = instruction\n if ins_key in complexity_dict:\n attr_complexity, option_complexity = complexity_dict[ins_key]\n else:\n print(\"no complexity for \", ins_key)\n complexity.append(attr_complexity + option_complexity)\n return complexity\n\ndef eval_success(sessions) -> list:\n success = []\n for sess in sessions:\n r = get_reward(sess)\n if r >= 1:\n success.append(1)\n else:\n success.append(0)\n return success \n\ndef eval_initial_halluci(sessions) -> list:\n initial_halluci = []\n for sess in sessions:\n initial_halluci.append(get_halluci(sess)[0])\n return initial_halluci\n\ndef eval_avg_halluci(sessions) -> list:\n avg_halluci = []\n for sess in sessions:\n halluci = get_halluci(sess)\n avg_halluci.append(sum(halluci)/len(halluci))\n return avg_halluci\n\ndef eval_fail(sessions) -> list:\n fail_list = [get_fail(sess) for sess in sessions]\n return fail_list\n\ndef eval_reward(sessions) -> list:\n reward = []\n for sess in sessions:\n reward.append(get_reward(sess))\n return reward\n\ndef eval_recall(sessions) -> list:\n recall = [get_recall(sess) for sess in sessions]\n return recall\n\ndef eval_precision(sessions) -> list:\n prec = [get_precision(sess) for sess in sessions]\n return prec\n\ndef y_wrt_x_rel(x, y):\n x_dict = defaultdict(list)\n for idx, c in enumerate(x):\n x_dict[c].append(y[idx])\n x_dict_y = {key:round(sum(val)/len(val), 4) for key, val in x_dict.items()}\n return x_dict_y\n\ndef get_all_eval_values(llm_name):\n agent_types = available_agent_names\n for a_type in agent_types:\n get_eval_values(llm_name, a_type)\n \ndef get_eval_values(llm_name, agent_type, path=\"./execution_data/\"):\n file_name = f\"{agent_type}_{llm_name}_batch.json\"\n file_name = os.path.join(path, file_name)\n delete_repeat(file_name)\n session_idx = get_file_sess_idx(file_name)\n assert len(session_idx) == 900\n sessions = get_file_sess(file_name)\n # print(len(sessions))\n recalls = eval_recall(sessions)\n rewards = eval_reward(sessions)\n precisions = eval_precision(sessions)\n success = eval_success(sessions)\n fail = eval_fail(sessions)\n avg_reward = round(sum(rewards)/len(rewards), 4)\n success_rate = round(sum(success)/len(success), 4)\n fail_rate = round(sum(fail)/len(success), 4)\n avg_recall = round(sum(recalls)/len(recalls), 4)\n avg_prec = round(sum(precisions)/len(precisions), 4)\n print(f\"{avg_reward}\\t{success_rate}\\t{fail_rate}\\t{avg_recall}\\t{avg_prec}\")","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate.get_complexity","uri":"program://BOLAA/function/web_run.evaluate.get_complexity#L14-L25","kind":"function","name":"get_complexity","path":"web_run/evaluate.py","language":"python","start_line":14,"end_line":25,"context_start_line":1,"context_end_line":45,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport json\nimport os\nimport re \nfrom collections import defaultdict\nfrom web_run.config import available_agent_names\n\ndef get_complexity(ins_attr_file=\"../webshop/data/items_human_ins_new.json\"):\n with open(ins_attr_file) as f:\n human_attr = json.load(f)\n complexity_dict = {}\n for asin in human_attr:\n for ins in human_attr[asin]:\n instruction = ins[\"instruction\"]\n attribute_complexity = len(ins[\"instruction_attributes\"])\n option_complexity = len(ins[\"instruction_options\"])\n key = instruction.strip('.') \n complexity_dict[key] = [attribute_complexity, option_complexity]\n return complexity_dict\n\ndef get_reward(session):\n last_session = session[-1]\n observation = last_session['observation']\n if observation.startswith('Your score'):\n tokens = observation.split(':')\n for idx, token in enumerate(tokens):\n if \"Your score (min 0.0, max 1.0)\" in token:\n cur_idx = idx+1\n reward = tokens[cur_idx].strip()\n return float(reward)\n return 0.0\n\ndef get_sess_ins(session):\n instruction = session[0]['instruction_text']\n return instruction\n\ndef get_sess_step(session):\n step_id = session[-1][\"step_id\"]\n numbers = re.findall(r'\\d+', step_id)","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate.get_reward","uri":"program://BOLAA/function/web_run.evaluate.get_reward#L27-L37","kind":"function","name":"get_reward","path":"web_run/evaluate.py","language":"python","start_line":27,"end_line":37,"context_start_line":7,"context_end_line":57,"code":"\nimport json\nimport os\nimport re \nfrom collections import defaultdict\nfrom web_run.config import available_agent_names\n\ndef get_complexity(ins_attr_file=\"../webshop/data/items_human_ins_new.json\"):\n with open(ins_attr_file) as f:\n human_attr = json.load(f)\n complexity_dict = {}\n for asin in human_attr:\n for ins in human_attr[asin]:\n instruction = ins[\"instruction\"]\n attribute_complexity = len(ins[\"instruction_attributes\"])\n option_complexity = len(ins[\"instruction_options\"])\n key = instruction.strip('.') \n complexity_dict[key] = [attribute_complexity, option_complexity]\n return complexity_dict\n\ndef get_reward(session):\n last_session = session[-1]\n observation = last_session['observation']\n if observation.startswith('Your score'):\n tokens = observation.split(':')\n for idx, token in enumerate(tokens):\n if \"Your score (min 0.0, max 1.0)\" in token:\n cur_idx = idx+1\n reward = tokens[cur_idx].strip()\n return float(reward)\n return 0.0\n\ndef get_sess_ins(session):\n instruction = session[0]['instruction_text']\n return instruction\n\ndef get_sess_step(session):\n step_id = session[-1][\"step_id\"]\n numbers = re.findall(r'\\d+', step_id)\n sess_idx, step_len = numbers\n return int(step_len)\n\ndef filter_results(file_name):\n sessions = get_file_sess(file_name)\n original = len(sessions)\n new_sessions = []\n with open(file_name + '.back', 'a') as f:\n for _, sess in enumerate(sessions):\n json.dump(sess, f)\n f.write('\\n')\n saving_label = True","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate.get_sess_ins","uri":"program://BOLAA/function/web_run.evaluate.get_sess_ins#L39-L41","kind":"function","name":"get_sess_ins","path":"web_run/evaluate.py","language":"python","start_line":39,"end_line":41,"context_start_line":19,"context_end_line":61,"code":" for ins in human_attr[asin]:\n instruction = ins[\"instruction\"]\n attribute_complexity = len(ins[\"instruction_attributes\"])\n option_complexity = len(ins[\"instruction_options\"])\n key = instruction.strip('.') \n complexity_dict[key] = [attribute_complexity, option_complexity]\n return complexity_dict\n\ndef get_reward(session):\n last_session = session[-1]\n observation = last_session['observation']\n if observation.startswith('Your score'):\n tokens = observation.split(':')\n for idx, token in enumerate(tokens):\n if \"Your score (min 0.0, max 1.0)\" in token:\n cur_idx = idx+1\n reward = tokens[cur_idx].strip()\n return float(reward)\n return 0.0\n\ndef get_sess_ins(session):\n instruction = session[0]['instruction_text']\n return instruction\n\ndef get_sess_step(session):\n step_id = session[-1][\"step_id\"]\n numbers = re.findall(r'\\d+', step_id)\n sess_idx, step_len = numbers\n return int(step_len)\n\ndef filter_results(file_name):\n sessions = get_file_sess(file_name)\n original = len(sessions)\n new_sessions = []\n with open(file_name + '.back', 'a') as f:\n for _, sess in enumerate(sessions):\n json.dump(sess, f)\n f.write('\\n')\n saving_label = True\n for step in sess: \n if \"action\" in step: # checking whether it is a action step\n if \"No response\" in step[\"action\"]: # checking whether it is No response due to LLM \n saving_label = False","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate.get_sess_step","uri":"program://BOLAA/function/web_run.evaluate.get_sess_step#L43-L47","kind":"function","name":"get_sess_step","path":"web_run/evaluate.py","language":"python","start_line":43,"end_line":47,"context_start_line":23,"context_end_line":67,"code":" key = instruction.strip('.') \n complexity_dict[key] = [attribute_complexity, option_complexity]\n return complexity_dict\n\ndef get_reward(session):\n last_session = session[-1]\n observation = last_session['observation']\n if observation.startswith('Your score'):\n tokens = observation.split(':')\n for idx, token in enumerate(tokens):\n if \"Your score (min 0.0, max 1.0)\" in token:\n cur_idx = idx+1\n reward = tokens[cur_idx].strip()\n return float(reward)\n return 0.0\n\ndef get_sess_ins(session):\n instruction = session[0]['instruction_text']\n return instruction\n\ndef get_sess_step(session):\n step_id = session[-1][\"step_id\"]\n numbers = re.findall(r'\\d+', step_id)\n sess_idx, step_len = numbers\n return int(step_len)\n\ndef filter_results(file_name):\n sessions = get_file_sess(file_name)\n original = len(sessions)\n new_sessions = []\n with open(file_name + '.back', 'a') as f:\n for _, sess in enumerate(sessions):\n json.dump(sess, f)\n f.write('\\n')\n saving_label = True\n for step in sess: \n if \"action\" in step: # checking whether it is a action step\n if \"No response\" in step[\"action\"]: # checking whether it is No response due to LLM \n saving_label = False\n if \"observation\" in step:\n if \"Your score (min 0.0, max 1.0):\" in step[\"observation\"]:\n saving_label = True\n if saving_label:\n new_sessions.append(sess) \n after_filtering = len(new_sessions)","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate.filter_results","uri":"program://BOLAA/function/web_run.evaluate.filter_results#L49-L73","kind":"function","name":"filter_results","path":"web_run/evaluate.py","language":"python","start_line":49,"end_line":73,"context_start_line":29,"context_end_line":93,"code":" observation = last_session['observation']\n if observation.startswith('Your score'):\n tokens = observation.split(':')\n for idx, token in enumerate(tokens):\n if \"Your score (min 0.0, max 1.0)\" in token:\n cur_idx = idx+1\n reward = tokens[cur_idx].strip()\n return float(reward)\n return 0.0\n\ndef get_sess_ins(session):\n instruction = session[0]['instruction_text']\n return instruction\n\ndef get_sess_step(session):\n step_id = session[-1][\"step_id\"]\n numbers = re.findall(r'\\d+', step_id)\n sess_idx, step_len = numbers\n return int(step_len)\n\ndef filter_results(file_name):\n sessions = get_file_sess(file_name)\n original = len(sessions)\n new_sessions = []\n with open(file_name + '.back', 'a') as f:\n for _, sess in enumerate(sessions):\n json.dump(sess, f)\n f.write('\\n')\n saving_label = True\n for step in sess: \n if \"action\" in step: # checking whether it is a action step\n if \"No response\" in step[\"action\"]: # checking whether it is No response due to LLM \n saving_label = False\n if \"observation\" in step:\n if \"Your score (min 0.0, max 1.0):\" in step[\"observation\"]:\n saving_label = True\n if saving_label:\n new_sessions.append(sess) \n after_filtering = len(new_sessions)\n if original - after_filtering > 0:\n print(f\"{original - after_filtering} session contain No response\")\n with open(file_name, 'w') as f:\n for sess in new_sessions:\n json.dump(sess, f)\n f.write('\\n')\n\ndef delete_repeat(file_name):\n sessions = get_file_sess(file_name)\n idx_score = {}\n idx_ref = {}\n with open(file_name + '.repeat', 'a') as f: # only saving highest score\n for sess in sessions:\n json.dump(sess, f)\n f.write('\\n')\n sess_idx = get_sess_idx(sess)\n reward = get_reward(sess)\n if sess_idx in idx_score:\n if reward < idx_score[sess_idx]:\n continue\n idx_score[sess_idx] = reward\n idx_ref[sess_idx] = sess\n with open(file_name, 'w') as f:\n sort_idx = sorted(idx_ref.keys())\n for sess_idx in sort_idx:\n sess = idx_ref[sess_idx]","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate.delete_repeat","uri":"program://BOLAA/function/web_run.evaluate.delete_repeat#L75-L95","kind":"function","name":"delete_repeat","path":"web_run/evaluate.py","language":"python","start_line":75,"end_line":95,"context_start_line":55,"context_end_line":115,"code":" json.dump(sess, f)\n f.write('\\n')\n saving_label = True\n for step in sess: \n if \"action\" in step: # checking whether it is a action step\n if \"No response\" in step[\"action\"]: # checking whether it is No response due to LLM \n saving_label = False\n if \"observation\" in step:\n if \"Your score (min 0.0, max 1.0):\" in step[\"observation\"]:\n saving_label = True\n if saving_label:\n new_sessions.append(sess) \n after_filtering = len(new_sessions)\n if original - after_filtering > 0:\n print(f\"{original - after_filtering} session contain No response\")\n with open(file_name, 'w') as f:\n for sess in new_sessions:\n json.dump(sess, f)\n f.write('\\n')\n\ndef delete_repeat(file_name):\n sessions = get_file_sess(file_name)\n idx_score = {}\n idx_ref = {}\n with open(file_name + '.repeat', 'a') as f: # only saving highest score\n for sess in sessions:\n json.dump(sess, f)\n f.write('\\n')\n sess_idx = get_sess_idx(sess)\n reward = get_reward(sess)\n if sess_idx in idx_score:\n if reward < idx_score[sess_idx]:\n continue\n idx_score[sess_idx] = reward\n idx_ref[sess_idx] = sess\n with open(file_name, 'w') as f:\n sort_idx = sorted(idx_ref.keys())\n for sess_idx in sort_idx:\n sess = idx_ref[sess_idx]\n json.dump(sess, f)\n f.write('\\n')\n \ndef get_file_sess(file_name):\n sessions = []\n with open(file_name) as f:\n for line in f:\n session = json.loads(line)\n sessions.append(session)\n return sessions\n\ndef get_sess_idx(session):\n step_id = session[-1][\"step_id\"]\n numbers = re.findall(r'\\d+', step_id)\n sess_idx, step_len = numbers\n return int(sess_idx)\n\ndef get_file_sess_idx(file_name):\n session_idx = []\n with open(file_name) as f:\n for line in f:\n session = json.loads(line)","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate.get_file_sess","uri":"program://BOLAA/function/web_run.evaluate.get_file_sess#L97-L103","kind":"function","name":"get_file_sess","path":"web_run/evaluate.py","language":"python","start_line":97,"end_line":103,"context_start_line":77,"context_end_line":123,"code":" idx_score = {}\n idx_ref = {}\n with open(file_name + '.repeat', 'a') as f: # only saving highest score\n for sess in sessions:\n json.dump(sess, f)\n f.write('\\n')\n sess_idx = get_sess_idx(sess)\n reward = get_reward(sess)\n if sess_idx in idx_score:\n if reward < idx_score[sess_idx]:\n continue\n idx_score[sess_idx] = reward\n idx_ref[sess_idx] = sess\n with open(file_name, 'w') as f:\n sort_idx = sorted(idx_ref.keys())\n for sess_idx in sort_idx:\n sess = idx_ref[sess_idx]\n json.dump(sess, f)\n f.write('\\n')\n \ndef get_file_sess(file_name):\n sessions = []\n with open(file_name) as f:\n for line in f:\n session = json.loads(line)\n sessions.append(session)\n return sessions\n\ndef get_sess_idx(session):\n step_id = session[-1][\"step_id\"]\n numbers = re.findall(r'\\d+', step_id)\n sess_idx, step_len = numbers\n return int(sess_idx)\n\ndef get_file_sess_idx(file_name):\n session_idx = []\n with open(file_name) as f:\n for line in f:\n session = json.loads(line)\n session_idx.append(get_sess_idx(session))\n return set(session_idx)\n\ndef get_goal_item(session):\n goal = session[0]\n asin = goal['asin']\n return asin \n","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate.get_sess_idx","uri":"program://BOLAA/function/web_run.evaluate.get_sess_idx#L105-L109","kind":"function","name":"get_sess_idx","path":"web_run/evaluate.py","language":"python","start_line":105,"end_line":109,"context_start_line":85,"context_end_line":129,"code":" if sess_idx in idx_score:\n if reward < idx_score[sess_idx]:\n continue\n idx_score[sess_idx] = reward\n idx_ref[sess_idx] = sess\n with open(file_name, 'w') as f:\n sort_idx = sorted(idx_ref.keys())\n for sess_idx in sort_idx:\n sess = idx_ref[sess_idx]\n json.dump(sess, f)\n f.write('\\n')\n \ndef get_file_sess(file_name):\n sessions = []\n with open(file_name) as f:\n for line in f:\n session = json.loads(line)\n sessions.append(session)\n return sessions\n\ndef get_sess_idx(session):\n step_id = session[-1][\"step_id\"]\n numbers = re.findall(r'\\d+', step_id)\n sess_idx, step_len = numbers\n return int(sess_idx)\n\ndef get_file_sess_idx(file_name):\n session_idx = []\n with open(file_name) as f:\n for line in f:\n session = json.loads(line)\n session_idx.append(get_sess_idx(session))\n return set(session_idx)\n\ndef get_goal_item(session):\n goal = session[0]\n asin = goal['asin']\n return asin \n\ndef get_session_items(session):\n items = []\n for step in session:\n if \"retrieved_items\" in step:\n items += step[\"retrieved_items\"]\n return items","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate.get_file_sess_idx","uri":"program://BOLAA/function/web_run.evaluate.get_file_sess_idx#L111-L117","kind":"function","name":"get_file_sess_idx","path":"web_run/evaluate.py","language":"python","start_line":111,"end_line":117,"context_start_line":91,"context_end_line":137,"code":" sort_idx = sorted(idx_ref.keys())\n for sess_idx in sort_idx:\n sess = idx_ref[sess_idx]\n json.dump(sess, f)\n f.write('\\n')\n \ndef get_file_sess(file_name):\n sessions = []\n with open(file_name) as f:\n for line in f:\n session = json.loads(line)\n sessions.append(session)\n return sessions\n\ndef get_sess_idx(session):\n step_id = session[-1][\"step_id\"]\n numbers = re.findall(r'\\d+', step_id)\n sess_idx, step_len = numbers\n return int(sess_idx)\n\ndef get_file_sess_idx(file_name):\n session_idx = []\n with open(file_name) as f:\n for line in f:\n session = json.loads(line)\n session_idx.append(get_sess_idx(session))\n return set(session_idx)\n\ndef get_goal_item(session):\n goal = session[0]\n asin = goal['asin']\n return asin \n\ndef get_session_items(session):\n items = []\n for step in session:\n if \"retrieved_items\" in step:\n items += step[\"retrieved_items\"]\n return items\n\ndef merge_sessions_by_llm(model_name, path = \"./execution_data/\"):\n file_list = []\n sessions = []\n for root, _, files in os.walk(path):\n for file_name in files:\n if model_name in file_name:\n file_list.append(os.path.join(root, file_name))","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate.get_goal_item","uri":"program://BOLAA/function/web_run.evaluate.get_goal_item#L119-L122","kind":"function","name":"get_goal_item","path":"web_run/evaluate.py","language":"python","start_line":119,"end_line":122,"context_start_line":99,"context_end_line":142,"code":" with open(file_name) as f:\n for line in f:\n session = json.loads(line)\n sessions.append(session)\n return sessions\n\ndef get_sess_idx(session):\n step_id = session[-1][\"step_id\"]\n numbers = re.findall(r'\\d+', step_id)\n sess_idx, step_len = numbers\n return int(sess_idx)\n\ndef get_file_sess_idx(file_name):\n session_idx = []\n with open(file_name) as f:\n for line in f:\n session = json.loads(line)\n session_idx.append(get_sess_idx(session))\n return set(session_idx)\n\ndef get_goal_item(session):\n goal = session[0]\n asin = goal['asin']\n return asin \n\ndef get_session_items(session):\n items = []\n for step in session:\n if \"retrieved_items\" in step:\n items += step[\"retrieved_items\"]\n return items\n\ndef merge_sessions_by_llm(model_name, path = \"./execution_data/\"):\n file_list = []\n sessions = []\n for root, _, files in os.walk(path):\n for file_name in files:\n if model_name in file_name:\n file_list.append(os.path.join(root, file_name))\n for f_name in file_list:\n with open(f_name) as f:\n for line in f:\n session = json.loads(line)\n sessions.append(session)","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate.get_session_items","uri":"program://BOLAA/function/web_run.evaluate.get_session_items#L124-L129","kind":"function","name":"get_session_items","path":"web_run/evaluate.py","language":"python","start_line":124,"end_line":129,"context_start_line":104,"context_end_line":149,"code":"\ndef get_sess_idx(session):\n step_id = session[-1][\"step_id\"]\n numbers = re.findall(r'\\d+', step_id)\n sess_idx, step_len = numbers\n return int(sess_idx)\n\ndef get_file_sess_idx(file_name):\n session_idx = []\n with open(file_name) as f:\n for line in f:\n session = json.loads(line)\n session_idx.append(get_sess_idx(session))\n return set(session_idx)\n\ndef get_goal_item(session):\n goal = session[0]\n asin = goal['asin']\n return asin \n\ndef get_session_items(session):\n items = []\n for step in session:\n if \"retrieved_items\" in step:\n items += step[\"retrieved_items\"]\n return items\n\ndef merge_sessions_by_llm(model_name, path = \"./execution_data/\"):\n file_list = []\n sessions = []\n for root, _, files in os.walk(path):\n for file_name in files:\n if model_name in file_name:\n file_list.append(os.path.join(root, file_name))\n for f_name in file_list:\n with open(f_name) as f:\n for line in f:\n session = json.loads(line)\n sessions.append(session)\n return sessions\n\ndef get_recall(sess):\n goal_item = get_goal_item(sess)\n retri_items = get_session_items(sess)\n if goal_item in retri_items:\n return 1","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate.merge_sessions_by_llm","uri":"program://BOLAA/function/web_run.evaluate.merge_sessions_by_llm#L131-L143","kind":"function","name":"merge_sessions_by_llm","path":"web_run/evaluate.py","language":"python","start_line":131,"end_line":143,"context_start_line":111,"context_end_line":163,"code":"def get_file_sess_idx(file_name):\n session_idx = []\n with open(file_name) as f:\n for line in f:\n session = json.loads(line)\n session_idx.append(get_sess_idx(session))\n return set(session_idx)\n\ndef get_goal_item(session):\n goal = session[0]\n asin = goal['asin']\n return asin \n\ndef get_session_items(session):\n items = []\n for step in session:\n if \"retrieved_items\" in step:\n items += step[\"retrieved_items\"]\n return items\n\ndef merge_sessions_by_llm(model_name, path = \"./execution_data/\"):\n file_list = []\n sessions = []\n for root, _, files in os.walk(path):\n for file_name in files:\n if model_name in file_name:\n file_list.append(os.path.join(root, file_name))\n for f_name in file_list:\n with open(f_name) as f:\n for line in f:\n session = json.loads(line)\n sessions.append(session)\n return sessions\n\ndef get_recall(sess):\n goal_item = get_goal_item(sess)\n retri_items = get_session_items(sess)\n if goal_item in retri_items:\n return 1\n else:\n return 0\n \ndef get_precision(sess):\n goal_item = get_goal_item(sess)\n retri_items = get_session_items(sess)\n if goal_item in retri_items:\n return 1/len(retri_items)\n else:\n return 0\n\ndef get_fail(sess):\n if \"observation\" in sess[-1]:\n if \"Your score (min 0.0, max 1.0):\" in sess[-1][\"observation\"]:","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate.get_recall","uri":"program://BOLAA/function/web_run.evaluate.get_recall#L145-L151","kind":"function","name":"get_recall","path":"web_run/evaluate.py","language":"python","start_line":145,"end_line":151,"context_start_line":125,"context_end_line":171,"code":" items = []\n for step in session:\n if \"retrieved_items\" in step:\n items += step[\"retrieved_items\"]\n return items\n\ndef merge_sessions_by_llm(model_name, path = \"./execution_data/\"):\n file_list = []\n sessions = []\n for root, _, files in os.walk(path):\n for file_name in files:\n if model_name in file_name:\n file_list.append(os.path.join(root, file_name))\n for f_name in file_list:\n with open(f_name) as f:\n for line in f:\n session = json.loads(line)\n sessions.append(session)\n return sessions\n\ndef get_recall(sess):\n goal_item = get_goal_item(sess)\n retri_items = get_session_items(sess)\n if goal_item in retri_items:\n return 1\n else:\n return 0\n \ndef get_precision(sess):\n goal_item = get_goal_item(sess)\n retri_items = get_session_items(sess)\n if goal_item in retri_items:\n return 1/len(retri_items)\n else:\n return 0\n\ndef get_fail(sess):\n if \"observation\" in sess[-1]:\n if \"Your score (min 0.0, max 1.0):\" in sess[-1][\"observation\"]:\n return 0\n return 1\n\ndef get_halluci(sess):\n halluci_step_idx = []\n for step in sess:\n if \"step_id\" in step:\n step_id = step[\"step_id\"]","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate.get_precision","uri":"program://BOLAA/function/web_run.evaluate.get_precision#L153-L159","kind":"function","name":"get_precision","path":"web_run/evaluate.py","language":"python","start_line":153,"end_line":159,"context_start_line":133,"context_end_line":179,"code":" sessions = []\n for root, _, files in os.walk(path):\n for file_name in files:\n if model_name in file_name:\n file_list.append(os.path.join(root, file_name))\n for f_name in file_list:\n with open(f_name) as f:\n for line in f:\n session = json.loads(line)\n sessions.append(session)\n return sessions\n\ndef get_recall(sess):\n goal_item = get_goal_item(sess)\n retri_items = get_session_items(sess)\n if goal_item in retri_items:\n return 1\n else:\n return 0\n \ndef get_precision(sess):\n goal_item = get_goal_item(sess)\n retri_items = get_session_items(sess)\n if goal_item in retri_items:\n return 1/len(retri_items)\n else:\n return 0\n\ndef get_fail(sess):\n if \"observation\" in sess[-1]:\n if \"Your score (min 0.0, max 1.0):\" in sess[-1][\"observation\"]:\n return 0\n return 1\n\ndef get_halluci(sess):\n halluci_step_idx = []\n for step in sess:\n if \"step_id\" in step:\n step_id = step[\"step_id\"]\n numbers = re.findall(r'\\d+', step_id)\n sess_idx, step_idx = numbers\n if \"observation\" in step:\n if \"Invalid action!\" in step[\"observation\"]:\n halluci_step_idx.append(step_idx)\n return halluci_step_idx\n \ndef eval_complexity(sessions, complexity_dict):","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate.get_fail","uri":"program://BOLAA/function/web_run.evaluate.get_fail#L161-L165","kind":"function","name":"get_fail","path":"web_run/evaluate.py","language":"python","start_line":161,"end_line":165,"context_start_line":141,"context_end_line":185,"code":" session = json.loads(line)\n sessions.append(session)\n return sessions\n\ndef get_recall(sess):\n goal_item = get_goal_item(sess)\n retri_items = get_session_items(sess)\n if goal_item in retri_items:\n return 1\n else:\n return 0\n \ndef get_precision(sess):\n goal_item = get_goal_item(sess)\n retri_items = get_session_items(sess)\n if goal_item in retri_items:\n return 1/len(retri_items)\n else:\n return 0\n\ndef get_fail(sess):\n if \"observation\" in sess[-1]:\n if \"Your score (min 0.0, max 1.0):\" in sess[-1][\"observation\"]:\n return 0\n return 1\n\ndef get_halluci(sess):\n halluci_step_idx = []\n for step in sess:\n if \"step_id\" in step:\n step_id = step[\"step_id\"]\n numbers = re.findall(r'\\d+', step_id)\n sess_idx, step_idx = numbers\n if \"observation\" in step:\n if \"Invalid action!\" in step[\"observation\"]:\n halluci_step_idx.append(step_idx)\n return halluci_step_idx\n \ndef eval_complexity(sessions, complexity_dict):\n complexity = []\n for sess in sessions:\n instruction = get_sess_ins(sess)\n if instruction.find(\", and price lower\") > 0:\n ins_key = instruction[:instruction.find(\", and price lower\")]\n else:","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate.get_halluci","uri":"program://BOLAA/function/web_run.evaluate.get_halluci#L167-L177","kind":"function","name":"get_halluci","path":"web_run/evaluate.py","language":"python","start_line":167,"end_line":177,"context_start_line":147,"context_end_line":197,"code":" retri_items = get_session_items(sess)\n if goal_item in retri_items:\n return 1\n else:\n return 0\n \ndef get_precision(sess):\n goal_item = get_goal_item(sess)\n retri_items = get_session_items(sess)\n if goal_item in retri_items:\n return 1/len(retri_items)\n else:\n return 0\n\ndef get_fail(sess):\n if \"observation\" in sess[-1]:\n if \"Your score (min 0.0, max 1.0):\" in sess[-1][\"observation\"]:\n return 0\n return 1\n\ndef get_halluci(sess):\n halluci_step_idx = []\n for step in sess:\n if \"step_id\" in step:\n step_id = step[\"step_id\"]\n numbers = re.findall(r'\\d+', step_id)\n sess_idx, step_idx = numbers\n if \"observation\" in step:\n if \"Invalid action!\" in step[\"observation\"]:\n halluci_step_idx.append(step_idx)\n return halluci_step_idx\n \ndef eval_complexity(sessions, complexity_dict):\n complexity = []\n for sess in sessions:\n instruction = get_sess_ins(sess)\n if instruction.find(\", and price lower\") > 0:\n ins_key = instruction[:instruction.find(\", and price lower\")]\n else:\n ins_key = instruction\n if ins_key in complexity_dict:\n attr_complexity, option_complexity = complexity_dict[ins_key]\n else:\n print(\"no complexity for \", ins_key)\n complexity.append(attr_complexity + option_complexity)\n return complexity\n\ndef eval_success(sessions) -> list:\n success = []\n for sess in sessions:\n r = get_reward(sess)","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate.eval_complexity","uri":"program://BOLAA/function/web_run.evaluate.eval_complexity#L179-L192","kind":"function","name":"eval_complexity","path":"web_run/evaluate.py","language":"python","start_line":179,"end_line":192,"context_start_line":159,"context_end_line":212,"code":" return 0\n\ndef get_fail(sess):\n if \"observation\" in sess[-1]:\n if \"Your score (min 0.0, max 1.0):\" in sess[-1][\"observation\"]:\n return 0\n return 1\n\ndef get_halluci(sess):\n halluci_step_idx = []\n for step in sess:\n if \"step_id\" in step:\n step_id = step[\"step_id\"]\n numbers = re.findall(r'\\d+', step_id)\n sess_idx, step_idx = numbers\n if \"observation\" in step:\n if \"Invalid action!\" in step[\"observation\"]:\n halluci_step_idx.append(step_idx)\n return halluci_step_idx\n \ndef eval_complexity(sessions, complexity_dict):\n complexity = []\n for sess in sessions:\n instruction = get_sess_ins(sess)\n if instruction.find(\", and price lower\") > 0:\n ins_key = instruction[:instruction.find(\", and price lower\")]\n else:\n ins_key = instruction\n if ins_key in complexity_dict:\n attr_complexity, option_complexity = complexity_dict[ins_key]\n else:\n print(\"no complexity for \", ins_key)\n complexity.append(attr_complexity + option_complexity)\n return complexity\n\ndef eval_success(sessions) -> list:\n success = []\n for sess in sessions:\n r = get_reward(sess)\n if r >= 1:\n success.append(1)\n else:\n success.append(0)\n return success \n\ndef eval_initial_halluci(sessions) -> list:\n initial_halluci = []\n for sess in sessions:\n initial_halluci.append(get_halluci(sess)[0])\n return initial_halluci\n\ndef eval_avg_halluci(sessions) -> list:\n avg_halluci = []\n for sess in sessions:","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate.eval_success","uri":"program://BOLAA/function/web_run.evaluate.eval_success#L194-L202","kind":"function","name":"eval_success","path":"web_run/evaluate.py","language":"python","start_line":194,"end_line":202,"context_start_line":174,"context_end_line":222,"code":" if \"observation\" in step:\n if \"Invalid action!\" in step[\"observation\"]:\n halluci_step_idx.append(step_idx)\n return halluci_step_idx\n \ndef eval_complexity(sessions, complexity_dict):\n complexity = []\n for sess in sessions:\n instruction = get_sess_ins(sess)\n if instruction.find(\", and price lower\") > 0:\n ins_key = instruction[:instruction.find(\", and price lower\")]\n else:\n ins_key = instruction\n if ins_key in complexity_dict:\n attr_complexity, option_complexity = complexity_dict[ins_key]\n else:\n print(\"no complexity for \", ins_key)\n complexity.append(attr_complexity + option_complexity)\n return complexity\n\ndef eval_success(sessions) -> list:\n success = []\n for sess in sessions:\n r = get_reward(sess)\n if r >= 1:\n success.append(1)\n else:\n success.append(0)\n return success \n\ndef eval_initial_halluci(sessions) -> list:\n initial_halluci = []\n for sess in sessions:\n initial_halluci.append(get_halluci(sess)[0])\n return initial_halluci\n\ndef eval_avg_halluci(sessions) -> list:\n avg_halluci = []\n for sess in sessions:\n halluci = get_halluci(sess)\n avg_halluci.append(sum(halluci)/len(halluci))\n return avg_halluci\n\ndef eval_fail(sessions) -> list:\n fail_list = [get_fail(sess) for sess in sessions]\n return fail_list\n\ndef eval_reward(sessions) -> list:\n reward = []","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate.eval_initial_halluci","uri":"program://BOLAA/function/web_run.evaluate.eval_initial_halluci#L204-L208","kind":"function","name":"eval_initial_halluci","path":"web_run/evaluate.py","language":"python","start_line":204,"end_line":208,"context_start_line":184,"context_end_line":228,"code":" ins_key = instruction[:instruction.find(\", and price lower\")]\n else:\n ins_key = instruction\n if ins_key in complexity_dict:\n attr_complexity, option_complexity = complexity_dict[ins_key]\n else:\n print(\"no complexity for \", ins_key)\n complexity.append(attr_complexity + option_complexity)\n return complexity\n\ndef eval_success(sessions) -> list:\n success = []\n for sess in sessions:\n r = get_reward(sess)\n if r >= 1:\n success.append(1)\n else:\n success.append(0)\n return success \n\ndef eval_initial_halluci(sessions) -> list:\n initial_halluci = []\n for sess in sessions:\n initial_halluci.append(get_halluci(sess)[0])\n return initial_halluci\n\ndef eval_avg_halluci(sessions) -> list:\n avg_halluci = []\n for sess in sessions:\n halluci = get_halluci(sess)\n avg_halluci.append(sum(halluci)/len(halluci))\n return avg_halluci\n\ndef eval_fail(sessions) -> list:\n fail_list = [get_fail(sess) for sess in sessions]\n return fail_list\n\ndef eval_reward(sessions) -> list:\n reward = []\n for sess in sessions:\n reward.append(get_reward(sess))\n return reward\n\ndef eval_recall(sessions) -> list:\n recall = [get_recall(sess) for sess in sessions]","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate.eval_avg_halluci","uri":"program://BOLAA/function/web_run.evaluate.eval_avg_halluci#L210-L215","kind":"function","name":"eval_avg_halluci","path":"web_run/evaluate.py","language":"python","start_line":210,"end_line":215,"context_start_line":190,"context_end_line":235,"code":" print(\"no complexity for \", ins_key)\n complexity.append(attr_complexity + option_complexity)\n return complexity\n\ndef eval_success(sessions) -> list:\n success = []\n for sess in sessions:\n r = get_reward(sess)\n if r >= 1:\n success.append(1)\n else:\n success.append(0)\n return success \n\ndef eval_initial_halluci(sessions) -> list:\n initial_halluci = []\n for sess in sessions:\n initial_halluci.append(get_halluci(sess)[0])\n return initial_halluci\n\ndef eval_avg_halluci(sessions) -> list:\n avg_halluci = []\n for sess in sessions:\n halluci = get_halluci(sess)\n avg_halluci.append(sum(halluci)/len(halluci))\n return avg_halluci\n\ndef eval_fail(sessions) -> list:\n fail_list = [get_fail(sess) for sess in sessions]\n return fail_list\n\ndef eval_reward(sessions) -> list:\n reward = []\n for sess in sessions:\n reward.append(get_reward(sess))\n return reward\n\ndef eval_recall(sessions) -> list:\n recall = [get_recall(sess) for sess in sessions]\n return recall\n\ndef eval_precision(sessions) -> list:\n prec = [get_precision(sess) for sess in sessions]\n return prec\n\ndef y_wrt_x_rel(x, y):","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate.eval_fail","uri":"program://BOLAA/function/web_run.evaluate.eval_fail#L217-L219","kind":"function","name":"eval_fail","path":"web_run/evaluate.py","language":"python","start_line":217,"end_line":219,"context_start_line":197,"context_end_line":239,"code":" r = get_reward(sess)\n if r >= 1:\n success.append(1)\n else:\n success.append(0)\n return success \n\ndef eval_initial_halluci(sessions) -> list:\n initial_halluci = []\n for sess in sessions:\n initial_halluci.append(get_halluci(sess)[0])\n return initial_halluci\n\ndef eval_avg_halluci(sessions) -> list:\n avg_halluci = []\n for sess in sessions:\n halluci = get_halluci(sess)\n avg_halluci.append(sum(halluci)/len(halluci))\n return avg_halluci\n\ndef eval_fail(sessions) -> list:\n fail_list = [get_fail(sess) for sess in sessions]\n return fail_list\n\ndef eval_reward(sessions) -> list:\n reward = []\n for sess in sessions:\n reward.append(get_reward(sess))\n return reward\n\ndef eval_recall(sessions) -> list:\n recall = [get_recall(sess) for sess in sessions]\n return recall\n\ndef eval_precision(sessions) -> list:\n prec = [get_precision(sess) for sess in sessions]\n return prec\n\ndef y_wrt_x_rel(x, y):\n x_dict = defaultdict(list)\n for idx, c in enumerate(x):\n x_dict[c].append(y[idx])\n x_dict_y = {key:round(sum(val)/len(val), 4) for key, val in x_dict.items()}","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate.eval_reward","uri":"program://BOLAA/function/web_run.evaluate.eval_reward#L221-L225","kind":"function","name":"eval_reward","path":"web_run/evaluate.py","language":"python","start_line":221,"end_line":225,"context_start_line":201,"context_end_line":245,"code":" success.append(0)\n return success \n\ndef eval_initial_halluci(sessions) -> list:\n initial_halluci = []\n for sess in sessions:\n initial_halluci.append(get_halluci(sess)[0])\n return initial_halluci\n\ndef eval_avg_halluci(sessions) -> list:\n avg_halluci = []\n for sess in sessions:\n halluci = get_halluci(sess)\n avg_halluci.append(sum(halluci)/len(halluci))\n return avg_halluci\n\ndef eval_fail(sessions) -> list:\n fail_list = [get_fail(sess) for sess in sessions]\n return fail_list\n\ndef eval_reward(sessions) -> list:\n reward = []\n for sess in sessions:\n reward.append(get_reward(sess))\n return reward\n\ndef eval_recall(sessions) -> list:\n recall = [get_recall(sess) for sess in sessions]\n return recall\n\ndef eval_precision(sessions) -> list:\n prec = [get_precision(sess) for sess in sessions]\n return prec\n\ndef y_wrt_x_rel(x, y):\n x_dict = defaultdict(list)\n for idx, c in enumerate(x):\n x_dict[c].append(y[idx])\n x_dict_y = {key:round(sum(val)/len(val), 4) for key, val in x_dict.items()}\n return x_dict_y\n\ndef get_all_eval_values(llm_name):\n agent_types = available_agent_names\n for a_type in agent_types:\n get_eval_values(llm_name, a_type)","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate.eval_recall","uri":"program://BOLAA/function/web_run.evaluate.eval_recall#L227-L229","kind":"function","name":"eval_recall","path":"web_run/evaluate.py","language":"python","start_line":227,"end_line":229,"context_start_line":207,"context_end_line":249,"code":" initial_halluci.append(get_halluci(sess)[0])\n return initial_halluci\n\ndef eval_avg_halluci(sessions) -> list:\n avg_halluci = []\n for sess in sessions:\n halluci = get_halluci(sess)\n avg_halluci.append(sum(halluci)/len(halluci))\n return avg_halluci\n\ndef eval_fail(sessions) -> list:\n fail_list = [get_fail(sess) for sess in sessions]\n return fail_list\n\ndef eval_reward(sessions) -> list:\n reward = []\n for sess in sessions:\n reward.append(get_reward(sess))\n return reward\n\ndef eval_recall(sessions) -> list:\n recall = [get_recall(sess) for sess in sessions]\n return recall\n\ndef eval_precision(sessions) -> list:\n prec = [get_precision(sess) for sess in sessions]\n return prec\n\ndef y_wrt_x_rel(x, y):\n x_dict = defaultdict(list)\n for idx, c in enumerate(x):\n x_dict[c].append(y[idx])\n x_dict_y = {key:round(sum(val)/len(val), 4) for key, val in x_dict.items()}\n return x_dict_y\n\ndef get_all_eval_values(llm_name):\n agent_types = available_agent_names\n for a_type in agent_types:\n get_eval_values(llm_name, a_type)\n \ndef get_eval_values(llm_name, agent_type, path=\"./execution_data/\"):\n file_name = f\"{agent_type}_{llm_name}_batch.json\"\n file_name = os.path.join(path, file_name)","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate.eval_precision","uri":"program://BOLAA/function/web_run.evaluate.eval_precision#L231-L233","kind":"function","name":"eval_precision","path":"web_run/evaluate.py","language":"python","start_line":231,"end_line":233,"context_start_line":211,"context_end_line":253,"code":" avg_halluci = []\n for sess in sessions:\n halluci = get_halluci(sess)\n avg_halluci.append(sum(halluci)/len(halluci))\n return avg_halluci\n\ndef eval_fail(sessions) -> list:\n fail_list = [get_fail(sess) for sess in sessions]\n return fail_list\n\ndef eval_reward(sessions) -> list:\n reward = []\n for sess in sessions:\n reward.append(get_reward(sess))\n return reward\n\ndef eval_recall(sessions) -> list:\n recall = [get_recall(sess) for sess in sessions]\n return recall\n\ndef eval_precision(sessions) -> list:\n prec = [get_precision(sess) for sess in sessions]\n return prec\n\ndef y_wrt_x_rel(x, y):\n x_dict = defaultdict(list)\n for idx, c in enumerate(x):\n x_dict[c].append(y[idx])\n x_dict_y = {key:round(sum(val)/len(val), 4) for key, val in x_dict.items()}\n return x_dict_y\n\ndef get_all_eval_values(llm_name):\n agent_types = available_agent_names\n for a_type in agent_types:\n get_eval_values(llm_name, a_type)\n \ndef get_eval_values(llm_name, agent_type, path=\"./execution_data/\"):\n file_name = f\"{agent_type}_{llm_name}_batch.json\"\n file_name = os.path.join(path, file_name)\n delete_repeat(file_name)\n session_idx = get_file_sess_idx(file_name)\n assert len(session_idx) == 900\n sessions = get_file_sess(file_name)","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate.y_wrt_x_rel","uri":"program://BOLAA/function/web_run.evaluate.y_wrt_x_rel#L235-L240","kind":"function","name":"y_wrt_x_rel","path":"web_run/evaluate.py","language":"python","start_line":235,"end_line":240,"context_start_line":215,"context_end_line":260,"code":" return avg_halluci\n\ndef eval_fail(sessions) -> list:\n fail_list = [get_fail(sess) for sess in sessions]\n return fail_list\n\ndef eval_reward(sessions) -> list:\n reward = []\n for sess in sessions:\n reward.append(get_reward(sess))\n return reward\n\ndef eval_recall(sessions) -> list:\n recall = [get_recall(sess) for sess in sessions]\n return recall\n\ndef eval_precision(sessions) -> list:\n prec = [get_precision(sess) for sess in sessions]\n return prec\n\ndef y_wrt_x_rel(x, y):\n x_dict = defaultdict(list)\n for idx, c in enumerate(x):\n x_dict[c].append(y[idx])\n x_dict_y = {key:round(sum(val)/len(val), 4) for key, val in x_dict.items()}\n return x_dict_y\n\ndef get_all_eval_values(llm_name):\n agent_types = available_agent_names\n for a_type in agent_types:\n get_eval_values(llm_name, a_type)\n \ndef get_eval_values(llm_name, agent_type, path=\"./execution_data/\"):\n file_name = f\"{agent_type}_{llm_name}_batch.json\"\n file_name = os.path.join(path, file_name)\n delete_repeat(file_name)\n session_idx = get_file_sess_idx(file_name)\n assert len(session_idx) == 900\n sessions = get_file_sess(file_name)\n # print(len(sessions))\n recalls = eval_recall(sessions)\n rewards = eval_reward(sessions)\n precisions = eval_precision(sessions)\n success = eval_success(sessions)\n fail = eval_fail(sessions)\n avg_reward = round(sum(rewards)/len(rewards), 4)","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate.get_all_eval_values","uri":"program://BOLAA/function/web_run.evaluate.get_all_eval_values#L242-L245","kind":"function","name":"get_all_eval_values","path":"web_run/evaluate.py","language":"python","start_line":242,"end_line":245,"context_start_line":222,"context_end_line":265,"code":" reward = []\n for sess in sessions:\n reward.append(get_reward(sess))\n return reward\n\ndef eval_recall(sessions) -> list:\n recall = [get_recall(sess) for sess in sessions]\n return recall\n\ndef eval_precision(sessions) -> list:\n prec = [get_precision(sess) for sess in sessions]\n return prec\n\ndef y_wrt_x_rel(x, y):\n x_dict = defaultdict(list)\n for idx, c in enumerate(x):\n x_dict[c].append(y[idx])\n x_dict_y = {key:round(sum(val)/len(val), 4) for key, val in x_dict.items()}\n return x_dict_y\n\ndef get_all_eval_values(llm_name):\n agent_types = available_agent_names\n for a_type in agent_types:\n get_eval_values(llm_name, a_type)\n \ndef get_eval_values(llm_name, agent_type, path=\"./execution_data/\"):\n file_name = f\"{agent_type}_{llm_name}_batch.json\"\n file_name = os.path.join(path, file_name)\n delete_repeat(file_name)\n session_idx = get_file_sess_idx(file_name)\n assert len(session_idx) == 900\n sessions = get_file_sess(file_name)\n # print(len(sessions))\n recalls = eval_recall(sessions)\n rewards = eval_reward(sessions)\n precisions = eval_precision(sessions)\n success = eval_success(sessions)\n fail = eval_fail(sessions)\n avg_reward = round(sum(rewards)/len(rewards), 4)\n success_rate = round(sum(success)/len(success), 4)\n fail_rate = round(sum(fail)/len(success), 4)\n avg_recall = round(sum(recalls)/len(recalls), 4)\n avg_prec = round(sum(precisions)/len(precisions), 4)\n print(f\"{avg_reward}\\t{success_rate}\\t{fail_rate}\\t{avg_recall}\\t{avg_prec}\")","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.evaluate.get_eval_values","uri":"program://BOLAA/function/web_run.evaluate.get_eval_values#L247-L265","kind":"function","name":"get_eval_values","path":"web_run/evaluate.py","language":"python","start_line":247,"end_line":265,"context_start_line":227,"context_end_line":265,"code":"def eval_recall(sessions) -> list:\n recall = [get_recall(sess) for sess in sessions]\n return recall\n\ndef eval_precision(sessions) -> list:\n prec = [get_precision(sess) for sess in sessions]\n return prec\n\ndef y_wrt_x_rel(x, y):\n x_dict = defaultdict(list)\n for idx, c in enumerate(x):\n x_dict[c].append(y[idx])\n x_dict_y = {key:round(sum(val)/len(val), 4) for key, val in x_dict.items()}\n return x_dict_y\n\ndef get_all_eval_values(llm_name):\n agent_types = available_agent_names\n for a_type in agent_types:\n get_eval_values(llm_name, a_type)\n \ndef get_eval_values(llm_name, agent_type, path=\"./execution_data/\"):\n file_name = f\"{agent_type}_{llm_name}_batch.json\"\n file_name = os.path.join(path, file_name)\n delete_repeat(file_name)\n session_idx = get_file_sess_idx(file_name)\n assert len(session_idx) == 900\n sessions = get_file_sess(file_name)\n # print(len(sessions))\n recalls = eval_recall(sessions)\n rewards = eval_reward(sessions)\n precisions = eval_precision(sessions)\n success = eval_success(sessions)\n fail = eval_fail(sessions)\n avg_reward = round(sum(rewards)/len(rewards), 4)\n success_rate = round(sum(success)/len(success), 4)\n fail_rate = round(sum(fail)/len(success), 4)\n avg_recall = round(sum(recalls)/len(recalls), 4)\n avg_prec = round(sum(precisions)/len(precisions), 4)\n print(f\"{avg_reward}\\t{success_rate}\\t{fail_rate}\\t{avg_recall}\\t{avg_prec}\")","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.llms","uri":"program://BOLAA/module/web_run.llms#L1-L80","kind":"module","name":"web_run.llms","path":"web_run/llms.py","language":"python","start_line":1,"end_line":80,"context_start_line":1,"context_end_line":80,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport os\nimport sys\nimport json\nimport random\nimport tiktoken\ntoken_enc = tiktoken.get_encoding(\"cl100k_base\")\nimport openai\nfrom langchain import PromptTemplate, OpenAI, LLMChain\nfrom transformers import AutoTokenizer, AutoModelForCausalLM\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.chains import LLMChain\nfrom langchain import PromptTemplate\nfrom langchain.prompts.chat import (\n ChatPromptTemplate,\n SystemMessagePromptTemplate,\n AIMessagePromptTemplate,\n HumanMessagePromptTemplate,\n)\nfrom web_run.config import OPENAI_API_KEY\n\nOPENAI_CHAT_MODELS = [\"gpt-3.5-turbo\",\"gpt-3.5-turbo-16k-0613\",\"gpt-3.5-turbo-16k\",\"gpt-4-0613\",\"gpt-4-32k-0613\"]\nOPENAI_LLM_MODELS = [\"text-davinci-003\",\"text-ada-001\"]\nFASTCHAT_MODELS = [\"vicuna-7b\"]\n\n \nclass langchain_openai_chatllm:\n def __init__(self, llm_name):\n openai.api_key = OPENAI_API_KEY\n self.llm_name = llm_name\n human_template=\"{prompt}\"\n human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)\n self.chat_prompt = ChatPromptTemplate.from_messages([human_message_prompt])\n \n def run(self, prompt, temperature=1, stop=['\\n'], max_tokens=128):\n chat = ChatOpenAI(model=self.llm_name, temperature=temperature, stop=stop, max_tokens=max_tokens)\n self.chain = LLMChain(llm=chat, prompt=self.chat_prompt)\n return self.chain.run(prompt)\n \nclass langchain_openai_llm:\n def __init__(self, llm_name):\n openai.api_key = OPENAI_API_KEY\n self.prompt_temp = PromptTemplate(\n input_variables=[\"prompt\"], template=\"{prompt}\"\n )\n self.llm_name = llm_name\n \n def run(self, prompt, temperature=0.9, stop=['\\n'], max_tokens=128):\n llm = OpenAI(model=self.llm_name, temperature=temperature, stop=['\\n'], max_tokens=max_tokens)\n chain = LLMChain(llm=llm, prompt=self.prompt_temp)\n return chain.run(prompt)\n\n\nclass langchain_fastchat_llm:\n def __init__(self, llm_name):\n openai.api_key = \"EMPTY\" # Not support yet\n openai.api_base = \"http://localhost:8000/v1\"\n self.prompt_temp = PromptTemplate(\n input_variables=[\"prompt\"], template=\"{prompt}\"\n )\n self.llm_name = llm_name\n \n def run(self, prompt, temperature=0.9, stop=['\\n'], max_tokens=128):\n llm = OpenAI(model=self.llm_name, temperature=temperature, stop=['\\n'], max_tokens=max_tokens)\n chain = LLMChain(llm=llm, prompt=self.prompt_temp)\n return chain.run(prompt)\n\ndef get_llm_backend(llm_name):\n if llm_name in OPENAI_CHAT_MODELS:\n return langchain_openai_chatllm(llm_name)\n elif llm_name in OPENAI_LLM_MODELS:\n return langchain_openai_llm(llm_name)\n else:\n return langchain_fastchat_llm(llm_name)","source_hash":"e8dadcd5c975227c22060fdc5519cc6907b63536aec6f5814eafb56dd95eef88","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.llms.langchain_openai_chatllm","uri":"program://BOLAA/class/web_run.llms.langchain_openai_chatllm#L33-L44","kind":"class","name":"langchain_openai_chatllm","path":"web_run/llms.py","language":"python","start_line":33,"end_line":44,"context_start_line":13,"context_end_line":64,"code":"token_enc = tiktoken.get_encoding(\"cl100k_base\")\nimport openai\nfrom langchain import PromptTemplate, OpenAI, LLMChain\nfrom transformers import AutoTokenizer, AutoModelForCausalLM\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.chains import LLMChain\nfrom langchain import PromptTemplate\nfrom langchain.prompts.chat import (\n ChatPromptTemplate,\n SystemMessagePromptTemplate,\n AIMessagePromptTemplate,\n HumanMessagePromptTemplate,\n)\nfrom web_run.config import OPENAI_API_KEY\n\nOPENAI_CHAT_MODELS = [\"gpt-3.5-turbo\",\"gpt-3.5-turbo-16k-0613\",\"gpt-3.5-turbo-16k\",\"gpt-4-0613\",\"gpt-4-32k-0613\"]\nOPENAI_LLM_MODELS = [\"text-davinci-003\",\"text-ada-001\"]\nFASTCHAT_MODELS = [\"vicuna-7b\"]\n\n \nclass langchain_openai_chatllm:\n def __init__(self, llm_name):\n openai.api_key = OPENAI_API_KEY\n self.llm_name = llm_name\n human_template=\"{prompt}\"\n human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)\n self.chat_prompt = ChatPromptTemplate.from_messages([human_message_prompt])\n \n def run(self, prompt, temperature=1, stop=['\\n'], max_tokens=128):\n chat = ChatOpenAI(model=self.llm_name, temperature=temperature, stop=stop, max_tokens=max_tokens)\n self.chain = LLMChain(llm=chat, prompt=self.chat_prompt)\n return self.chain.run(prompt)\n \nclass langchain_openai_llm:\n def __init__(self, llm_name):\n openai.api_key = OPENAI_API_KEY\n self.prompt_temp = PromptTemplate(\n input_variables=[\"prompt\"], template=\"{prompt}\"\n )\n self.llm_name = llm_name\n \n def run(self, prompt, temperature=0.9, stop=['\\n'], max_tokens=128):\n llm = OpenAI(model=self.llm_name, temperature=temperature, stop=['\\n'], max_tokens=max_tokens)\n chain = LLMChain(llm=llm, prompt=self.prompt_temp)\n return chain.run(prompt)\n\n\nclass langchain_fastchat_llm:\n def __init__(self, llm_name):\n openai.api_key = \"EMPTY\" # Not support yet\n openai.api_base = \"http://localhost:8000/v1\"\n self.prompt_temp = PromptTemplate(","source_hash":"e8dadcd5c975227c22060fdc5519cc6907b63536aec6f5814eafb56dd95eef88","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.llms.langchain_openai_llm","uri":"program://BOLAA/class/web_run.llms.langchain_openai_llm#L46-L57","kind":"class","name":"langchain_openai_llm","path":"web_run/llms.py","language":"python","start_line":46,"end_line":57,"context_start_line":26,"context_end_line":77,"code":"from web_run.config import OPENAI_API_KEY\n\nOPENAI_CHAT_MODELS = [\"gpt-3.5-turbo\",\"gpt-3.5-turbo-16k-0613\",\"gpt-3.5-turbo-16k\",\"gpt-4-0613\",\"gpt-4-32k-0613\"]\nOPENAI_LLM_MODELS = [\"text-davinci-003\",\"text-ada-001\"]\nFASTCHAT_MODELS = [\"vicuna-7b\"]\n\n \nclass langchain_openai_chatllm:\n def __init__(self, llm_name):\n openai.api_key = OPENAI_API_KEY\n self.llm_name = llm_name\n human_template=\"{prompt}\"\n human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)\n self.chat_prompt = ChatPromptTemplate.from_messages([human_message_prompt])\n \n def run(self, prompt, temperature=1, stop=['\\n'], max_tokens=128):\n chat = ChatOpenAI(model=self.llm_name, temperature=temperature, stop=stop, max_tokens=max_tokens)\n self.chain = LLMChain(llm=chat, prompt=self.chat_prompt)\n return self.chain.run(prompt)\n \nclass langchain_openai_llm:\n def __init__(self, llm_name):\n openai.api_key = OPENAI_API_KEY\n self.prompt_temp = PromptTemplate(\n input_variables=[\"prompt\"], template=\"{prompt}\"\n )\n self.llm_name = llm_name\n \n def run(self, prompt, temperature=0.9, stop=['\\n'], max_tokens=128):\n llm = OpenAI(model=self.llm_name, temperature=temperature, stop=['\\n'], max_tokens=max_tokens)\n chain = LLMChain(llm=llm, prompt=self.prompt_temp)\n return chain.run(prompt)\n\n\nclass langchain_fastchat_llm:\n def __init__(self, llm_name):\n openai.api_key = \"EMPTY\" # Not support yet\n openai.api_base = \"http://localhost:8000/v1\"\n self.prompt_temp = PromptTemplate(\n input_variables=[\"prompt\"], template=\"{prompt}\"\n )\n self.llm_name = llm_name\n \n def run(self, prompt, temperature=0.9, stop=['\\n'], max_tokens=128):\n llm = OpenAI(model=self.llm_name, temperature=temperature, stop=['\\n'], max_tokens=max_tokens)\n chain = LLMChain(llm=llm, prompt=self.prompt_temp)\n return chain.run(prompt)\n\ndef get_llm_backend(llm_name):\n if llm_name in OPENAI_CHAT_MODELS:\n return langchain_openai_chatllm(llm_name)\n elif llm_name in OPENAI_LLM_MODELS:","source_hash":"e8dadcd5c975227c22060fdc5519cc6907b63536aec6f5814eafb56dd95eef88","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.llms.langchain_fastchat_llm","uri":"program://BOLAA/class/web_run.llms.langchain_fastchat_llm#L60-L72","kind":"class","name":"langchain_fastchat_llm","path":"web_run/llms.py","language":"python","start_line":60,"end_line":72,"context_start_line":40,"context_end_line":80,"code":" \n def run(self, prompt, temperature=1, stop=['\\n'], max_tokens=128):\n chat = ChatOpenAI(model=self.llm_name, temperature=temperature, stop=stop, max_tokens=max_tokens)\n self.chain = LLMChain(llm=chat, prompt=self.chat_prompt)\n return self.chain.run(prompt)\n \nclass langchain_openai_llm:\n def __init__(self, llm_name):\n openai.api_key = OPENAI_API_KEY\n self.prompt_temp = PromptTemplate(\n input_variables=[\"prompt\"], template=\"{prompt}\"\n )\n self.llm_name = llm_name\n \n def run(self, prompt, temperature=0.9, stop=['\\n'], max_tokens=128):\n llm = OpenAI(model=self.llm_name, temperature=temperature, stop=['\\n'], max_tokens=max_tokens)\n chain = LLMChain(llm=llm, prompt=self.prompt_temp)\n return chain.run(prompt)\n\n\nclass langchain_fastchat_llm:\n def __init__(self, llm_name):\n openai.api_key = \"EMPTY\" # Not support yet\n openai.api_base = \"http://localhost:8000/v1\"\n self.prompt_temp = PromptTemplate(\n input_variables=[\"prompt\"], template=\"{prompt}\"\n )\n self.llm_name = llm_name\n \n def run(self, prompt, temperature=0.9, stop=['\\n'], max_tokens=128):\n llm = OpenAI(model=self.llm_name, temperature=temperature, stop=['\\n'], max_tokens=max_tokens)\n chain = LLMChain(llm=llm, prompt=self.prompt_temp)\n return chain.run(prompt)\n\ndef get_llm_backend(llm_name):\n if llm_name in OPENAI_CHAT_MODELS:\n return langchain_openai_chatllm(llm_name)\n elif llm_name in OPENAI_LLM_MODELS:\n return langchain_openai_llm(llm_name)\n else:\n return langchain_fastchat_llm(llm_name)","source_hash":"e8dadcd5c975227c22060fdc5519cc6907b63536aec6f5814eafb56dd95eef88","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.llms.get_llm_backend","uri":"program://BOLAA/function/web_run.llms.get_llm_backend#L74-L80","kind":"function","name":"get_llm_backend","path":"web_run/llms.py","language":"python","start_line":74,"end_line":80,"context_start_line":54,"context_end_line":80,"code":" def run(self, prompt, temperature=0.9, stop=['\\n'], max_tokens=128):\n llm = OpenAI(model=self.llm_name, temperature=temperature, stop=['\\n'], max_tokens=max_tokens)\n chain = LLMChain(llm=llm, prompt=self.prompt_temp)\n return chain.run(prompt)\n\n\nclass langchain_fastchat_llm:\n def __init__(self, llm_name):\n openai.api_key = \"EMPTY\" # Not support yet\n openai.api_base = \"http://localhost:8000/v1\"\n self.prompt_temp = PromptTemplate(\n input_variables=[\"prompt\"], template=\"{prompt}\"\n )\n self.llm_name = llm_name\n \n def run(self, prompt, temperature=0.9, stop=['\\n'], max_tokens=128):\n llm = OpenAI(model=self.llm_name, temperature=temperature, stop=['\\n'], max_tokens=max_tokens)\n chain = LLMChain(llm=llm, prompt=self.prompt_temp)\n return chain.run(prompt)\n\ndef get_llm_backend(llm_name):\n if llm_name in OPENAI_CHAT_MODELS:\n return langchain_openai_chatllm(llm_name)\n elif llm_name in OPENAI_LLM_MODELS:\n return langchain_openai_llm(llm_name)\n else:\n return langchain_fastchat_llm(llm_name)","source_hash":"e8dadcd5c975227c22060fdc5519cc6907b63536aec6f5814eafb56dd95eef88","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.llms.__init__","uri":"program://BOLAA/function/web_run.llms.__init__#L61-L67","kind":"function","name":"__init__","path":"web_run/llms.py","language":"python","start_line":61,"end_line":67,"context_start_line":41,"context_end_line":80,"code":" def run(self, prompt, temperature=1, stop=['\\n'], max_tokens=128):\n chat = ChatOpenAI(model=self.llm_name, temperature=temperature, stop=stop, max_tokens=max_tokens)\n self.chain = LLMChain(llm=chat, prompt=self.chat_prompt)\n return self.chain.run(prompt)\n \nclass langchain_openai_llm:\n def __init__(self, llm_name):\n openai.api_key = OPENAI_API_KEY\n self.prompt_temp = PromptTemplate(\n input_variables=[\"prompt\"], template=\"{prompt}\"\n )\n self.llm_name = llm_name\n \n def run(self, prompt, temperature=0.9, stop=['\\n'], max_tokens=128):\n llm = OpenAI(model=self.llm_name, temperature=temperature, stop=['\\n'], max_tokens=max_tokens)\n chain = LLMChain(llm=llm, prompt=self.prompt_temp)\n return chain.run(prompt)\n\n\nclass langchain_fastchat_llm:\n def __init__(self, llm_name):\n openai.api_key = \"EMPTY\" # Not support yet\n openai.api_base = \"http://localhost:8000/v1\"\n self.prompt_temp = PromptTemplate(\n input_variables=[\"prompt\"], template=\"{prompt}\"\n )\n self.llm_name = llm_name\n \n def run(self, prompt, temperature=0.9, stop=['\\n'], max_tokens=128):\n llm = OpenAI(model=self.llm_name, temperature=temperature, stop=['\\n'], max_tokens=max_tokens)\n chain = LLMChain(llm=llm, prompt=self.prompt_temp)\n return chain.run(prompt)\n\ndef get_llm_backend(llm_name):\n if llm_name in OPENAI_CHAT_MODELS:\n return langchain_openai_chatllm(llm_name)\n elif llm_name in OPENAI_LLM_MODELS:\n return langchain_openai_llm(llm_name)\n else:\n return langchain_fastchat_llm(llm_name)","source_hash":"e8dadcd5c975227c22060fdc5519cc6907b63536aec6f5814eafb56dd95eef88","truncated":false} {"repo_id":"BOLAA","entity_id":"py:web_run.llms.run","uri":"program://BOLAA/function/web_run.llms.run#L69-L72","kind":"function","name":"run","path":"web_run/llms.py","language":"python","start_line":69,"end_line":72,"context_start_line":49,"context_end_line":80,"code":" self.prompt_temp = PromptTemplate(\n input_variables=[\"prompt\"], template=\"{prompt}\"\n )\n self.llm_name = llm_name\n \n def run(self, prompt, temperature=0.9, stop=['\\n'], max_tokens=128):\n llm = OpenAI(model=self.llm_name, temperature=temperature, stop=['\\n'], max_tokens=max_tokens)\n chain = LLMChain(llm=llm, prompt=self.prompt_temp)\n return chain.run(prompt)\n\n\nclass langchain_fastchat_llm:\n def __init__(self, llm_name):\n openai.api_key = \"EMPTY\" # Not support yet\n openai.api_base = \"http://localhost:8000/v1\"\n self.prompt_temp = PromptTemplate(\n input_variables=[\"prompt\"], template=\"{prompt}\"\n )\n self.llm_name = llm_name\n \n def run(self, prompt, temperature=0.9, stop=['\\n'], max_tokens=128):\n llm = OpenAI(model=self.llm_name, temperature=temperature, stop=['\\n'], max_tokens=max_tokens)\n chain = LLMChain(llm=llm, prompt=self.prompt_temp)\n return chain.run(prompt)\n\ndef get_llm_backend(llm_name):\n if llm_name in OPENAI_CHAT_MODELS:\n return langchain_openai_chatllm(llm_name)\n elif llm_name in OPENAI_LLM_MODELS:\n return langchain_openai_llm(llm_name)\n else:\n return langchain_fastchat_llm(llm_name)","source_hash":"e8dadcd5c975227c22060fdc5519cc6907b63536aec6f5814eafb56dd95eef88","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.config","uri":"program://BOLAA/module/hotpotqa_run.config#L1-L9","kind":"module","name":"hotpotqa_run.config","path":"hotpotqa_run/config.py","language":"python","start_line":1,"end_line":9,"context_start_line":1,"context_end_line":9,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\navailable_agent_names = [\"Zeroshot_HotPotQA_run_Agent\",\"ZeroshotThink_HotPotQA_run_Agent\",\"React_HotPotQA_run_Agent\",\"Planner_HotPotQA_run_Agent\",\"PlannerReact_HotPotQA_run_Agent\"]\nOPENAI_API_KEY = \"\"","source_hash":"834865f6e526c92e21eeb20b1ebcec03502024591da49b5deea9c012aaaf2ebc","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wikienv","uri":"program://BOLAA/module/hotpotqa_run.wikienv#L1-L175","kind":"module","name":"hotpotqa_run.wikienv","path":"hotpotqa_run/wikienv.py","language":"python","start_line":1,"end_line":175,"context_start_line":1,"context_end_line":175,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport ast\nimport json\nimport time\nimport gym\nimport requests\nfrom bs4 import BeautifulSoup\n\n# import wikipedia\n\ndef clean_str(p):\n return p.encode().decode(\"unicode-escape\").encode(\"latin1\").decode(\"utf-8\")\n\n\nclass textSpace(gym.spaces.Space):\n def contains(self, x) -> bool:\n \"\"\"Return boolean specifying if x is a valid member of this space.\"\"\"\n return isinstance(x, str)\n\n\nclass WikiEnv(gym.Env):\n\n def __init__(self):\n \"\"\"\n Initialize the environment.\n \"\"\"\n super().__init__()\n self.page = None # current Wikipedia page\n self.obs = None # current observation\n self.lookup_keyword = None # current lookup keyword\n self.lookup_list = None # list of paragraphs containing current lookup keyword\n self.lookup_cnt = None # current lookup index\n self.steps = 0 # current number of steps\n self.answer = None # current answer from the agent\n self.observation_space = self.action_space = textSpace()\n self.search_time = 0\n self.num_searches = 0\n \n def _get_obs(self):\n return self.obs\n\n def _get_info(self):\n return {\"steps\": self.steps, \"answer\": self.answer}\n\n def reset(self, seed=None, return_info=False, options=None):\n # We need the following line to seed self.np_random\n # super().reset(seed=seed)\n self.obs = (\"Interact with Wikipedia using search[], lookup[], and \"\n \"finish[].\\n\")\n self.page = None\n self.lookup_keyword = None\n self.lookup_list = None\n self.lookup_cnt = None\n self.steps = 0\n self.answer = None\n observation = self._get_obs()\n info = self._get_info()\n return (observation, info) if return_info else observation\n\n def construct_lookup_list(self, keyword):\n # find all paragraphs\n if self.page is None:\n return []\n paragraphs = self.page.split(\"\\n\")\n paragraphs = [p.strip() for p in paragraphs if p.strip()]\n\n # find all sentence\n sentences = []\n for p in paragraphs:\n sentences += p.split('. ')\n sentences = [s.strip() + '.' for s in sentences if s.strip()]\n\n parts = sentences\n parts = [p for p in parts if keyword.lower() in p.lower()]\n return parts\n\n @staticmethod\n def get_page_obs(page):\n # find all paragraphs\n paragraphs = page.split(\"\\n\")\n paragraphs = [p.strip() for p in paragraphs if p.strip()]\n\n # find all sentence\n sentences = []\n for p in paragraphs:\n sentences += p.split('. ')\n sentences = [s.strip() + '.' for s in sentences if s.strip()]\n return ' '.join(sentences[:5])\n\n # ps = page.split(\"\\n\")\n # ret = ps[0]\n # for i in range(1, len(ps)):\n # if len((ret + ps[i]).split(\" \")) <= 50:\n # ret += ps[i]\n # else:\n # break\n # return ret\n\n def search_step(self, entity):\n entity_ = entity.replace(\" \", \"+\")\n search_url = f\"https://en.wikipedia.org/w/index.php?search={entity_}\"\n old_time = time.time()\n response_text = requests.get(search_url).text\n self.search_time += time.time() - old_time\n self.num_searches += 1\n soup = BeautifulSoup(response_text, features=\"html.parser\")\n result_divs = soup.find_all(\"div\", {\"class\": \"mw-search-result-heading\"})\n if result_divs: # mismatch\n self.result_titles = [clean_str(div.get_text().strip()) for div in result_divs]\n self.obs = f\"Could not find {entity}. Similar: {self.result_titles[:5]}.\"\n else:\n page = [p.get_text().strip() for p in soup.find_all(\"p\") + soup.find_all(\"ul\")]\n if any(\"may refer to:\" in p for p in page):\n self.search_step(\"[\" + entity + \"]\")\n else:\n self.page = \"\"\n for p in page:\n if len(p.split(\" \")) > 2:\n self.page += clean_str(p)\n if not p.endswith(\"\\n\"):\n self.page += \"\\n\"\n self.obs = self.get_page_obs(self.page)\n self.lookup_keyword = self.lookup_list = self.lookup_cnt = None\n \n def step(self, action):\n reward = 0\n done = False\n action = action.strip()\n if self.answer is not None: # already finished\n done = True\n return self.obs, reward, done, self._get_info()\n \n if action.startswith(\"search[\") and action.endswith(\"]\"):\n entity = action[len(\"search[\"):-1]\n # entity_ = entity.replace(\" \", \"_\")\n # search_url = f\"https://en.wikipedia.org/wiki/{entity_}\"\n self.search_step(entity)\n elif action.startswith(\"lookup[\") and action.endswith(\"]\"):\n keyword = action[len(\"lookup[\"):-1]\n if self.lookup_keyword != keyword: # reset lookup\n self.lookup_keyword = keyword\n self.lookup_list = self.construct_lookup_list(keyword)\n self.lookup_cnt = 0\n if self.lookup_cnt >= len(self.lookup_list):\n self.obs = \"No more results.\\n\"\n else:\n self.obs = f\"(Result {self.lookup_cnt + 1} / {len(self.lookup_list)}) \" + self.lookup_list[self.lookup_cnt]\n self.lookup_cnt += 1\n elif action.startswith(\"finish[\") and action.endswith(\"]\"):\n answer = action[len(\"finish[\"):-1]\n self.answer = answer\n done = True\n self.obs = f\"Episode finished, reward = {reward}\\n\"\n elif action.startswith(\"think[\") and action.endswith(\"]\"):\n self.obs = \"Nice thought.\"\n else:\n self.obs = \"Invalid action: {}\".format(action)\n\n self.steps += 1\n\n return self.obs, reward, done, self._get_info()\n \n def get_time_info(self):\n speed = self.search_time / self.num_searches if self.num_searches else 0\n return {\n \"call_speed\": speed,\n \"call_time\": self.search_time,\n \"num_calls\": self.num_searches,\n }","source_hash":"b79b874c4a5be411be5ed7262e5557188c4bb5bdbc5f3a2837331c25e294c3ce","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wikienv.clean_str","uri":"program://BOLAA/function/hotpotqa_run.wikienv.clean_str#L17-L18","kind":"function","name":"clean_str","path":"hotpotqa_run/wikienv.py","language":"python","start_line":17,"end_line":18,"context_start_line":1,"context_end_line":38,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport ast\nimport json\nimport time\nimport gym\nimport requests\nfrom bs4 import BeautifulSoup\n\n# import wikipedia\n\ndef clean_str(p):\n return p.encode().decode(\"unicode-escape\").encode(\"latin1\").decode(\"utf-8\")\n\n\nclass textSpace(gym.spaces.Space):\n def contains(self, x) -> bool:\n \"\"\"Return boolean specifying if x is a valid member of this space.\"\"\"\n return isinstance(x, str)\n\n\nclass WikiEnv(gym.Env):\n\n def __init__(self):\n \"\"\"\n Initialize the environment.\n \"\"\"\n super().__init__()\n self.page = None # current Wikipedia page\n self.obs = None # current observation\n self.lookup_keyword = None # current lookup keyword\n self.lookup_list = None # list of paragraphs containing current lookup keyword\n self.lookup_cnt = None # current lookup index","source_hash":"b79b874c4a5be411be5ed7262e5557188c4bb5bdbc5f3a2837331c25e294c3ce","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wikienv.textSpace","uri":"program://BOLAA/class/hotpotqa_run.wikienv.textSpace#L21-L24","kind":"class","name":"textSpace","path":"hotpotqa_run/wikienv.py","language":"python","start_line":21,"end_line":24,"context_start_line":1,"context_end_line":44,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport ast\nimport json\nimport time\nimport gym\nimport requests\nfrom bs4 import BeautifulSoup\n\n# import wikipedia\n\ndef clean_str(p):\n return p.encode().decode(\"unicode-escape\").encode(\"latin1\").decode(\"utf-8\")\n\n\nclass textSpace(gym.spaces.Space):\n def contains(self, x) -> bool:\n \"\"\"Return boolean specifying if x is a valid member of this space.\"\"\"\n return isinstance(x, str)\n\n\nclass WikiEnv(gym.Env):\n\n def __init__(self):\n \"\"\"\n Initialize the environment.\n \"\"\"\n super().__init__()\n self.page = None # current Wikipedia page\n self.obs = None # current observation\n self.lookup_keyword = None # current lookup keyword\n self.lookup_list = None # list of paragraphs containing current lookup keyword\n self.lookup_cnt = None # current lookup index\n self.steps = 0 # current number of steps\n self.answer = None # current answer from the agent\n self.observation_space = self.action_space = textSpace()\n self.search_time = 0\n self.num_searches = 0\n ","source_hash":"b79b874c4a5be411be5ed7262e5557188c4bb5bdbc5f3a2837331c25e294c3ce","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wikienv.WikiEnv","uri":"program://BOLAA/class/hotpotqa_run.wikienv.WikiEnv#L27-L175","kind":"class","name":"WikiEnv","path":"hotpotqa_run/wikienv.py","language":"python","start_line":27,"end_line":175,"context_start_line":7,"context_end_line":175,"code":"\nimport ast\nimport json\nimport time\nimport gym\nimport requests\nfrom bs4 import BeautifulSoup\n\n# import wikipedia\n\ndef clean_str(p):\n return p.encode().decode(\"unicode-escape\").encode(\"latin1\").decode(\"utf-8\")\n\n\nclass textSpace(gym.spaces.Space):\n def contains(self, x) -> bool:\n \"\"\"Return boolean specifying if x is a valid member of this space.\"\"\"\n return isinstance(x, str)\n\n\nclass WikiEnv(gym.Env):\n\n def __init__(self):\n \"\"\"\n Initialize the environment.\n \"\"\"\n super().__init__()\n self.page = None # current Wikipedia page\n self.obs = None # current observation\n self.lookup_keyword = None # current lookup keyword\n self.lookup_list = None # list of paragraphs containing current lookup keyword\n self.lookup_cnt = None # current lookup index\n self.steps = 0 # current number of steps\n self.answer = None # current answer from the agent\n self.observation_space = self.action_space = textSpace()\n self.search_time = 0\n self.num_searches = 0\n \n def _get_obs(self):\n return self.obs\n\n def _get_info(self):\n return {\"steps\": self.steps, \"answer\": self.answer}\n\n def reset(self, seed=None, return_info=False, options=None):\n # We need the following line to seed self.np_random\n # super().reset(seed=seed)\n self.obs = (\"Interact with Wikipedia using search[], lookup[], and \"\n \"finish[].\\n\")\n self.page = None\n self.lookup_keyword = None\n self.lookup_list = None\n self.lookup_cnt = None\n self.steps = 0\n self.answer = None\n observation = self._get_obs()\n info = self._get_info()\n return (observation, info) if return_info else observation\n\n def construct_lookup_list(self, keyword):\n # find all paragraphs\n if self.page is None:\n return []\n paragraphs = self.page.split(\"\\n\")\n paragraphs = [p.strip() for p in paragraphs if p.strip()]\n\n # find all sentence\n sentences = []\n for p in paragraphs:\n sentences += p.split('. ')\n sentences = [s.strip() + '.' for s in sentences if s.strip()]\n\n parts = sentences\n parts = [p for p in parts if keyword.lower() in p.lower()]\n return parts\n\n @staticmethod\n def get_page_obs(page):\n # find all paragraphs\n paragraphs = page.split(\"\\n\")\n paragraphs = [p.strip() for p in paragraphs if p.strip()]\n\n # find all sentence\n sentences = []\n for p in paragraphs:\n sentences += p.split('. ')\n sentences = [s.strip() + '.' for s in sentences if s.strip()]\n return ' '.join(sentences[:5])\n\n # ps = page.split(\"\\n\")\n # ret = ps[0]\n # for i in range(1, len(ps)):\n # if len((ret + ps[i]).split(\" \")) <= 50:\n # ret += ps[i]\n # else:\n # break\n # return ret\n\n def search_step(self, entity):\n entity_ = entity.replace(\" \", \"+\")\n search_url = f\"https://en.wikipedia.org/w/index.php?search={entity_}\"\n old_time = time.time()\n response_text = requests.get(search_url).text\n self.search_time += time.time() - old_time\n self.num_searches += 1\n soup = BeautifulSoup(response_text, features=\"html.parser\")\n result_divs = soup.find_all(\"div\", {\"class\": \"mw-search-result-heading\"})\n if result_divs: # mismatch\n self.result_titles = [clean_str(div.get_text().strip()) for div in result_divs]\n self.obs = f\"Could not find {entity}. Similar: {self.result_titles[:5]}.\"\n else:\n page = [p.get_text().strip() for p in soup.find_all(\"p\") + soup.find_all(\"ul\")]\n if any(\"may refer to:\" in p for p in page):\n self.search_step(\"[\" + entity + \"]\")\n else:\n self.page = \"\"\n for p in page:\n if len(p.split(\" \")) > 2:\n self.page += clean_str(p)\n if not p.endswith(\"\\n\"):\n self.page += \"\\n\"\n self.obs = self.get_page_obs(self.page)\n self.lookup_keyword = self.lookup_list = self.lookup_cnt = None\n \n def step(self, action):\n reward = 0\n done = False\n action = action.strip()\n if self.answer is not None: # already finished\n done = True\n return self.obs, reward, done, self._get_info()\n \n if action.startswith(\"search[\") and action.endswith(\"]\"):\n entity = action[len(\"search[\"):-1]\n # entity_ = entity.replace(\" \", \"_\")\n # search_url = f\"https://en.wikipedia.org/wiki/{entity_}\"\n self.search_step(entity)\n elif action.startswith(\"lookup[\") and action.endswith(\"]\"):\n keyword = action[len(\"lookup[\"):-1]\n if self.lookup_keyword != keyword: # reset lookup\n self.lookup_keyword = keyword\n self.lookup_list = self.construct_lookup_list(keyword)\n self.lookup_cnt = 0\n if self.lookup_cnt >= len(self.lookup_list):\n self.obs = \"No more results.\\n\"\n else:\n self.obs = f\"(Result {self.lookup_cnt + 1} / {len(self.lookup_list)}) \" + self.lookup_list[self.lookup_cnt]\n self.lookup_cnt += 1\n elif action.startswith(\"finish[\") and action.endswith(\"]\"):\n answer = action[len(\"finish[\"):-1]\n self.answer = answer\n done = True\n self.obs = f\"Episode finished, reward = {reward}\\n\"\n elif action.startswith(\"think[\") and action.endswith(\"]\"):\n self.obs = \"Nice thought.\"\n else:\n self.obs = \"Invalid action: {}\".format(action)\n\n self.steps += 1\n\n return self.obs, reward, done, self._get_info()\n \n def get_time_info(self):\n speed = self.search_time / self.num_searches if self.num_searches else 0\n return {\n \"call_speed\": speed,\n \"call_time\": self.search_time,\n \"num_calls\": self.num_searches,\n }","source_hash":"b79b874c4a5be411be5ed7262e5557188c4bb5bdbc5f3a2837331c25e294c3ce","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wikienv.contains","uri":"program://BOLAA/function/hotpotqa_run.wikienv.contains#L22-L24","kind":"function","name":"contains","path":"hotpotqa_run/wikienv.py","language":"python","start_line":22,"end_line":24,"context_start_line":2,"context_end_line":44,"code":" Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport ast\nimport json\nimport time\nimport gym\nimport requests\nfrom bs4 import BeautifulSoup\n\n# import wikipedia\n\ndef clean_str(p):\n return p.encode().decode(\"unicode-escape\").encode(\"latin1\").decode(\"utf-8\")\n\n\nclass textSpace(gym.spaces.Space):\n def contains(self, x) -> bool:\n \"\"\"Return boolean specifying if x is a valid member of this space.\"\"\"\n return isinstance(x, str)\n\n\nclass WikiEnv(gym.Env):\n\n def __init__(self):\n \"\"\"\n Initialize the environment.\n \"\"\"\n super().__init__()\n self.page = None # current Wikipedia page\n self.obs = None # current observation\n self.lookup_keyword = None # current lookup keyword\n self.lookup_list = None # list of paragraphs containing current lookup keyword\n self.lookup_cnt = None # current lookup index\n self.steps = 0 # current number of steps\n self.answer = None # current answer from the agent\n self.observation_space = self.action_space = textSpace()\n self.search_time = 0\n self.num_searches = 0\n ","source_hash":"b79b874c4a5be411be5ed7262e5557188c4bb5bdbc5f3a2837331c25e294c3ce","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wikienv.__init__","uri":"program://BOLAA/function/hotpotqa_run.wikienv.__init__#L29-L43","kind":"function","name":"__init__","path":"hotpotqa_run/wikienv.py","language":"python","start_line":29,"end_line":43,"context_start_line":9,"context_end_line":63,"code":"import json\nimport time\nimport gym\nimport requests\nfrom bs4 import BeautifulSoup\n\n# import wikipedia\n\ndef clean_str(p):\n return p.encode().decode(\"unicode-escape\").encode(\"latin1\").decode(\"utf-8\")\n\n\nclass textSpace(gym.spaces.Space):\n def contains(self, x) -> bool:\n \"\"\"Return boolean specifying if x is a valid member of this space.\"\"\"\n return isinstance(x, str)\n\n\nclass WikiEnv(gym.Env):\n\n def __init__(self):\n \"\"\"\n Initialize the environment.\n \"\"\"\n super().__init__()\n self.page = None # current Wikipedia page\n self.obs = None # current observation\n self.lookup_keyword = None # current lookup keyword\n self.lookup_list = None # list of paragraphs containing current lookup keyword\n self.lookup_cnt = None # current lookup index\n self.steps = 0 # current number of steps\n self.answer = None # current answer from the agent\n self.observation_space = self.action_space = textSpace()\n self.search_time = 0\n self.num_searches = 0\n \n def _get_obs(self):\n return self.obs\n\n def _get_info(self):\n return {\"steps\": self.steps, \"answer\": self.answer}\n\n def reset(self, seed=None, return_info=False, options=None):\n # We need the following line to seed self.np_random\n # super().reset(seed=seed)\n self.obs = (\"Interact with Wikipedia using search[], lookup[], and \"\n \"finish[].\\n\")\n self.page = None\n self.lookup_keyword = None\n self.lookup_list = None\n self.lookup_cnt = None\n self.steps = 0\n self.answer = None\n observation = self._get_obs()\n info = self._get_info()","source_hash":"b79b874c4a5be411be5ed7262e5557188c4bb5bdbc5f3a2837331c25e294c3ce","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wikienv._get_obs","uri":"program://BOLAA/function/hotpotqa_run.wikienv._get_obs#L45-L46","kind":"function","name":"_get_obs","path":"hotpotqa_run/wikienv.py","language":"python","start_line":45,"end_line":46,"context_start_line":25,"context_end_line":66,"code":"\n\nclass WikiEnv(gym.Env):\n\n def __init__(self):\n \"\"\"\n Initialize the environment.\n \"\"\"\n super().__init__()\n self.page = None # current Wikipedia page\n self.obs = None # current observation\n self.lookup_keyword = None # current lookup keyword\n self.lookup_list = None # list of paragraphs containing current lookup keyword\n self.lookup_cnt = None # current lookup index\n self.steps = 0 # current number of steps\n self.answer = None # current answer from the agent\n self.observation_space = self.action_space = textSpace()\n self.search_time = 0\n self.num_searches = 0\n \n def _get_obs(self):\n return self.obs\n\n def _get_info(self):\n return {\"steps\": self.steps, \"answer\": self.answer}\n\n def reset(self, seed=None, return_info=False, options=None):\n # We need the following line to seed self.np_random\n # super().reset(seed=seed)\n self.obs = (\"Interact with Wikipedia using search[], lookup[], and \"\n \"finish[].\\n\")\n self.page = None\n self.lookup_keyword = None\n self.lookup_list = None\n self.lookup_cnt = None\n self.steps = 0\n self.answer = None\n observation = self._get_obs()\n info = self._get_info()\n return (observation, info) if return_info else observation\n\n def construct_lookup_list(self, keyword):","source_hash":"b79b874c4a5be411be5ed7262e5557188c4bb5bdbc5f3a2837331c25e294c3ce","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wikienv._get_info","uri":"program://BOLAA/function/hotpotqa_run.wikienv._get_info#L48-L49","kind":"function","name":"_get_info","path":"hotpotqa_run/wikienv.py","language":"python","start_line":48,"end_line":49,"context_start_line":28,"context_end_line":69,"code":"\n def __init__(self):\n \"\"\"\n Initialize the environment.\n \"\"\"\n super().__init__()\n self.page = None # current Wikipedia page\n self.obs = None # current observation\n self.lookup_keyword = None # current lookup keyword\n self.lookup_list = None # list of paragraphs containing current lookup keyword\n self.lookup_cnt = None # current lookup index\n self.steps = 0 # current number of steps\n self.answer = None # current answer from the agent\n self.observation_space = self.action_space = textSpace()\n self.search_time = 0\n self.num_searches = 0\n \n def _get_obs(self):\n return self.obs\n\n def _get_info(self):\n return {\"steps\": self.steps, \"answer\": self.answer}\n\n def reset(self, seed=None, return_info=False, options=None):\n # We need the following line to seed self.np_random\n # super().reset(seed=seed)\n self.obs = (\"Interact with Wikipedia using search[], lookup[], and \"\n \"finish[].\\n\")\n self.page = None\n self.lookup_keyword = None\n self.lookup_list = None\n self.lookup_cnt = None\n self.steps = 0\n self.answer = None\n observation = self._get_obs()\n info = self._get_info()\n return (observation, info) if return_info else observation\n\n def construct_lookup_list(self, keyword):\n # find all paragraphs\n if self.page is None:\n return []","source_hash":"b79b874c4a5be411be5ed7262e5557188c4bb5bdbc5f3a2837331c25e294c3ce","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wikienv.reset","uri":"program://BOLAA/function/hotpotqa_run.wikienv.reset#L51-L64","kind":"function","name":"reset","path":"hotpotqa_run/wikienv.py","language":"python","start_line":51,"end_line":64,"context_start_line":31,"context_end_line":84,"code":" Initialize the environment.\n \"\"\"\n super().__init__()\n self.page = None # current Wikipedia page\n self.obs = None # current observation\n self.lookup_keyword = None # current lookup keyword\n self.lookup_list = None # list of paragraphs containing current lookup keyword\n self.lookup_cnt = None # current lookup index\n self.steps = 0 # current number of steps\n self.answer = None # current answer from the agent\n self.observation_space = self.action_space = textSpace()\n self.search_time = 0\n self.num_searches = 0\n \n def _get_obs(self):\n return self.obs\n\n def _get_info(self):\n return {\"steps\": self.steps, \"answer\": self.answer}\n\n def reset(self, seed=None, return_info=False, options=None):\n # We need the following line to seed self.np_random\n # super().reset(seed=seed)\n self.obs = (\"Interact with Wikipedia using search[], lookup[], and \"\n \"finish[].\\n\")\n self.page = None\n self.lookup_keyword = None\n self.lookup_list = None\n self.lookup_cnt = None\n self.steps = 0\n self.answer = None\n observation = self._get_obs()\n info = self._get_info()\n return (observation, info) if return_info else observation\n\n def construct_lookup_list(self, keyword):\n # find all paragraphs\n if self.page is None:\n return []\n paragraphs = self.page.split(\"\\n\")\n paragraphs = [p.strip() for p in paragraphs if p.strip()]\n\n # find all sentence\n sentences = []\n for p in paragraphs:\n sentences += p.split('. ')\n sentences = [s.strip() + '.' for s in sentences if s.strip()]\n\n parts = sentences\n parts = [p for p in parts if keyword.lower() in p.lower()]\n return parts\n\n @staticmethod\n def get_page_obs(page):","source_hash":"b79b874c4a5be411be5ed7262e5557188c4bb5bdbc5f3a2837331c25e294c3ce","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wikienv.construct_lookup_list","uri":"program://BOLAA/function/hotpotqa_run.wikienv.construct_lookup_list#L66-L81","kind":"function","name":"construct_lookup_list","path":"hotpotqa_run/wikienv.py","language":"python","start_line":66,"end_line":81,"context_start_line":46,"context_end_line":101,"code":" return self.obs\n\n def _get_info(self):\n return {\"steps\": self.steps, \"answer\": self.answer}\n\n def reset(self, seed=None, return_info=False, options=None):\n # We need the following line to seed self.np_random\n # super().reset(seed=seed)\n self.obs = (\"Interact with Wikipedia using search[], lookup[], and \"\n \"finish[].\\n\")\n self.page = None\n self.lookup_keyword = None\n self.lookup_list = None\n self.lookup_cnt = None\n self.steps = 0\n self.answer = None\n observation = self._get_obs()\n info = self._get_info()\n return (observation, info) if return_info else observation\n\n def construct_lookup_list(self, keyword):\n # find all paragraphs\n if self.page is None:\n return []\n paragraphs = self.page.split(\"\\n\")\n paragraphs = [p.strip() for p in paragraphs if p.strip()]\n\n # find all sentence\n sentences = []\n for p in paragraphs:\n sentences += p.split('. ')\n sentences = [s.strip() + '.' for s in sentences if s.strip()]\n\n parts = sentences\n parts = [p for p in parts if keyword.lower() in p.lower()]\n return parts\n\n @staticmethod\n def get_page_obs(page):\n # find all paragraphs\n paragraphs = page.split(\"\\n\")\n paragraphs = [p.strip() for p in paragraphs if p.strip()]\n\n # find all sentence\n sentences = []\n for p in paragraphs:\n sentences += p.split('. ')\n sentences = [s.strip() + '.' for s in sentences if s.strip()]\n return ' '.join(sentences[:5])\n\n # ps = page.split(\"\\n\")\n # ret = ps[0]\n # for i in range(1, len(ps)):\n # if len((ret + ps[i]).split(\" \")) <= 50:\n # ret += ps[i]\n # else:","source_hash":"b79b874c4a5be411be5ed7262e5557188c4bb5bdbc5f3a2837331c25e294c3ce","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wikienv.get_page_obs","uri":"program://BOLAA/function/hotpotqa_run.wikienv.get_page_obs#L84-L94","kind":"function","name":"get_page_obs","path":"hotpotqa_run/wikienv.py","language":"python","start_line":84,"end_line":94,"context_start_line":64,"context_end_line":114,"code":" return (observation, info) if return_info else observation\n\n def construct_lookup_list(self, keyword):\n # find all paragraphs\n if self.page is None:\n return []\n paragraphs = self.page.split(\"\\n\")\n paragraphs = [p.strip() for p in paragraphs if p.strip()]\n\n # find all sentence\n sentences = []\n for p in paragraphs:\n sentences += p.split('. ')\n sentences = [s.strip() + '.' for s in sentences if s.strip()]\n\n parts = sentences\n parts = [p for p in parts if keyword.lower() in p.lower()]\n return parts\n\n @staticmethod\n def get_page_obs(page):\n # find all paragraphs\n paragraphs = page.split(\"\\n\")\n paragraphs = [p.strip() for p in paragraphs if p.strip()]\n\n # find all sentence\n sentences = []\n for p in paragraphs:\n sentences += p.split('. ')\n sentences = [s.strip() + '.' for s in sentences if s.strip()]\n return ' '.join(sentences[:5])\n\n # ps = page.split(\"\\n\")\n # ret = ps[0]\n # for i in range(1, len(ps)):\n # if len((ret + ps[i]).split(\" \")) <= 50:\n # ret += ps[i]\n # else:\n # break\n # return ret\n\n def search_step(self, entity):\n entity_ = entity.replace(\" \", \"+\")\n search_url = f\"https://en.wikipedia.org/w/index.php?search={entity_}\"\n old_time = time.time()\n response_text = requests.get(search_url).text\n self.search_time += time.time() - old_time\n self.num_searches += 1\n soup = BeautifulSoup(response_text, features=\"html.parser\")\n result_divs = soup.find_all(\"div\", {\"class\": \"mw-search-result-heading\"})\n if result_divs: # mismatch","source_hash":"b79b874c4a5be411be5ed7262e5557188c4bb5bdbc5f3a2837331c25e294c3ce","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wikienv.search_step","uri":"program://BOLAA/function/hotpotqa_run.wikienv.search_step#L105-L129","kind":"function","name":"search_step","path":"hotpotqa_run/wikienv.py","language":"python","start_line":105,"end_line":129,"context_start_line":85,"context_end_line":149,"code":" # find all paragraphs\n paragraphs = page.split(\"\\n\")\n paragraphs = [p.strip() for p in paragraphs if p.strip()]\n\n # find all sentence\n sentences = []\n for p in paragraphs:\n sentences += p.split('. ')\n sentences = [s.strip() + '.' for s in sentences if s.strip()]\n return ' '.join(sentences[:5])\n\n # ps = page.split(\"\\n\")\n # ret = ps[0]\n # for i in range(1, len(ps)):\n # if len((ret + ps[i]).split(\" \")) <= 50:\n # ret += ps[i]\n # else:\n # break\n # return ret\n\n def search_step(self, entity):\n entity_ = entity.replace(\" \", \"+\")\n search_url = f\"https://en.wikipedia.org/w/index.php?search={entity_}\"\n old_time = time.time()\n response_text = requests.get(search_url).text\n self.search_time += time.time() - old_time\n self.num_searches += 1\n soup = BeautifulSoup(response_text, features=\"html.parser\")\n result_divs = soup.find_all(\"div\", {\"class\": \"mw-search-result-heading\"})\n if result_divs: # mismatch\n self.result_titles = [clean_str(div.get_text().strip()) for div in result_divs]\n self.obs = f\"Could not find {entity}. Similar: {self.result_titles[:5]}.\"\n else:\n page = [p.get_text().strip() for p in soup.find_all(\"p\") + soup.find_all(\"ul\")]\n if any(\"may refer to:\" in p for p in page):\n self.search_step(\"[\" + entity + \"]\")\n else:\n self.page = \"\"\n for p in page:\n if len(p.split(\" \")) > 2:\n self.page += clean_str(p)\n if not p.endswith(\"\\n\"):\n self.page += \"\\n\"\n self.obs = self.get_page_obs(self.page)\n self.lookup_keyword = self.lookup_list = self.lookup_cnt = None\n \n def step(self, action):\n reward = 0\n done = False\n action = action.strip()\n if self.answer is not None: # already finished\n done = True\n return self.obs, reward, done, self._get_info()\n \n if action.startswith(\"search[\") and action.endswith(\"]\"):\n entity = action[len(\"search[\"):-1]\n # entity_ = entity.replace(\" \", \"_\")\n # search_url = f\"https://en.wikipedia.org/wiki/{entity_}\"\n self.search_step(entity)\n elif action.startswith(\"lookup[\") and action.endswith(\"]\"):\n keyword = action[len(\"lookup[\"):-1]\n if self.lookup_keyword != keyword: # reset lookup\n self.lookup_keyword = keyword\n self.lookup_list = self.construct_lookup_list(keyword)\n self.lookup_cnt = 0","source_hash":"b79b874c4a5be411be5ed7262e5557188c4bb5bdbc5f3a2837331c25e294c3ce","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wikienv.step","uri":"program://BOLAA/function/hotpotqa_run.wikienv.step#L131-L167","kind":"function","name":"step","path":"hotpotqa_run/wikienv.py","language":"python","start_line":131,"end_line":167,"context_start_line":111,"context_end_line":175,"code":" self.num_searches += 1\n soup = BeautifulSoup(response_text, features=\"html.parser\")\n result_divs = soup.find_all(\"div\", {\"class\": \"mw-search-result-heading\"})\n if result_divs: # mismatch\n self.result_titles = [clean_str(div.get_text().strip()) for div in result_divs]\n self.obs = f\"Could not find {entity}. Similar: {self.result_titles[:5]}.\"\n else:\n page = [p.get_text().strip() for p in soup.find_all(\"p\") + soup.find_all(\"ul\")]\n if any(\"may refer to:\" in p for p in page):\n self.search_step(\"[\" + entity + \"]\")\n else:\n self.page = \"\"\n for p in page:\n if len(p.split(\" \")) > 2:\n self.page += clean_str(p)\n if not p.endswith(\"\\n\"):\n self.page += \"\\n\"\n self.obs = self.get_page_obs(self.page)\n self.lookup_keyword = self.lookup_list = self.lookup_cnt = None\n \n def step(self, action):\n reward = 0\n done = False\n action = action.strip()\n if self.answer is not None: # already finished\n done = True\n return self.obs, reward, done, self._get_info()\n \n if action.startswith(\"search[\") and action.endswith(\"]\"):\n entity = action[len(\"search[\"):-1]\n # entity_ = entity.replace(\" \", \"_\")\n # search_url = f\"https://en.wikipedia.org/wiki/{entity_}\"\n self.search_step(entity)\n elif action.startswith(\"lookup[\") and action.endswith(\"]\"):\n keyword = action[len(\"lookup[\"):-1]\n if self.lookup_keyword != keyword: # reset lookup\n self.lookup_keyword = keyword\n self.lookup_list = self.construct_lookup_list(keyword)\n self.lookup_cnt = 0\n if self.lookup_cnt >= len(self.lookup_list):\n self.obs = \"No more results.\\n\"\n else:\n self.obs = f\"(Result {self.lookup_cnt + 1} / {len(self.lookup_list)}) \" + self.lookup_list[self.lookup_cnt]\n self.lookup_cnt += 1\n elif action.startswith(\"finish[\") and action.endswith(\"]\"):\n answer = action[len(\"finish[\"):-1]\n self.answer = answer\n done = True\n self.obs = f\"Episode finished, reward = {reward}\\n\"\n elif action.startswith(\"think[\") and action.endswith(\"]\"):\n self.obs = \"Nice thought.\"\n else:\n self.obs = \"Invalid action: {}\".format(action)\n\n self.steps += 1\n\n return self.obs, reward, done, self._get_info()\n \n def get_time_info(self):\n speed = self.search_time / self.num_searches if self.num_searches else 0\n return {\n \"call_speed\": speed,\n \"call_time\": self.search_time,\n \"num_calls\": self.num_searches,\n }","source_hash":"b79b874c4a5be411be5ed7262e5557188c4bb5bdbc5f3a2837331c25e294c3ce","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wikienv.get_time_info","uri":"program://BOLAA/function/hotpotqa_run.wikienv.get_time_info#L169-L175","kind":"function","name":"get_time_info","path":"hotpotqa_run/wikienv.py","language":"python","start_line":169,"end_line":175,"context_start_line":149,"context_end_line":175,"code":" self.lookup_cnt = 0\n if self.lookup_cnt >= len(self.lookup_list):\n self.obs = \"No more results.\\n\"\n else:\n self.obs = f\"(Result {self.lookup_cnt + 1} / {len(self.lookup_list)}) \" + self.lookup_list[self.lookup_cnt]\n self.lookup_cnt += 1\n elif action.startswith(\"finish[\") and action.endswith(\"]\"):\n answer = action[len(\"finish[\"):-1]\n self.answer = answer\n done = True\n self.obs = f\"Episode finished, reward = {reward}\\n\"\n elif action.startswith(\"think[\") and action.endswith(\"]\"):\n self.obs = \"Nice thought.\"\n else:\n self.obs = \"Invalid action: {}\".format(action)\n\n self.steps += 1\n\n return self.obs, reward, done, self._get_info()\n \n def get_time_info(self):\n speed = self.search_time / self.num_searches if self.num_searches else 0\n return {\n \"call_speed\": speed,\n \"call_time\": self.search_time,\n \"num_calls\": self.num_searches,\n }","source_hash":"b79b874c4a5be411be5ed7262e5557188c4bb5bdbc5f3a2837331c25e294c3ce","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.hotpotqa_env","uri":"program://BOLAA/module/hotpotqa_run.hotpotqa_env#L1-L83","kind":"module","name":"hotpotqa_run.hotpotqa_env","path":"hotpotqa_run/hotpotqa_env.py","language":"python","start_line":1,"end_line":83,"context_start_line":1,"context_end_line":83,"code":"import wikienv, wrappers\n\ndef step(env, action):\n attempts = 0\n while attempts < 10:\n try:\n return env.step(action)\n except requests.exceptions.Timeout:\n attempts += 1\n\nclass HotPotQAEnv:\n def __init__(self, n_tasks=100):\n self.n_tasks = n_tasks\n self.sessions = {}\n env = wikienv.WikiEnv()\n env = wrappers.HotPotQAWrapper(env, split=\"dev\")\n env = wrappers.LoggingWrapper(env)\n for idx in range(self.n_tasks):\n self.sessions[idx] = {'session': idx, \n 'question': question = env.reset(idx=idx)\n }\n\n def step(self, session, action):\n done = False\n observation_ = None\n if action == 'reset':\n self.sessions[session] = {'session': session, 'page_type': 'init'}\n elif action.startswith('think['):\n observation = 'OK.'\n elif action.startswith('search['):\n assert self.sessions[session]['page_type'] == 'init'\n query = action[7:-1]\n self.sessions[session] = {'session': session, 'page_type': 'search',\n 'query_string': query, 'page_num': 1}\n elif action.startswith('click['):\n button = action[6:-1]\n if button == 'Buy Now':\n assert self.sessions[session]['page_type'] == 'item'\n self.sessions[session]['page_type'] = 'end'\n done = True\n elif button == 'Back to Search':\n assert self.sessions[session]['page_type'] in ['search', 'item_sub', 'item']\n self.sessions[session] = {'session': session, 'page_type': 'init'}\n elif button == 'Next >':\n assert False # ad hoc page limitation\n assert self.sessions[session]['page_type'] == 'search'\n self.sessions[session]['page_num'] += 1\n elif button == '< Prev':\n assert self.sessions[session]['page_type'] in ['search', 'item_sub', 'item']\n if self.sessions[session]['page_type'] == 'search':\n assert False\n self.sessions[session]['page_num'] -= 1\n elif self.sessions[session]['page_type'] == 'item_sub':\n self.sessions[session]['page_type'] = 'item'\n elif self.sessions[session]['page_type'] == 'item':\n self.sessions[session]['page_type'] = 'search'\n self.sessions[session]['options'] = {}\n elif button in ACTION_TO_TEMPLATE:\n assert self.sessions[session]['page_type'] == 'item'\n self.sessions[session]['page_type'] = 'item_sub'\n self.sessions[session]['subpage'] = button\n else:\n if self.sessions[session]['page_type'] == 'search':\n assert button in self.sessions[session].get('asins', []) # must be asins\n self.sessions[session]['page_type'] = 'item'\n self.sessions[session]['asin'] = button\n elif self.sessions[session]['page_type'] == 'item':\n assert 'option_types' in self.sessions[session]\n assert button in self.sessions[session]['option_types'], (button, self.sessions[session]['option_types']) # must be options\n option_type = self.sessions[session]['option_types'][button]\n if not 'options' in self.sessions[session]:\n self.sessions[session]['options'] = {}\n self.sessions[session]['options'][option_type] = button\n observation_ = f'You have clicked {button}.'\n else:\n assert False\n observation, info, clickable = webshop_text(**self.sessions[session])\n if observation_:\n observation = observation_\n self.sessions[session].update(info)\n reward = info.get('reward', 0.0)\n asins = info.get('asins', [])\n return observation, reward, done, asins, clickable","source_hash":"03a84e448feccc0f54a0e17bcfc7329a4b025ff7a55114477b70b3b7f65d2207","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch","uri":"program://BOLAA/module/hotpotqa_run.agent_arch#L1-L369","kind":"module","name":"hotpotqa_run.agent_arch","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":1,"end_line":369,"context_start_line":1,"context_end_line":369,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport random\nimport re, string, os\nimport json \nimport time\nimport tiktoken\nfrom langchain.llms.base import BaseLLM\nfrom langchain import OpenAI, Wikipedia\nfrom langchain.docstore.base import Docstore\nfrom langchain.agents.react.base import DocstoreExplorer\nfrom langchain.prompts import PromptTemplate\nfrom collections import Counter\n\nfrom hotpotqa_run.pre_prompt import (react_agent_prompt, zeroshot_agent_prompt, \n plan_prompt, planner_agent_prompt, plannerreact_agent_prompt)\nfrom hotpotqa_run.fewshots import REACT_EXAMPLE, PLANNER_EXAMPLE, PLAN_EXAMPLE, PLANNERREACT_EXAMPLE\n\nfrom web_run.llms import token_enc\n\ndef parse_action(string):\n pattern = r'^(\\w+)\\[(.+)\\]$'\n match = re.match(pattern, string)\n \n if match:\n action_type = match.group(1)\n argument = match.group(2)\n return action_type, argument\n else:\n action_type, argument = fuzzy_parse_action(string)\n return action_type, argument\n \ndef fuzzy_parse_action(text):\n text = text.strip(' ').strip('.')\n pattern = r'^(\\w+)\\[(.+)\\]'\n match = re.match(pattern, text)\n if match:\n action_type = match.group(1)\n argument = match.group(2)\n return action_type, argument\n else:\n return text, ''\n\ndef format_step(step: str) -> str:\n return step.strip('\\n').strip().replace('\\n', '')\n\ndef truncate_scratchpad(scratchpad: str, n_tokens: int = 1600, tokenizer = token_enc) -> str:\n lines = scratchpad.split('\\n')\n observations = filter(lambda x: x.startswith('Observation'), lines)\n observations_by_tokens = sorted(observations, key=lambda x: len(tokenizer.encode(x)))\n while len(token_enc.encode('\\n'.join(lines))) > n_tokens:\n largest_observation = observations_by_tokens.pop(-1)\n ind = lines.index(largest_observation)\n lines[ind] = largest_observation.split(':')[0] + ': [truncated wikipedia excerpt]'\n return '\\n'.join(lines)\n\ndef normalize_answer(s):\n def remove_articles(text):\n return re.sub(r\"\\b(a|an|the)\\b\", \" \", text)\n \n def white_space_fix(text):\n return \" \".join(text.split())\n \n def remove_punc(text):\n exclude = set(string.punctuation)\n return \"\".join(ch for ch in text if ch not in exclude)\n \n def lower(text):\n return text.lower()\n\n return white_space_fix(remove_articles(remove_punc(lower(s))))\n\ndef f1_score(prediction, ground_truth):\n normalized_prediction = normalize_answer(prediction)\n normalized_ground_truth = normalize_answer(ground_truth)\n\n ZERO_METRIC = (0, 0, 0)\n\n if normalized_prediction in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n if normalized_ground_truth in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n \n prediction_tokens = normalized_prediction.split()\n ground_truth_tokens = normalized_ground_truth.split()\n common = Counter(prediction_tokens) & Counter(ground_truth_tokens)\n num_same = sum(common.values())\n if num_same == 0:\n return ZERO_METRIC\n precision = 1.0 * num_same / len(prediction_tokens)\n recall = 1.0 * num_same / len(ground_truth_tokens)\n f1 = (2 * precision * recall) / (precision + recall)\n return f1, precision, recall\n\ndef EM(answer, key) -> bool:\n return normalize_answer(answer) == normalize_answer(key)\n\n\nclass BaseAgent:\n def __init__(self,\n question: str,\n key: str,\n llm: BaseLLM,\n context_len: int = 2000,\n max_steps: int= 10,\n docstore: Docstore = Wikipedia()\n ) -> None:\n \n self.question = question\n self.answer = ''\n self.key = key\n self.max_steps = max_steps\n self.agent_prompt = \"\"\n self.examples = \"\"\n self.context_len = context_len\n self.run_error = False\n self.name = \"Base_HotPotQA_run_Agent\"\n\n self.docstore = DocstoreExplorer(docstore) # Search, Lookup\n self.llm = llm\n \n self.enc = token_enc\n self.__reset_agent()\n \n def run(self, reset = True) -> None:\n if reset:\n self.__reset_agent()\n \n while not self.is_halted() and not self.is_finished() and not self.run_error:\n self.step()\n \n def prompt_agent(self) -> str:\n generation = self.llm(self._build_agent_prompt())\n self.check_run_error(generation)\n return format_step(generation)\n \n def check_run_error(self, text):\n if text in [\"No response\"]:\n self.run_error = True\n \n def is_finished(self) -> bool:\n return self.finished\n \n def reward(self) -> float:\n return f1_score(self.answer, self.key) \n \n def is_correct(self) -> bool:\n return EM(self.answer, self.key)\n\n def is_halted(self) -> bool:\n return ((self.step_n > self.max_steps)\n or (len(self.enc.encode(self._build_agent_prompt())) > self.context_len)\n ) and not self.finished\n\n def __reset_agent(self) -> None:\n self.step_n = 1\n self.finished = False\n self.scratchpad: str = ''\n\n def set_qa(self, question: str, key: str) -> None:\n self.question = question\n self.key = key\n\n def _think(self):\n self.scratchpad += f'\\nThought {self.step_n}:'\n self.scratchpad += ' ' + self.prompt_agent()\n print(self.scratchpad.split('\\n')[-1])\n \n def _action(self):\n self.scratchpad += f'\\nAction {self.step_n}:'\n action = self.prompt_agent()\n self.scratchpad += ' ' + action\n action_type, argument = parse_action(action)\n print(self.scratchpad.split('\\n')[-1])\n return action_type, argument\n \n def step(self) -> None:\n \n # agent forward\n ret = self.forward()\n if ret:\n action_type, argument = ret[0], ret[1]\n else:\n action_type = ret\n \n # Observe\n self.scratchpad += f'\\nObservation {self.step_n}: '\n \n if action_type == 'Finish':\n self.answer = argument\n if self.is_correct():\n self.scratchpad += 'Answer is CORRECT'\n else: \n self.scratchpad += 'Answer is INCORRECT'\n self.finished = True\n self.step_n += 1\n return\n\n if action_type == 'Search':\n try:\n self.scratchpad += format_step(self.docstore.search(argument))\n except Exception as e:\n print(e)\n self.scratchpad += f'Could not find that page, please try again.'\n \n elif action_type == 'Lookup':\n try:\n self.scratchpad += format_step(self.docstore.lookup(argument))\n except ValueError:\n self.scratchpad += f'The last page Searched was not found, so you cannot Lookup a keyword in it. Please try one of the similar pages given.'\n\n else:\n self.scratchpad += 'Invalid Action. Valid Actions are Lookup[] Search[] and Finish[].'\n\n print(self.scratchpad.split('\\n')[-1])\n\n self.step_n += 1\n \n def _build_agent_prompt(self) -> str:\n raise NotImplementedError\n \n def forward(self):\n raise NotImplementedError\n \nclass ReactAgent(BaseAgent):\n def __init__(self,\n question: str,\n key: str,\n llm,\n context_len: int = 2000\n ) -> None:\n super().__init__(question, key, llm, context_len)\n\n self.examples = REACT_EXAMPLE\n self.agent_prompt = react_agent_prompt\n self.name = \"React_HotPotQA_run_Agent\"\n \n def forward(self):\n self._think()\n action_type, argument = self._action()\n return action_type, argument\n\n def _build_agent_prompt(self) -> str:\n return self.agent_prompt.format(\n examples = self.examples,\n question = self.question,\n scratchpad = self.scratchpad)\n \nclass ZeroshotAgent(BaseAgent):\n def __init__(self,\n question: str,\n key: str,\n llm,\n context_len: int = 2000\n ) -> None:\n super().__init__(question, key, llm, context_len)\n\n self.examples = \"\"\n self.agent_prompt = zeroshot_agent_prompt\n self.name = \"Zeroshot_HotPotQA_run_Agent\"\n \n def forward(self):\n action_type, argument = self._action()\n return action_type, argument\n\n def _build_agent_prompt(self) -> str:\n return self.agent_prompt.format(\n question = self.question,\n scratchpad = self.scratchpad)\n \nclass ZeroshotThinkAgent(BaseAgent):\n def __init__(self,\n question: str,\n key: str,\n llm,\n context_len: int = 2000\n ) -> None:\n super().__init__(question, key, llm, context_len)\n\n self.examples = \"\"\n self.agent_prompt = zeroshot_agent_prompt\n self.name = \"ZeroshotThink_HotPotQA_run_Agent\"\n \n def forward(self):\n self._think()\n action_type, argument = self._action()\n return action_type, argument\n\n def _build_agent_prompt(self) -> str:\n return self.agent_prompt.format(\n question = self.question,\n scratchpad = self.scratchpad)\n \nclass PlannerAgent(BaseAgent):\n def __init__(self,\n question: str,\n key: str,\n llm,\n context_len: int = 2000\n ) -> None:\n super().__init__(question, key, llm, context_len)\n\n self.examples = PLANNER_EXAMPLE\n self.plan_example = PLAN_EXAMPLE\n self.agent_prompt = planner_agent_prompt\n self.plan_prompt = plan_prompt\n self.name = \"Planner_HotPotQA_run_Agent\"\n self._plan()\n \n def _plan(self):\n self.plan = format_step(self.llm(self._build_plan_prompt()))\n\n \n def _build_plan_prompt(self):\n return self.plan_prompt.format(\n examples = self.plan_example,\n question = self.question,\n )\n \n def forward(self):\n action_type, argument = self._action()\n return action_type, argument\n\n def _build_agent_prompt(self) -> str:\n prompt = self.agent_prompt.format(\n examples = self.examples,\n question = self.question,\n plan = self.plan,\n scratchpad = self.scratchpad)\n return prompt\n\nclass PlannerReactAgent(PlannerAgent):\n def __init__(self,\n question: str,\n key: str,\n llm,\n context_len: int = 2000\n ) -> None:\n super().__init__(question, key, llm, context_len)\n\n self.examples = PLANNERREACT_EXAMPLE\n self.plan_example = PLAN_EXAMPLE\n self.agent_prompt = plannerreact_agent_prompt\n self.plan_prompt = plan_prompt\n self.name = \"PlannerReact_HotPotQA_run_Agent\"\n self._plan()\n \n def forward(self):\n self._think()\n action_type, argument = self._action()\n return action_type, argument\n\n\ndef get_agent(agent_name):\n if agent_name in [\"Zeroshot_HotPotQA_run_Agent\"]:\n return ZeroshotAgent\n if agent_name in [\"ZeroshotThink_HotPotQA_run_Agent\"]:\n return ZeroshotThinkAgent\n if agent_name in [\"React_HotPotQA_run_Agent\"]:\n return ReactAgent\n if agent_name in [\"Planner_HotPotQA_run_Agent\"]:\n return PlannerAgent\n if agent_name in [\"PlannerReact_HotPotQA_run_Agent\"]:\n return PlannerReactAgent","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.parse_action","uri":"program://BOLAA/function/hotpotqa_run.agent_arch.parse_action#L26-L36","kind":"function","name":"parse_action","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":26,"end_line":36,"context_start_line":6,"context_end_line":56,"code":"\"\"\"\n\nimport random\nimport re, string, os\nimport json \nimport time\nimport tiktoken\nfrom langchain.llms.base import BaseLLM\nfrom langchain import OpenAI, Wikipedia\nfrom langchain.docstore.base import Docstore\nfrom langchain.agents.react.base import DocstoreExplorer\nfrom langchain.prompts import PromptTemplate\nfrom collections import Counter\n\nfrom hotpotqa_run.pre_prompt import (react_agent_prompt, zeroshot_agent_prompt, \n plan_prompt, planner_agent_prompt, plannerreact_agent_prompt)\nfrom hotpotqa_run.fewshots import REACT_EXAMPLE, PLANNER_EXAMPLE, PLAN_EXAMPLE, PLANNERREACT_EXAMPLE\n\nfrom web_run.llms import token_enc\n\ndef parse_action(string):\n pattern = r'^(\\w+)\\[(.+)\\]$'\n match = re.match(pattern, string)\n \n if match:\n action_type = match.group(1)\n argument = match.group(2)\n return action_type, argument\n else:\n action_type, argument = fuzzy_parse_action(string)\n return action_type, argument\n \ndef fuzzy_parse_action(text):\n text = text.strip(' ').strip('.')\n pattern = r'^(\\w+)\\[(.+)\\]'\n match = re.match(pattern, text)\n if match:\n action_type = match.group(1)\n argument = match.group(2)\n return action_type, argument\n else:\n return text, ''\n\ndef format_step(step: str) -> str:\n return step.strip('\\n').strip().replace('\\n', '')\n\ndef truncate_scratchpad(scratchpad: str, n_tokens: int = 1600, tokenizer = token_enc) -> str:\n lines = scratchpad.split('\\n')\n observations = filter(lambda x: x.startswith('Observation'), lines)\n observations_by_tokens = sorted(observations, key=lambda x: len(tokenizer.encode(x)))\n while len(token_enc.encode('\\n'.join(lines))) > n_tokens:","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.fuzzy_parse_action","uri":"program://BOLAA/function/hotpotqa_run.agent_arch.fuzzy_parse_action#L38-L47","kind":"function","name":"fuzzy_parse_action","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":38,"end_line":47,"context_start_line":18,"context_end_line":67,"code":"from collections import Counter\n\nfrom hotpotqa_run.pre_prompt import (react_agent_prompt, zeroshot_agent_prompt, \n plan_prompt, planner_agent_prompt, plannerreact_agent_prompt)\nfrom hotpotqa_run.fewshots import REACT_EXAMPLE, PLANNER_EXAMPLE, PLAN_EXAMPLE, PLANNERREACT_EXAMPLE\n\nfrom web_run.llms import token_enc\n\ndef parse_action(string):\n pattern = r'^(\\w+)\\[(.+)\\]$'\n match = re.match(pattern, string)\n \n if match:\n action_type = match.group(1)\n argument = match.group(2)\n return action_type, argument\n else:\n action_type, argument = fuzzy_parse_action(string)\n return action_type, argument\n \ndef fuzzy_parse_action(text):\n text = text.strip(' ').strip('.')\n pattern = r'^(\\w+)\\[(.+)\\]'\n match = re.match(pattern, text)\n if match:\n action_type = match.group(1)\n argument = match.group(2)\n return action_type, argument\n else:\n return text, ''\n\ndef format_step(step: str) -> str:\n return step.strip('\\n').strip().replace('\\n', '')\n\ndef truncate_scratchpad(scratchpad: str, n_tokens: int = 1600, tokenizer = token_enc) -> str:\n lines = scratchpad.split('\\n')\n observations = filter(lambda x: x.startswith('Observation'), lines)\n observations_by_tokens = sorted(observations, key=lambda x: len(tokenizer.encode(x)))\n while len(token_enc.encode('\\n'.join(lines))) > n_tokens:\n largest_observation = observations_by_tokens.pop(-1)\n ind = lines.index(largest_observation)\n lines[ind] = largest_observation.split(':')[0] + ': [truncated wikipedia excerpt]'\n return '\\n'.join(lines)\n\ndef normalize_answer(s):\n def remove_articles(text):\n return re.sub(r\"\\b(a|an|the)\\b\", \" \", text)\n \n def white_space_fix(text):\n return \" \".join(text.split())","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.format_step","uri":"program://BOLAA/function/hotpotqa_run.agent_arch.format_step#L49-L50","kind":"function","name":"format_step","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":49,"end_line":50,"context_start_line":29,"context_end_line":70,"code":" \n if match:\n action_type = match.group(1)\n argument = match.group(2)\n return action_type, argument\n else:\n action_type, argument = fuzzy_parse_action(string)\n return action_type, argument\n \ndef fuzzy_parse_action(text):\n text = text.strip(' ').strip('.')\n pattern = r'^(\\w+)\\[(.+)\\]'\n match = re.match(pattern, text)\n if match:\n action_type = match.group(1)\n argument = match.group(2)\n return action_type, argument\n else:\n return text, ''\n\ndef format_step(step: str) -> str:\n return step.strip('\\n').strip().replace('\\n', '')\n\ndef truncate_scratchpad(scratchpad: str, n_tokens: int = 1600, tokenizer = token_enc) -> str:\n lines = scratchpad.split('\\n')\n observations = filter(lambda x: x.startswith('Observation'), lines)\n observations_by_tokens = sorted(observations, key=lambda x: len(tokenizer.encode(x)))\n while len(token_enc.encode('\\n'.join(lines))) > n_tokens:\n largest_observation = observations_by_tokens.pop(-1)\n ind = lines.index(largest_observation)\n lines[ind] = largest_observation.split(':')[0] + ': [truncated wikipedia excerpt]'\n return '\\n'.join(lines)\n\ndef normalize_answer(s):\n def remove_articles(text):\n return re.sub(r\"\\b(a|an|the)\\b\", \" \", text)\n \n def white_space_fix(text):\n return \" \".join(text.split())\n \n def remove_punc(text):\n exclude = set(string.punctuation)","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.truncate_scratchpad","uri":"program://BOLAA/function/hotpotqa_run.agent_arch.truncate_scratchpad#L52-L60","kind":"function","name":"truncate_scratchpad","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":52,"end_line":60,"context_start_line":32,"context_end_line":80,"code":" argument = match.group(2)\n return action_type, argument\n else:\n action_type, argument = fuzzy_parse_action(string)\n return action_type, argument\n \ndef fuzzy_parse_action(text):\n text = text.strip(' ').strip('.')\n pattern = r'^(\\w+)\\[(.+)\\]'\n match = re.match(pattern, text)\n if match:\n action_type = match.group(1)\n argument = match.group(2)\n return action_type, argument\n else:\n return text, ''\n\ndef format_step(step: str) -> str:\n return step.strip('\\n').strip().replace('\\n', '')\n\ndef truncate_scratchpad(scratchpad: str, n_tokens: int = 1600, tokenizer = token_enc) -> str:\n lines = scratchpad.split('\\n')\n observations = filter(lambda x: x.startswith('Observation'), lines)\n observations_by_tokens = sorted(observations, key=lambda x: len(tokenizer.encode(x)))\n while len(token_enc.encode('\\n'.join(lines))) > n_tokens:\n largest_observation = observations_by_tokens.pop(-1)\n ind = lines.index(largest_observation)\n lines[ind] = largest_observation.split(':')[0] + ': [truncated wikipedia excerpt]'\n return '\\n'.join(lines)\n\ndef normalize_answer(s):\n def remove_articles(text):\n return re.sub(r\"\\b(a|an|the)\\b\", \" \", text)\n \n def white_space_fix(text):\n return \" \".join(text.split())\n \n def remove_punc(text):\n exclude = set(string.punctuation)\n return \"\".join(ch for ch in text if ch not in exclude)\n \n def lower(text):\n return text.lower()\n\n return white_space_fix(remove_articles(remove_punc(lower(s))))\n\ndef f1_score(prediction, ground_truth):\n normalized_prediction = normalize_answer(prediction)\n normalized_ground_truth = normalize_answer(ground_truth)","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.normalize_answer","uri":"program://BOLAA/function/hotpotqa_run.agent_arch.normalize_answer#L62-L76","kind":"function","name":"normalize_answer","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":62,"end_line":76,"context_start_line":42,"context_end_line":96,"code":" if match:\n action_type = match.group(1)\n argument = match.group(2)\n return action_type, argument\n else:\n return text, ''\n\ndef format_step(step: str) -> str:\n return step.strip('\\n').strip().replace('\\n', '')\n\ndef truncate_scratchpad(scratchpad: str, n_tokens: int = 1600, tokenizer = token_enc) -> str:\n lines = scratchpad.split('\\n')\n observations = filter(lambda x: x.startswith('Observation'), lines)\n observations_by_tokens = sorted(observations, key=lambda x: len(tokenizer.encode(x)))\n while len(token_enc.encode('\\n'.join(lines))) > n_tokens:\n largest_observation = observations_by_tokens.pop(-1)\n ind = lines.index(largest_observation)\n lines[ind] = largest_observation.split(':')[0] + ': [truncated wikipedia excerpt]'\n return '\\n'.join(lines)\n\ndef normalize_answer(s):\n def remove_articles(text):\n return re.sub(r\"\\b(a|an|the)\\b\", \" \", text)\n \n def white_space_fix(text):\n return \" \".join(text.split())\n \n def remove_punc(text):\n exclude = set(string.punctuation)\n return \"\".join(ch for ch in text if ch not in exclude)\n \n def lower(text):\n return text.lower()\n\n return white_space_fix(remove_articles(remove_punc(lower(s))))\n\ndef f1_score(prediction, ground_truth):\n normalized_prediction = normalize_answer(prediction)\n normalized_ground_truth = normalize_answer(ground_truth)\n\n ZERO_METRIC = (0, 0, 0)\n\n if normalized_prediction in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n if normalized_ground_truth in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n \n prediction_tokens = normalized_prediction.split()\n ground_truth_tokens = normalized_ground_truth.split()\n common = Counter(prediction_tokens) & Counter(ground_truth_tokens)\n num_same = sum(common.values())\n if num_same == 0:\n return ZERO_METRIC\n precision = 1.0 * num_same / len(prediction_tokens)\n recall = 1.0 * num_same / len(ground_truth_tokens)","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.f1_score","uri":"program://BOLAA/function/hotpotqa_run.agent_arch.f1_score#L78-L98","kind":"function","name":"f1_score","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":78,"end_line":98,"context_start_line":58,"context_end_line":118,"code":" ind = lines.index(largest_observation)\n lines[ind] = largest_observation.split(':')[0] + ': [truncated wikipedia excerpt]'\n return '\\n'.join(lines)\n\ndef normalize_answer(s):\n def remove_articles(text):\n return re.sub(r\"\\b(a|an|the)\\b\", \" \", text)\n \n def white_space_fix(text):\n return \" \".join(text.split())\n \n def remove_punc(text):\n exclude = set(string.punctuation)\n return \"\".join(ch for ch in text if ch not in exclude)\n \n def lower(text):\n return text.lower()\n\n return white_space_fix(remove_articles(remove_punc(lower(s))))\n\ndef f1_score(prediction, ground_truth):\n normalized_prediction = normalize_answer(prediction)\n normalized_ground_truth = normalize_answer(ground_truth)\n\n ZERO_METRIC = (0, 0, 0)\n\n if normalized_prediction in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n if normalized_ground_truth in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n \n prediction_tokens = normalized_prediction.split()\n ground_truth_tokens = normalized_ground_truth.split()\n common = Counter(prediction_tokens) & Counter(ground_truth_tokens)\n num_same = sum(common.values())\n if num_same == 0:\n return ZERO_METRIC\n precision = 1.0 * num_same / len(prediction_tokens)\n recall = 1.0 * num_same / len(ground_truth_tokens)\n f1 = (2 * precision * recall) / (precision + recall)\n return f1, precision, recall\n\ndef EM(answer, key) -> bool:\n return normalize_answer(answer) == normalize_answer(key)\n\n\nclass BaseAgent:\n def __init__(self,\n question: str,\n key: str,\n llm: BaseLLM,\n context_len: int = 2000,\n max_steps: int= 10,\n docstore: Docstore = Wikipedia()\n ) -> None:\n \n self.question = question\n self.answer = ''\n self.key = key\n self.max_steps = max_steps\n self.agent_prompt = \"\"","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.EM","uri":"program://BOLAA/function/hotpotqa_run.agent_arch.EM#L100-L101","kind":"function","name":"EM","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":100,"end_line":101,"context_start_line":80,"context_end_line":121,"code":" normalized_ground_truth = normalize_answer(ground_truth)\n\n ZERO_METRIC = (0, 0, 0)\n\n if normalized_prediction in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n if normalized_ground_truth in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n \n prediction_tokens = normalized_prediction.split()\n ground_truth_tokens = normalized_ground_truth.split()\n common = Counter(prediction_tokens) & Counter(ground_truth_tokens)\n num_same = sum(common.values())\n if num_same == 0:\n return ZERO_METRIC\n precision = 1.0 * num_same / len(prediction_tokens)\n recall = 1.0 * num_same / len(ground_truth_tokens)\n f1 = (2 * precision * recall) / (precision + recall)\n return f1, precision, recall\n\ndef EM(answer, key) -> bool:\n return normalize_answer(answer) == normalize_answer(key)\n\n\nclass BaseAgent:\n def __init__(self,\n question: str,\n key: str,\n llm: BaseLLM,\n context_len: int = 2000,\n max_steps: int= 10,\n docstore: Docstore = Wikipedia()\n ) -> None:\n \n self.question = question\n self.answer = ''\n self.key = key\n self.max_steps = max_steps\n self.agent_prompt = \"\"\n self.examples = \"\"\n self.context_len = context_len\n self.run_error = False","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.BaseAgent","uri":"program://BOLAA/class/hotpotqa_run.agent_arch.BaseAgent#L104-L228","kind":"class","name":"BaseAgent","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":104,"end_line":228,"context_start_line":84,"context_end_line":248,"code":" if normalized_prediction in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n if normalized_ground_truth in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n \n prediction_tokens = normalized_prediction.split()\n ground_truth_tokens = normalized_ground_truth.split()\n common = Counter(prediction_tokens) & Counter(ground_truth_tokens)\n num_same = sum(common.values())\n if num_same == 0:\n return ZERO_METRIC\n precision = 1.0 * num_same / len(prediction_tokens)\n recall = 1.0 * num_same / len(ground_truth_tokens)\n f1 = (2 * precision * recall) / (precision + recall)\n return f1, precision, recall\n\ndef EM(answer, key) -> bool:\n return normalize_answer(answer) == normalize_answer(key)\n\n\nclass BaseAgent:\n def __init__(self,\n question: str,\n key: str,\n llm: BaseLLM,\n context_len: int = 2000,\n max_steps: int= 10,\n docstore: Docstore = Wikipedia()\n ) -> None:\n \n self.question = question\n self.answer = ''\n self.key = key\n self.max_steps = max_steps\n self.agent_prompt = \"\"\n self.examples = \"\"\n self.context_len = context_len\n self.run_error = False\n self.name = \"Base_HotPotQA_run_Agent\"\n\n self.docstore = DocstoreExplorer(docstore) # Search, Lookup\n self.llm = llm\n \n self.enc = token_enc\n self.__reset_agent()\n \n def run(self, reset = True) -> None:\n if reset:\n self.__reset_agent()\n \n while not self.is_halted() and not self.is_finished() and not self.run_error:\n self.step()\n \n def prompt_agent(self) -> str:\n generation = self.llm(self._build_agent_prompt())\n self.check_run_error(generation)\n return format_step(generation)\n \n def check_run_error(self, text):\n if text in [\"No response\"]:\n self.run_error = True\n \n def is_finished(self) -> bool:\n return self.finished\n \n def reward(self) -> float:\n return f1_score(self.answer, self.key) \n \n def is_correct(self) -> bool:\n return EM(self.answer, self.key)\n\n def is_halted(self) -> bool:\n return ((self.step_n > self.max_steps)\n or (len(self.enc.encode(self._build_agent_prompt())) > self.context_len)\n ) and not self.finished\n\n def __reset_agent(self) -> None:\n self.step_n = 1\n self.finished = False\n self.scratchpad: str = ''\n\n def set_qa(self, question: str, key: str) -> None:\n self.question = question\n self.key = key\n\n def _think(self):\n self.scratchpad += f'\\nThought {self.step_n}:'\n self.scratchpad += ' ' + self.prompt_agent()\n print(self.scratchpad.split('\\n')[-1])\n \n def _action(self):\n self.scratchpad += f'\\nAction {self.step_n}:'\n action = self.prompt_agent()\n self.scratchpad += ' ' + action\n action_type, argument = parse_action(action)\n print(self.scratchpad.split('\\n')[-1])\n return action_type, argument\n \n def step(self) -> None:\n \n # agent forward\n ret = self.forward()\n if ret:\n action_type, argument = ret[0], ret[1]\n else:\n action_type = ret\n \n # Observe\n self.scratchpad += f'\\nObservation {self.step_n}: '\n \n if action_type == 'Finish':\n self.answer = argument\n if self.is_correct():\n self.scratchpad += 'Answer is CORRECT'\n else: \n self.scratchpad += 'Answer is INCORRECT'\n self.finished = True\n self.step_n += 1\n return\n\n if action_type == 'Search':\n try:\n self.scratchpad += format_step(self.docstore.search(argument))\n except Exception as e:\n print(e)\n self.scratchpad += f'Could not find that page, please try again.'\n \n elif action_type == 'Lookup':\n try:\n self.scratchpad += format_step(self.docstore.lookup(argument))\n except ValueError:\n self.scratchpad += f'The last page Searched was not found, so you cannot Lookup a keyword in it. Please try one of the similar pages given.'\n\n else:\n self.scratchpad += 'Invalid Action. Valid Actions are Lookup[] Search[] and Finish[].'\n\n print(self.scratchpad.split('\\n')[-1])\n\n self.step_n += 1\n \n def _build_agent_prompt(self) -> str:\n raise NotImplementedError\n \n def forward(self):\n raise NotImplementedError\n \nclass ReactAgent(BaseAgent):\n def __init__(self,\n question: str,\n key: str,\n llm,\n context_len: int = 2000\n ) -> None:\n super().__init__(question, key, llm, context_len)\n\n self.examples = REACT_EXAMPLE\n self.agent_prompt = react_agent_prompt\n self.name = \"React_HotPotQA_run_Agent\"\n \n def forward(self):\n self._think()\n action_type, argument = self._action()\n return action_type, argument\n\n def _build_agent_prompt(self) -> str:","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.ReactAgent","uri":"program://BOLAA/class/hotpotqa_run.agent_arch.ReactAgent#L230-L252","kind":"class","name":"ReactAgent","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":230,"end_line":252,"context_start_line":210,"context_end_line":272,"code":" \n elif action_type == 'Lookup':\n try:\n self.scratchpad += format_step(self.docstore.lookup(argument))\n except ValueError:\n self.scratchpad += f'The last page Searched was not found, so you cannot Lookup a keyword in it. Please try one of the similar pages given.'\n\n else:\n self.scratchpad += 'Invalid Action. Valid Actions are Lookup[] Search[] and Finish[].'\n\n print(self.scratchpad.split('\\n')[-1])\n\n self.step_n += 1\n \n def _build_agent_prompt(self) -> str:\n raise NotImplementedError\n \n def forward(self):\n raise NotImplementedError\n \nclass ReactAgent(BaseAgent):\n def __init__(self,\n question: str,\n key: str,\n llm,\n context_len: int = 2000\n ) -> None:\n super().__init__(question, key, llm, context_len)\n\n self.examples = REACT_EXAMPLE\n self.agent_prompt = react_agent_prompt\n self.name = \"React_HotPotQA_run_Agent\"\n \n def forward(self):\n self._think()\n action_type, argument = self._action()\n return action_type, argument\n\n def _build_agent_prompt(self) -> str:\n return self.agent_prompt.format(\n examples = self.examples,\n question = self.question,\n scratchpad = self.scratchpad)\n \nclass ZeroshotAgent(BaseAgent):\n def __init__(self,\n question: str,\n key: str,\n llm,\n context_len: int = 2000\n ) -> None:\n super().__init__(question, key, llm, context_len)\n\n self.examples = \"\"\n self.agent_prompt = zeroshot_agent_prompt\n self.name = \"Zeroshot_HotPotQA_run_Agent\"\n \n def forward(self):\n action_type, argument = self._action()\n return action_type, argument\n\n def _build_agent_prompt(self) -> str:\n return self.agent_prompt.format(","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.ZeroshotAgent","uri":"program://BOLAA/class/hotpotqa_run.agent_arch.ZeroshotAgent#L254-L274","kind":"class","name":"ZeroshotAgent","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":254,"end_line":274,"context_start_line":234,"context_end_line":294,"code":" llm,\n context_len: int = 2000\n ) -> None:\n super().__init__(question, key, llm, context_len)\n\n self.examples = REACT_EXAMPLE\n self.agent_prompt = react_agent_prompt\n self.name = \"React_HotPotQA_run_Agent\"\n \n def forward(self):\n self._think()\n action_type, argument = self._action()\n return action_type, argument\n\n def _build_agent_prompt(self) -> str:\n return self.agent_prompt.format(\n examples = self.examples,\n question = self.question,\n scratchpad = self.scratchpad)\n \nclass ZeroshotAgent(BaseAgent):\n def __init__(self,\n question: str,\n key: str,\n llm,\n context_len: int = 2000\n ) -> None:\n super().__init__(question, key, llm, context_len)\n\n self.examples = \"\"\n self.agent_prompt = zeroshot_agent_prompt\n self.name = \"Zeroshot_HotPotQA_run_Agent\"\n \n def forward(self):\n action_type, argument = self._action()\n return action_type, argument\n\n def _build_agent_prompt(self) -> str:\n return self.agent_prompt.format(\n question = self.question,\n scratchpad = self.scratchpad)\n \nclass ZeroshotThinkAgent(BaseAgent):\n def __init__(self,\n question: str,\n key: str,\n llm,\n context_len: int = 2000\n ) -> None:\n super().__init__(question, key, llm, context_len)\n\n self.examples = \"\"\n self.agent_prompt = zeroshot_agent_prompt\n self.name = \"ZeroshotThink_HotPotQA_run_Agent\"\n \n def forward(self):\n self._think()\n action_type, argument = self._action()\n return action_type, argument\n\n def _build_agent_prompt(self) -> str:","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.ZeroshotThinkAgent","uri":"program://BOLAA/class/hotpotqa_run.agent_arch.ZeroshotThinkAgent#L276-L297","kind":"class","name":"ZeroshotThinkAgent","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":276,"end_line":297,"context_start_line":256,"context_end_line":317,"code":" question: str,\n key: str,\n llm,\n context_len: int = 2000\n ) -> None:\n super().__init__(question, key, llm, context_len)\n\n self.examples = \"\"\n self.agent_prompt = zeroshot_agent_prompt\n self.name = \"Zeroshot_HotPotQA_run_Agent\"\n \n def forward(self):\n action_type, argument = self._action()\n return action_type, argument\n\n def _build_agent_prompt(self) -> str:\n return self.agent_prompt.format(\n question = self.question,\n scratchpad = self.scratchpad)\n \nclass ZeroshotThinkAgent(BaseAgent):\n def __init__(self,\n question: str,\n key: str,\n llm,\n context_len: int = 2000\n ) -> None:\n super().__init__(question, key, llm, context_len)\n\n self.examples = \"\"\n self.agent_prompt = zeroshot_agent_prompt\n self.name = \"ZeroshotThink_HotPotQA_run_Agent\"\n \n def forward(self):\n self._think()\n action_type, argument = self._action()\n return action_type, argument\n\n def _build_agent_prompt(self) -> str:\n return self.agent_prompt.format(\n question = self.question,\n scratchpad = self.scratchpad)\n \nclass PlannerAgent(BaseAgent):\n def __init__(self,\n question: str,\n key: str,\n llm,\n context_len: int = 2000\n ) -> None:\n super().__init__(question, key, llm, context_len)\n\n self.examples = PLANNER_EXAMPLE\n self.plan_example = PLAN_EXAMPLE\n self.agent_prompt = planner_agent_prompt\n self.plan_prompt = plan_prompt\n self.name = \"Planner_HotPotQA_run_Agent\"\n self._plan()\n \n def _plan(self):\n self.plan = format_step(self.llm(self._build_plan_prompt()))\n","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.PlannerAgent","uri":"program://BOLAA/class/hotpotqa_run.agent_arch.PlannerAgent#L299-L335","kind":"class","name":"PlannerAgent","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":299,"end_line":335,"context_start_line":279,"context_end_line":355,"code":" key: str,\n llm,\n context_len: int = 2000\n ) -> None:\n super().__init__(question, key, llm, context_len)\n\n self.examples = \"\"\n self.agent_prompt = zeroshot_agent_prompt\n self.name = \"ZeroshotThink_HotPotQA_run_Agent\"\n \n def forward(self):\n self._think()\n action_type, argument = self._action()\n return action_type, argument\n\n def _build_agent_prompt(self) -> str:\n return self.agent_prompt.format(\n question = self.question,\n scratchpad = self.scratchpad)\n \nclass PlannerAgent(BaseAgent):\n def __init__(self,\n question: str,\n key: str,\n llm,\n context_len: int = 2000\n ) -> None:\n super().__init__(question, key, llm, context_len)\n\n self.examples = PLANNER_EXAMPLE\n self.plan_example = PLAN_EXAMPLE\n self.agent_prompt = planner_agent_prompt\n self.plan_prompt = plan_prompt\n self.name = \"Planner_HotPotQA_run_Agent\"\n self._plan()\n \n def _plan(self):\n self.plan = format_step(self.llm(self._build_plan_prompt()))\n\n \n def _build_plan_prompt(self):\n return self.plan_prompt.format(\n examples = self.plan_example,\n question = self.question,\n )\n \n def forward(self):\n action_type, argument = self._action()\n return action_type, argument\n\n def _build_agent_prompt(self) -> str:\n prompt = self.agent_prompt.format(\n examples = self.examples,\n question = self.question,\n plan = self.plan,\n scratchpad = self.scratchpad)\n return prompt\n\nclass PlannerReactAgent(PlannerAgent):\n def __init__(self,\n question: str,\n key: str,\n llm,\n context_len: int = 2000\n ) -> None:\n super().__init__(question, key, llm, context_len)\n\n self.examples = PLANNERREACT_EXAMPLE\n self.plan_example = PLAN_EXAMPLE\n self.agent_prompt = plannerreact_agent_prompt\n self.plan_prompt = plan_prompt\n self.name = \"PlannerReact_HotPotQA_run_Agent\"\n self._plan()\n \n def forward(self):\n self._think()\n action_type, argument = self._action()","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.PlannerReactAgent","uri":"program://BOLAA/class/hotpotqa_run.agent_arch.PlannerReactAgent#L337-L356","kind":"class","name":"PlannerReactAgent","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":337,"end_line":356,"context_start_line":317,"context_end_line":369,"code":"\n \n def _build_plan_prompt(self):\n return self.plan_prompt.format(\n examples = self.plan_example,\n question = self.question,\n )\n \n def forward(self):\n action_type, argument = self._action()\n return action_type, argument\n\n def _build_agent_prompt(self) -> str:\n prompt = self.agent_prompt.format(\n examples = self.examples,\n question = self.question,\n plan = self.plan,\n scratchpad = self.scratchpad)\n return prompt\n\nclass PlannerReactAgent(PlannerAgent):\n def __init__(self,\n question: str,\n key: str,\n llm,\n context_len: int = 2000\n ) -> None:\n super().__init__(question, key, llm, context_len)\n\n self.examples = PLANNERREACT_EXAMPLE\n self.plan_example = PLAN_EXAMPLE\n self.agent_prompt = plannerreact_agent_prompt\n self.plan_prompt = plan_prompt\n self.name = \"PlannerReact_HotPotQA_run_Agent\"\n self._plan()\n \n def forward(self):\n self._think()\n action_type, argument = self._action()\n return action_type, argument\n\n\ndef get_agent(agent_name):\n if agent_name in [\"Zeroshot_HotPotQA_run_Agent\"]:\n return ZeroshotAgent\n if agent_name in [\"ZeroshotThink_HotPotQA_run_Agent\"]:\n return ZeroshotThinkAgent\n if agent_name in [\"React_HotPotQA_run_Agent\"]:\n return ReactAgent\n if agent_name in [\"Planner_HotPotQA_run_Agent\"]:\n return PlannerAgent\n if agent_name in [\"PlannerReact_HotPotQA_run_Agent\"]:\n return PlannerReactAgent","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.get_agent","uri":"program://BOLAA/function/hotpotqa_run.agent_arch.get_agent#L359-L369","kind":"function","name":"get_agent","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":359,"end_line":369,"context_start_line":339,"context_end_line":369,"code":" question: str,\n key: str,\n llm,\n context_len: int = 2000\n ) -> None:\n super().__init__(question, key, llm, context_len)\n\n self.examples = PLANNERREACT_EXAMPLE\n self.plan_example = PLAN_EXAMPLE\n self.agent_prompt = plannerreact_agent_prompt\n self.plan_prompt = plan_prompt\n self.name = \"PlannerReact_HotPotQA_run_Agent\"\n self._plan()\n \n def forward(self):\n self._think()\n action_type, argument = self._action()\n return action_type, argument\n\n\ndef get_agent(agent_name):\n if agent_name in [\"Zeroshot_HotPotQA_run_Agent\"]:\n return ZeroshotAgent\n if agent_name in [\"ZeroshotThink_HotPotQA_run_Agent\"]:\n return ZeroshotThinkAgent\n if agent_name in [\"React_HotPotQA_run_Agent\"]:\n return ReactAgent\n if agent_name in [\"Planner_HotPotQA_run_Agent\"]:\n return PlannerAgent\n if agent_name in [\"PlannerReact_HotPotQA_run_Agent\"]:\n return PlannerReactAgent","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.remove_articles","uri":"program://BOLAA/function/hotpotqa_run.agent_arch.remove_articles#L63-L64","kind":"function","name":"remove_articles","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":63,"end_line":64,"context_start_line":43,"context_end_line":84,"code":" action_type = match.group(1)\n argument = match.group(2)\n return action_type, argument\n else:\n return text, ''\n\ndef format_step(step: str) -> str:\n return step.strip('\\n').strip().replace('\\n', '')\n\ndef truncate_scratchpad(scratchpad: str, n_tokens: int = 1600, tokenizer = token_enc) -> str:\n lines = scratchpad.split('\\n')\n observations = filter(lambda x: x.startswith('Observation'), lines)\n observations_by_tokens = sorted(observations, key=lambda x: len(tokenizer.encode(x)))\n while len(token_enc.encode('\\n'.join(lines))) > n_tokens:\n largest_observation = observations_by_tokens.pop(-1)\n ind = lines.index(largest_observation)\n lines[ind] = largest_observation.split(':')[0] + ': [truncated wikipedia excerpt]'\n return '\\n'.join(lines)\n\ndef normalize_answer(s):\n def remove_articles(text):\n return re.sub(r\"\\b(a|an|the)\\b\", \" \", text)\n \n def white_space_fix(text):\n return \" \".join(text.split())\n \n def remove_punc(text):\n exclude = set(string.punctuation)\n return \"\".join(ch for ch in text if ch not in exclude)\n \n def lower(text):\n return text.lower()\n\n return white_space_fix(remove_articles(remove_punc(lower(s))))\n\ndef f1_score(prediction, ground_truth):\n normalized_prediction = normalize_answer(prediction)\n normalized_ground_truth = normalize_answer(ground_truth)\n\n ZERO_METRIC = (0, 0, 0)\n\n if normalized_prediction in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.white_space_fix","uri":"program://BOLAA/function/hotpotqa_run.agent_arch.white_space_fix#L66-L67","kind":"function","name":"white_space_fix","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":66,"end_line":67,"context_start_line":46,"context_end_line":87,"code":" else:\n return text, ''\n\ndef format_step(step: str) -> str:\n return step.strip('\\n').strip().replace('\\n', '')\n\ndef truncate_scratchpad(scratchpad: str, n_tokens: int = 1600, tokenizer = token_enc) -> str:\n lines = scratchpad.split('\\n')\n observations = filter(lambda x: x.startswith('Observation'), lines)\n observations_by_tokens = sorted(observations, key=lambda x: len(tokenizer.encode(x)))\n while len(token_enc.encode('\\n'.join(lines))) > n_tokens:\n largest_observation = observations_by_tokens.pop(-1)\n ind = lines.index(largest_observation)\n lines[ind] = largest_observation.split(':')[0] + ': [truncated wikipedia excerpt]'\n return '\\n'.join(lines)\n\ndef normalize_answer(s):\n def remove_articles(text):\n return re.sub(r\"\\b(a|an|the)\\b\", \" \", text)\n \n def white_space_fix(text):\n return \" \".join(text.split())\n \n def remove_punc(text):\n exclude = set(string.punctuation)\n return \"\".join(ch for ch in text if ch not in exclude)\n \n def lower(text):\n return text.lower()\n\n return white_space_fix(remove_articles(remove_punc(lower(s))))\n\ndef f1_score(prediction, ground_truth):\n normalized_prediction = normalize_answer(prediction)\n normalized_ground_truth = normalize_answer(ground_truth)\n\n ZERO_METRIC = (0, 0, 0)\n\n if normalized_prediction in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n if normalized_ground_truth in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.remove_punc","uri":"program://BOLAA/function/hotpotqa_run.agent_arch.remove_punc#L69-L71","kind":"function","name":"remove_punc","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":69,"end_line":71,"context_start_line":49,"context_end_line":91,"code":"def format_step(step: str) -> str:\n return step.strip('\\n').strip().replace('\\n', '')\n\ndef truncate_scratchpad(scratchpad: str, n_tokens: int = 1600, tokenizer = token_enc) -> str:\n lines = scratchpad.split('\\n')\n observations = filter(lambda x: x.startswith('Observation'), lines)\n observations_by_tokens = sorted(observations, key=lambda x: len(tokenizer.encode(x)))\n while len(token_enc.encode('\\n'.join(lines))) > n_tokens:\n largest_observation = observations_by_tokens.pop(-1)\n ind = lines.index(largest_observation)\n lines[ind] = largest_observation.split(':')[0] + ': [truncated wikipedia excerpt]'\n return '\\n'.join(lines)\n\ndef normalize_answer(s):\n def remove_articles(text):\n return re.sub(r\"\\b(a|an|the)\\b\", \" \", text)\n \n def white_space_fix(text):\n return \" \".join(text.split())\n \n def remove_punc(text):\n exclude = set(string.punctuation)\n return \"\".join(ch for ch in text if ch not in exclude)\n \n def lower(text):\n return text.lower()\n\n return white_space_fix(remove_articles(remove_punc(lower(s))))\n\ndef f1_score(prediction, ground_truth):\n normalized_prediction = normalize_answer(prediction)\n normalized_ground_truth = normalize_answer(ground_truth)\n\n ZERO_METRIC = (0, 0, 0)\n\n if normalized_prediction in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n if normalized_ground_truth in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n \n prediction_tokens = normalized_prediction.split()\n ground_truth_tokens = normalized_ground_truth.split()\n common = Counter(prediction_tokens) & Counter(ground_truth_tokens)","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.lower","uri":"program://BOLAA/function/hotpotqa_run.agent_arch.lower#L73-L74","kind":"function","name":"lower","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":73,"end_line":74,"context_start_line":53,"context_end_line":94,"code":" lines = scratchpad.split('\\n')\n observations = filter(lambda x: x.startswith('Observation'), lines)\n observations_by_tokens = sorted(observations, key=lambda x: len(tokenizer.encode(x)))\n while len(token_enc.encode('\\n'.join(lines))) > n_tokens:\n largest_observation = observations_by_tokens.pop(-1)\n ind = lines.index(largest_observation)\n lines[ind] = largest_observation.split(':')[0] + ': [truncated wikipedia excerpt]'\n return '\\n'.join(lines)\n\ndef normalize_answer(s):\n def remove_articles(text):\n return re.sub(r\"\\b(a|an|the)\\b\", \" \", text)\n \n def white_space_fix(text):\n return \" \".join(text.split())\n \n def remove_punc(text):\n exclude = set(string.punctuation)\n return \"\".join(ch for ch in text if ch not in exclude)\n \n def lower(text):\n return text.lower()\n\n return white_space_fix(remove_articles(remove_punc(lower(s))))\n\ndef f1_score(prediction, ground_truth):\n normalized_prediction = normalize_answer(prediction)\n normalized_ground_truth = normalize_answer(ground_truth)\n\n ZERO_METRIC = (0, 0, 0)\n\n if normalized_prediction in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n if normalized_ground_truth in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n \n prediction_tokens = normalized_prediction.split()\n ground_truth_tokens = normalized_ground_truth.split()\n common = Counter(prediction_tokens) & Counter(ground_truth_tokens)\n num_same = sum(common.values())\n if num_same == 0:\n return ZERO_METRIC","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.__init__","uri":"program://BOLAA/function/hotpotqa_run.agent_arch.__init__#L338-L351","kind":"function","name":"__init__","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":338,"end_line":351,"context_start_line":318,"context_end_line":369,"code":" \n def _build_plan_prompt(self):\n return self.plan_prompt.format(\n examples = self.plan_example,\n question = self.question,\n )\n \n def forward(self):\n action_type, argument = self._action()\n return action_type, argument\n\n def _build_agent_prompt(self) -> str:\n prompt = self.agent_prompt.format(\n examples = self.examples,\n question = self.question,\n plan = self.plan,\n scratchpad = self.scratchpad)\n return prompt\n\nclass PlannerReactAgent(PlannerAgent):\n def __init__(self,\n question: str,\n key: str,\n llm,\n context_len: int = 2000\n ) -> None:\n super().__init__(question, key, llm, context_len)\n\n self.examples = PLANNERREACT_EXAMPLE\n self.plan_example = PLAN_EXAMPLE\n self.agent_prompt = plannerreact_agent_prompt\n self.plan_prompt = plan_prompt\n self.name = \"PlannerReact_HotPotQA_run_Agent\"\n self._plan()\n \n def forward(self):\n self._think()\n action_type, argument = self._action()\n return action_type, argument\n\n\ndef get_agent(agent_name):\n if agent_name in [\"Zeroshot_HotPotQA_run_Agent\"]:\n return ZeroshotAgent\n if agent_name in [\"ZeroshotThink_HotPotQA_run_Agent\"]:\n return ZeroshotThinkAgent\n if agent_name in [\"React_HotPotQA_run_Agent\"]:\n return ReactAgent\n if agent_name in [\"Planner_HotPotQA_run_Agent\"]:\n return PlannerAgent\n if agent_name in [\"PlannerReact_HotPotQA_run_Agent\"]:\n return PlannerReactAgent","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.run","uri":"program://BOLAA/function/hotpotqa_run.agent_arch.run#L130-L135","kind":"function","name":"run","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":130,"end_line":135,"context_start_line":110,"context_end_line":155,"code":" max_steps: int= 10,\n docstore: Docstore = Wikipedia()\n ) -> None:\n \n self.question = question\n self.answer = ''\n self.key = key\n self.max_steps = max_steps\n self.agent_prompt = \"\"\n self.examples = \"\"\n self.context_len = context_len\n self.run_error = False\n self.name = \"Base_HotPotQA_run_Agent\"\n\n self.docstore = DocstoreExplorer(docstore) # Search, Lookup\n self.llm = llm\n \n self.enc = token_enc\n self.__reset_agent()\n \n def run(self, reset = True) -> None:\n if reset:\n self.__reset_agent()\n \n while not self.is_halted() and not self.is_finished() and not self.run_error:\n self.step()\n \n def prompt_agent(self) -> str:\n generation = self.llm(self._build_agent_prompt())\n self.check_run_error(generation)\n return format_step(generation)\n \n def check_run_error(self, text):\n if text in [\"No response\"]:\n self.run_error = True\n \n def is_finished(self) -> bool:\n return self.finished\n \n def reward(self) -> float:\n return f1_score(self.answer, self.key) \n \n def is_correct(self) -> bool:\n return EM(self.answer, self.key)\n\n def is_halted(self) -> bool:","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.prompt_agent","uri":"program://BOLAA/function/hotpotqa_run.agent_arch.prompt_agent#L137-L140","kind":"function","name":"prompt_agent","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":137,"end_line":140,"context_start_line":117,"context_end_line":160,"code":" self.max_steps = max_steps\n self.agent_prompt = \"\"\n self.examples = \"\"\n self.context_len = context_len\n self.run_error = False\n self.name = \"Base_HotPotQA_run_Agent\"\n\n self.docstore = DocstoreExplorer(docstore) # Search, Lookup\n self.llm = llm\n \n self.enc = token_enc\n self.__reset_agent()\n \n def run(self, reset = True) -> None:\n if reset:\n self.__reset_agent()\n \n while not self.is_halted() and not self.is_finished() and not self.run_error:\n self.step()\n \n def prompt_agent(self) -> str:\n generation = self.llm(self._build_agent_prompt())\n self.check_run_error(generation)\n return format_step(generation)\n \n def check_run_error(self, text):\n if text in [\"No response\"]:\n self.run_error = True\n \n def is_finished(self) -> bool:\n return self.finished\n \n def reward(self) -> float:\n return f1_score(self.answer, self.key) \n \n def is_correct(self) -> bool:\n return EM(self.answer, self.key)\n\n def is_halted(self) -> bool:\n return ((self.step_n > self.max_steps)\n or (len(self.enc.encode(self._build_agent_prompt())) > self.context_len)\n ) and not self.finished\n\n def __reset_agent(self) -> None:","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.check_run_error","uri":"program://BOLAA/function/hotpotqa_run.agent_arch.check_run_error#L142-L144","kind":"function","name":"check_run_error","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":142,"end_line":144,"context_start_line":122,"context_end_line":164,"code":" self.name = \"Base_HotPotQA_run_Agent\"\n\n self.docstore = DocstoreExplorer(docstore) # Search, Lookup\n self.llm = llm\n \n self.enc = token_enc\n self.__reset_agent()\n \n def run(self, reset = True) -> None:\n if reset:\n self.__reset_agent()\n \n while not self.is_halted() and not self.is_finished() and not self.run_error:\n self.step()\n \n def prompt_agent(self) -> str:\n generation = self.llm(self._build_agent_prompt())\n self.check_run_error(generation)\n return format_step(generation)\n \n def check_run_error(self, text):\n if text in [\"No response\"]:\n self.run_error = True\n \n def is_finished(self) -> bool:\n return self.finished\n \n def reward(self) -> float:\n return f1_score(self.answer, self.key) \n \n def is_correct(self) -> bool:\n return EM(self.answer, self.key)\n\n def is_halted(self) -> bool:\n return ((self.step_n > self.max_steps)\n or (len(self.enc.encode(self._build_agent_prompt())) > self.context_len)\n ) and not self.finished\n\n def __reset_agent(self) -> None:\n self.step_n = 1\n self.finished = False\n self.scratchpad: str = ''\n","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.is_finished","uri":"program://BOLAA/function/hotpotqa_run.agent_arch.is_finished#L146-L147","kind":"function","name":"is_finished","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":146,"end_line":147,"context_start_line":126,"context_end_line":167,"code":" \n self.enc = token_enc\n self.__reset_agent()\n \n def run(self, reset = True) -> None:\n if reset:\n self.__reset_agent()\n \n while not self.is_halted() and not self.is_finished() and not self.run_error:\n self.step()\n \n def prompt_agent(self) -> str:\n generation = self.llm(self._build_agent_prompt())\n self.check_run_error(generation)\n return format_step(generation)\n \n def check_run_error(self, text):\n if text in [\"No response\"]:\n self.run_error = True\n \n def is_finished(self) -> bool:\n return self.finished\n \n def reward(self) -> float:\n return f1_score(self.answer, self.key) \n \n def is_correct(self) -> bool:\n return EM(self.answer, self.key)\n\n def is_halted(self) -> bool:\n return ((self.step_n > self.max_steps)\n or (len(self.enc.encode(self._build_agent_prompt())) > self.context_len)\n ) and not self.finished\n\n def __reset_agent(self) -> None:\n self.step_n = 1\n self.finished = False\n self.scratchpad: str = ''\n\n def set_qa(self, question: str, key: str) -> None:\n self.question = question\n self.key = key","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.reward","uri":"program://BOLAA/function/hotpotqa_run.agent_arch.reward#L149-L150","kind":"function","name":"reward","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":149,"end_line":150,"context_start_line":129,"context_end_line":170,"code":" \n def run(self, reset = True) -> None:\n if reset:\n self.__reset_agent()\n \n while not self.is_halted() and not self.is_finished() and not self.run_error:\n self.step()\n \n def prompt_agent(self) -> str:\n generation = self.llm(self._build_agent_prompt())\n self.check_run_error(generation)\n return format_step(generation)\n \n def check_run_error(self, text):\n if text in [\"No response\"]:\n self.run_error = True\n \n def is_finished(self) -> bool:\n return self.finished\n \n def reward(self) -> float:\n return f1_score(self.answer, self.key) \n \n def is_correct(self) -> bool:\n return EM(self.answer, self.key)\n\n def is_halted(self) -> bool:\n return ((self.step_n > self.max_steps)\n or (len(self.enc.encode(self._build_agent_prompt())) > self.context_len)\n ) and not self.finished\n\n def __reset_agent(self) -> None:\n self.step_n = 1\n self.finished = False\n self.scratchpad: str = ''\n\n def set_qa(self, question: str, key: str) -> None:\n self.question = question\n self.key = key\n\n def _think(self):\n self.scratchpad += f'\\nThought {self.step_n}:'","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.is_correct","uri":"program://BOLAA/function/hotpotqa_run.agent_arch.is_correct#L152-L153","kind":"function","name":"is_correct","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":152,"end_line":153,"context_start_line":132,"context_end_line":173,"code":" self.__reset_agent()\n \n while not self.is_halted() and not self.is_finished() and not self.run_error:\n self.step()\n \n def prompt_agent(self) -> str:\n generation = self.llm(self._build_agent_prompt())\n self.check_run_error(generation)\n return format_step(generation)\n \n def check_run_error(self, text):\n if text in [\"No response\"]:\n self.run_error = True\n \n def is_finished(self) -> bool:\n return self.finished\n \n def reward(self) -> float:\n return f1_score(self.answer, self.key) \n \n def is_correct(self) -> bool:\n return EM(self.answer, self.key)\n\n def is_halted(self) -> bool:\n return ((self.step_n > self.max_steps)\n or (len(self.enc.encode(self._build_agent_prompt())) > self.context_len)\n ) and not self.finished\n\n def __reset_agent(self) -> None:\n self.step_n = 1\n self.finished = False\n self.scratchpad: str = ''\n\n def set_qa(self, question: str, key: str) -> None:\n self.question = question\n self.key = key\n\n def _think(self):\n self.scratchpad += f'\\nThought {self.step_n}:'\n self.scratchpad += ' ' + self.prompt_agent()\n print(self.scratchpad.split('\\n')[-1])\n ","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.is_halted","uri":"program://BOLAA/function/hotpotqa_run.agent_arch.is_halted#L155-L158","kind":"function","name":"is_halted","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":155,"end_line":158,"context_start_line":135,"context_end_line":178,"code":" self.step()\n \n def prompt_agent(self) -> str:\n generation = self.llm(self._build_agent_prompt())\n self.check_run_error(generation)\n return format_step(generation)\n \n def check_run_error(self, text):\n if text in [\"No response\"]:\n self.run_error = True\n \n def is_finished(self) -> bool:\n return self.finished\n \n def reward(self) -> float:\n return f1_score(self.answer, self.key) \n \n def is_correct(self) -> bool:\n return EM(self.answer, self.key)\n\n def is_halted(self) -> bool:\n return ((self.step_n > self.max_steps)\n or (len(self.enc.encode(self._build_agent_prompt())) > self.context_len)\n ) and not self.finished\n\n def __reset_agent(self) -> None:\n self.step_n = 1\n self.finished = False\n self.scratchpad: str = ''\n\n def set_qa(self, question: str, key: str) -> None:\n self.question = question\n self.key = key\n\n def _think(self):\n self.scratchpad += f'\\nThought {self.step_n}:'\n self.scratchpad += ' ' + self.prompt_agent()\n print(self.scratchpad.split('\\n')[-1])\n \n def _action(self):\n self.scratchpad += f'\\nAction {self.step_n}:'\n action = self.prompt_agent()\n self.scratchpad += ' ' + action\n action_type, argument = parse_action(action)","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.__reset_agent","uri":"program://BOLAA/function/hotpotqa_run.agent_arch.__reset_agent#L160-L163","kind":"function","name":"__reset_agent","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":160,"end_line":163,"context_start_line":140,"context_end_line":183,"code":" return format_step(generation)\n \n def check_run_error(self, text):\n if text in [\"No response\"]:\n self.run_error = True\n \n def is_finished(self) -> bool:\n return self.finished\n \n def reward(self) -> float:\n return f1_score(self.answer, self.key) \n \n def is_correct(self) -> bool:\n return EM(self.answer, self.key)\n\n def is_halted(self) -> bool:\n return ((self.step_n > self.max_steps)\n or (len(self.enc.encode(self._build_agent_prompt())) > self.context_len)\n ) and not self.finished\n\n def __reset_agent(self) -> None:\n self.step_n = 1\n self.finished = False\n self.scratchpad: str = ''\n\n def set_qa(self, question: str, key: str) -> None:\n self.question = question\n self.key = key\n\n def _think(self):\n self.scratchpad += f'\\nThought {self.step_n}:'\n self.scratchpad += ' ' + self.prompt_agent()\n print(self.scratchpad.split('\\n')[-1])\n \n def _action(self):\n self.scratchpad += f'\\nAction {self.step_n}:'\n action = self.prompt_agent()\n self.scratchpad += ' ' + action\n action_type, argument = parse_action(action)\n print(self.scratchpad.split('\\n')[-1])\n return action_type, argument\n \n def step(self) -> None:\n ","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.set_qa","uri":"program://BOLAA/function/hotpotqa_run.agent_arch.set_qa#L165-L167","kind":"function","name":"set_qa","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":165,"end_line":167,"context_start_line":145,"context_end_line":187,"code":" \n def is_finished(self) -> bool:\n return self.finished\n \n def reward(self) -> float:\n return f1_score(self.answer, self.key) \n \n def is_correct(self) -> bool:\n return EM(self.answer, self.key)\n\n def is_halted(self) -> bool:\n return ((self.step_n > self.max_steps)\n or (len(self.enc.encode(self._build_agent_prompt())) > self.context_len)\n ) and not self.finished\n\n def __reset_agent(self) -> None:\n self.step_n = 1\n self.finished = False\n self.scratchpad: str = ''\n\n def set_qa(self, question: str, key: str) -> None:\n self.question = question\n self.key = key\n\n def _think(self):\n self.scratchpad += f'\\nThought {self.step_n}:'\n self.scratchpad += ' ' + self.prompt_agent()\n print(self.scratchpad.split('\\n')[-1])\n \n def _action(self):\n self.scratchpad += f'\\nAction {self.step_n}:'\n action = self.prompt_agent()\n self.scratchpad += ' ' + action\n action_type, argument = parse_action(action)\n print(self.scratchpad.split('\\n')[-1])\n return action_type, argument\n \n def step(self) -> None:\n \n # agent forward\n ret = self.forward()\n if ret:\n action_type, argument = ret[0], ret[1]","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch._think","uri":"program://BOLAA/function/hotpotqa_run.agent_arch._think#L169-L172","kind":"function","name":"_think","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":169,"end_line":172,"context_start_line":149,"context_end_line":192,"code":" def reward(self) -> float:\n return f1_score(self.answer, self.key) \n \n def is_correct(self) -> bool:\n return EM(self.answer, self.key)\n\n def is_halted(self) -> bool:\n return ((self.step_n > self.max_steps)\n or (len(self.enc.encode(self._build_agent_prompt())) > self.context_len)\n ) and not self.finished\n\n def __reset_agent(self) -> None:\n self.step_n = 1\n self.finished = False\n self.scratchpad: str = ''\n\n def set_qa(self, question: str, key: str) -> None:\n self.question = question\n self.key = key\n\n def _think(self):\n self.scratchpad += f'\\nThought {self.step_n}:'\n self.scratchpad += ' ' + self.prompt_agent()\n print(self.scratchpad.split('\\n')[-1])\n \n def _action(self):\n self.scratchpad += f'\\nAction {self.step_n}:'\n action = self.prompt_agent()\n self.scratchpad += ' ' + action\n action_type, argument = parse_action(action)\n print(self.scratchpad.split('\\n')[-1])\n return action_type, argument\n \n def step(self) -> None:\n \n # agent forward\n ret = self.forward()\n if ret:\n action_type, argument = ret[0], ret[1]\n else:\n action_type = ret\n \n # Observe\n self.scratchpad += f'\\nObservation {self.step_n}: '","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch._action","uri":"program://BOLAA/function/hotpotqa_run.agent_arch._action#L174-L180","kind":"function","name":"_action","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":174,"end_line":180,"context_start_line":154,"context_end_line":200,"code":"\n def is_halted(self) -> bool:\n return ((self.step_n > self.max_steps)\n or (len(self.enc.encode(self._build_agent_prompt())) > self.context_len)\n ) and not self.finished\n\n def __reset_agent(self) -> None:\n self.step_n = 1\n self.finished = False\n self.scratchpad: str = ''\n\n def set_qa(self, question: str, key: str) -> None:\n self.question = question\n self.key = key\n\n def _think(self):\n self.scratchpad += f'\\nThought {self.step_n}:'\n self.scratchpad += ' ' + self.prompt_agent()\n print(self.scratchpad.split('\\n')[-1])\n \n def _action(self):\n self.scratchpad += f'\\nAction {self.step_n}:'\n action = self.prompt_agent()\n self.scratchpad += ' ' + action\n action_type, argument = parse_action(action)\n print(self.scratchpad.split('\\n')[-1])\n return action_type, argument\n \n def step(self) -> None:\n \n # agent forward\n ret = self.forward()\n if ret:\n action_type, argument = ret[0], ret[1]\n else:\n action_type = ret\n \n # Observe\n self.scratchpad += f'\\nObservation {self.step_n}: '\n \n if action_type == 'Finish':\n self.answer = argument\n if self.is_correct():\n self.scratchpad += 'Answer is CORRECT'\n else: \n self.scratchpad += 'Answer is INCORRECT'\n self.finished = True","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.step","uri":"program://BOLAA/function/hotpotqa_run.agent_arch.step#L182-L222","kind":"function","name":"step","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":182,"end_line":222,"context_start_line":162,"context_end_line":242,"code":" self.finished = False\n self.scratchpad: str = ''\n\n def set_qa(self, question: str, key: str) -> None:\n self.question = question\n self.key = key\n\n def _think(self):\n self.scratchpad += f'\\nThought {self.step_n}:'\n self.scratchpad += ' ' + self.prompt_agent()\n print(self.scratchpad.split('\\n')[-1])\n \n def _action(self):\n self.scratchpad += f'\\nAction {self.step_n}:'\n action = self.prompt_agent()\n self.scratchpad += ' ' + action\n action_type, argument = parse_action(action)\n print(self.scratchpad.split('\\n')[-1])\n return action_type, argument\n \n def step(self) -> None:\n \n # agent forward\n ret = self.forward()\n if ret:\n action_type, argument = ret[0], ret[1]\n else:\n action_type = ret\n \n # Observe\n self.scratchpad += f'\\nObservation {self.step_n}: '\n \n if action_type == 'Finish':\n self.answer = argument\n if self.is_correct():\n self.scratchpad += 'Answer is CORRECT'\n else: \n self.scratchpad += 'Answer is INCORRECT'\n self.finished = True\n self.step_n += 1\n return\n\n if action_type == 'Search':\n try:\n self.scratchpad += format_step(self.docstore.search(argument))\n except Exception as e:\n print(e)\n self.scratchpad += f'Could not find that page, please try again.'\n \n elif action_type == 'Lookup':\n try:\n self.scratchpad += format_step(self.docstore.lookup(argument))\n except ValueError:\n self.scratchpad += f'The last page Searched was not found, so you cannot Lookup a keyword in it. Please try one of the similar pages given.'\n\n else:\n self.scratchpad += 'Invalid Action. Valid Actions are Lookup[] Search[] and Finish[].'\n\n print(self.scratchpad.split('\\n')[-1])\n\n self.step_n += 1\n \n def _build_agent_prompt(self) -> str:\n raise NotImplementedError\n \n def forward(self):\n raise NotImplementedError\n \nclass ReactAgent(BaseAgent):\n def __init__(self,\n question: str,\n key: str,\n llm,\n context_len: int = 2000\n ) -> None:\n super().__init__(question, key, llm, context_len)\n\n self.examples = REACT_EXAMPLE\n self.agent_prompt = react_agent_prompt\n self.name = \"React_HotPotQA_run_Agent\"\n ","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch._build_agent_prompt","uri":"program://BOLAA/function/hotpotqa_run.agent_arch._build_agent_prompt#L329-L335","kind":"function","name":"_build_agent_prompt","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":329,"end_line":335,"context_start_line":309,"context_end_line":355,"code":" self.plan_example = PLAN_EXAMPLE\n self.agent_prompt = planner_agent_prompt\n self.plan_prompt = plan_prompt\n self.name = \"Planner_HotPotQA_run_Agent\"\n self._plan()\n \n def _plan(self):\n self.plan = format_step(self.llm(self._build_plan_prompt()))\n\n \n def _build_plan_prompt(self):\n return self.plan_prompt.format(\n examples = self.plan_example,\n question = self.question,\n )\n \n def forward(self):\n action_type, argument = self._action()\n return action_type, argument\n\n def _build_agent_prompt(self) -> str:\n prompt = self.agent_prompt.format(\n examples = self.examples,\n question = self.question,\n plan = self.plan,\n scratchpad = self.scratchpad)\n return prompt\n\nclass PlannerReactAgent(PlannerAgent):\n def __init__(self,\n question: str,\n key: str,\n llm,\n context_len: int = 2000\n ) -> None:\n super().__init__(question, key, llm, context_len)\n\n self.examples = PLANNERREACT_EXAMPLE\n self.plan_example = PLAN_EXAMPLE\n self.agent_prompt = plannerreact_agent_prompt\n self.plan_prompt = plan_prompt\n self.name = \"PlannerReact_HotPotQA_run_Agent\"\n self._plan()\n \n def forward(self):\n self._think()\n action_type, argument = self._action()","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch.forward","uri":"program://BOLAA/function/hotpotqa_run.agent_arch.forward#L353-L356","kind":"function","name":"forward","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":353,"end_line":356,"context_start_line":333,"context_end_line":369,"code":" plan = self.plan,\n scratchpad = self.scratchpad)\n return prompt\n\nclass PlannerReactAgent(PlannerAgent):\n def __init__(self,\n question: str,\n key: str,\n llm,\n context_len: int = 2000\n ) -> None:\n super().__init__(question, key, llm, context_len)\n\n self.examples = PLANNERREACT_EXAMPLE\n self.plan_example = PLAN_EXAMPLE\n self.agent_prompt = plannerreact_agent_prompt\n self.plan_prompt = plan_prompt\n self.name = \"PlannerReact_HotPotQA_run_Agent\"\n self._plan()\n \n def forward(self):\n self._think()\n action_type, argument = self._action()\n return action_type, argument\n\n\ndef get_agent(agent_name):\n if agent_name in [\"Zeroshot_HotPotQA_run_Agent\"]:\n return ZeroshotAgent\n if agent_name in [\"ZeroshotThink_HotPotQA_run_Agent\"]:\n return ZeroshotThinkAgent\n if agent_name in [\"React_HotPotQA_run_Agent\"]:\n return ReactAgent\n if agent_name in [\"Planner_HotPotQA_run_Agent\"]:\n return PlannerAgent\n if agent_name in [\"PlannerReact_HotPotQA_run_Agent\"]:\n return PlannerReactAgent","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch._plan","uri":"program://BOLAA/function/hotpotqa_run.agent_arch._plan#L315-L316","kind":"function","name":"_plan","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":315,"end_line":316,"context_start_line":295,"context_end_line":336,"code":" return self.agent_prompt.format(\n question = self.question,\n scratchpad = self.scratchpad)\n \nclass PlannerAgent(BaseAgent):\n def __init__(self,\n question: str,\n key: str,\n llm,\n context_len: int = 2000\n ) -> None:\n super().__init__(question, key, llm, context_len)\n\n self.examples = PLANNER_EXAMPLE\n self.plan_example = PLAN_EXAMPLE\n self.agent_prompt = planner_agent_prompt\n self.plan_prompt = plan_prompt\n self.name = \"Planner_HotPotQA_run_Agent\"\n self._plan()\n \n def _plan(self):\n self.plan = format_step(self.llm(self._build_plan_prompt()))\n\n \n def _build_plan_prompt(self):\n return self.plan_prompt.format(\n examples = self.plan_example,\n question = self.question,\n )\n \n def forward(self):\n action_type, argument = self._action()\n return action_type, argument\n\n def _build_agent_prompt(self) -> str:\n prompt = self.agent_prompt.format(\n examples = self.examples,\n question = self.question,\n plan = self.plan,\n scratchpad = self.scratchpad)\n return prompt\n","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.agent_arch._build_plan_prompt","uri":"program://BOLAA/function/hotpotqa_run.agent_arch._build_plan_prompt#L319-L323","kind":"function","name":"_build_plan_prompt","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":319,"end_line":323,"context_start_line":299,"context_end_line":343,"code":"class PlannerAgent(BaseAgent):\n def __init__(self,\n question: str,\n key: str,\n llm,\n context_len: int = 2000\n ) -> None:\n super().__init__(question, key, llm, context_len)\n\n self.examples = PLANNER_EXAMPLE\n self.plan_example = PLAN_EXAMPLE\n self.agent_prompt = planner_agent_prompt\n self.plan_prompt = plan_prompt\n self.name = \"Planner_HotPotQA_run_Agent\"\n self._plan()\n \n def _plan(self):\n self.plan = format_step(self.llm(self._build_plan_prompt()))\n\n \n def _build_plan_prompt(self):\n return self.plan_prompt.format(\n examples = self.plan_example,\n question = self.question,\n )\n \n def forward(self):\n action_type, argument = self._action()\n return action_type, argument\n\n def _build_agent_prompt(self) -> str:\n prompt = self.agent_prompt.format(\n examples = self.examples,\n question = self.question,\n plan = self.plan,\n scratchpad = self.scratchpad)\n return prompt\n\nclass PlannerReactAgent(PlannerAgent):\n def __init__(self,\n question: str,\n key: str,\n llm,\n context_len: int = 2000\n ) -> None:","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.utils","uri":"program://BOLAA/module/hotpotqa_run.utils#L1-L158","kind":"module","name":"hotpotqa_run.utils","path":"hotpotqa_run/utils.py","language":"python","start_line":1,"end_line":158,"context_start_line":1,"context_end_line":158,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport os\nimport joblib\nimport json\n\ndef summarize_trial(agents):\n correct = [a for a in agents if a.is_correct()]\n incorrect = [a for a in agents if a.is_finished() and not a.is_correct()]\n not_finish = [a for a in agents if not a.is_finished()]\n return correct, incorrect, not_finish\n\ndef remove_fewshot(prompt: str) -> str:\n prefix = prompt.split('Here are some examples:')[0]\n suffix = prompt.split('(END OF EXAMPLES)')[1]\n return prefix.strip('\\n').strip() + '\\n' + suffix.strip('\\n').strip()\n\ndef log_trial(agents, trial_n):\n correct, incorrect, not_finish = summarize_trial(agents)\n\n log = f\"\"\"\n########################################\nBEGIN TRIAL {trial_n}\nTrial summary: Correct: {len(correct)}, Incorrect: {len(incorrect)} , Not Finished: {len(not_finish)}\n#######################################\n\"\"\"\n\n log += '------------- BEGIN CORRECT AGENTS -------------\\n\\n'\n for agent in correct:\n # log += remove_fewshot(agent._build_agent_prompt()) + f'\\nCorrect answer: {agent.key}\\n\\n'\n log += agent._build_agent_prompt() + f'\\nCorrect answer: {agent.key}\\n\\n'\n\n log += '------------- BEGIN INCORRECT AGENTS -----------\\n\\n'\n for agent in incorrect:\n # log += remove_fewshot(agent._build_agent_prompt()) + f'\\nCorrect answer: {agent.key}\\n\\n'\n log += agent._build_agent_prompt() + f'\\nCorrect answer: {agent.key}\\n\\n'\n \n log += '------------- BEGIN NOT_FINISH AGENTS -----------\\n\\n'\n for agent in not_finish:\n log += agent._build_agent_prompt() + f'\\nCorrect answer: {agent.key}\\n\\n'\n\n return log\n\ndef summarize_trial_detailed(agents):\n correct = [a.is_correct() for a in agents]\n reward = [a.reward()[0] for a in agents]\n halted = [a for a in agents if a.is_halted()]\n incorrect = [a for a in agents if a.is_finished() and not a.is_correct()]\n error = [a.run_error for a in agents]\n return correct, reward, error, halted, incorrect\n\ndef log_agent(agent, file_path):\n question = agent.question\n g_truth = agent.key\n correct = agent.is_correct()\n reward = agent.reward()[0]\n halted = agent.is_halted()\n error = agent.run_error\n prompt = agent._build_agent_prompt()\n save_dict = {\"question\":question, \"answer\":g_truth, \"correct\":correct, \"reward\":reward, \n \"halted\":halted, \"error\":error,\"prompt\":prompt}\n with open(file_path, 'a') as f:\n json.dump(save_dict, f)\n f.write(\"\\n\")\n\n\ndef get_all_agent_sessions(file_name):\n sessions = []\n with open(file_name) as f:\n for line in f:\n session = json.loads(line)\n sessions.append(session)\n return sessions\n\ndef get_error_tasks(sessions):\n error_tasks = []\n for sess in sessions:\n if sess[\"error\"]:\n task = (sess[\"question\"], sess[\"answer\"])\n error_tasks.append(task)\n error_tasks = list(set(error_tasks))\n return error_tasks\n\ndef get_non_error_tasks(sessions):\n tasks = []\n for sess in sessions: \n if not sess[\"error\"]: \n task = (sess[\"question\"], sess[\"answer\"])\n tasks.append(task)\n tasks = list(set(tasks))\n return tasks\n\ndef delete_error(file_name):\n sessions = get_all_agent_sessions(file_name)\n non_error_sessions = [sess for sess in sessions if not sess[\"error\"]]\n with open(file_name+'.back', 'a') as b_f:\n for sess in sessions:\n json.dump(sess, b_f)\n b_f.write('\\n')\n with open(file_name, 'w') as f:\n for sess in non_error_sessions:\n json.dump(sess, f)\n f.write('\\n')\n \ndef summarize_react_trial(agents):\n correct = [a for a in agents if a.is_correct()]\n halted = [a for a in agents if a.is_halted()]\n incorrect = [a for a in agents if a.is_finished() and not a.is_correct()]\n return correct, incorrect, halted\n\ndef summarize_react_trial_detailed(agents):\n correct = [a.is_correct() for a in agents]\n reward = [a.reward()[0] for a in agents]\n return correct, reward\n\ndef log_react_trial(agents, trial_n):\n correct, incorrect, halted = summarize_react_trial(agents)\n\n log = f\"\"\"\n########################################\nBEGIN TRIAL {trial_n}\nTrial summary: Correct: {len(correct)}, Incorrect: {len(incorrect)}, Halted: {len(halted)}\n#######################################\n\"\"\"\n\n log += '------------- BEGIN CORRECT AGENTS -------------\\n\\n'\n for agent in correct:\n log += remove_fewshot(agent._build_agent_prompt()) + f'\\nCorrect answer: {agent.key}\\n\\n'\n\n log += '------------- BEGIN INCORRECT AGENTS -----------\\n\\n'\n for agent in incorrect:\n log += remove_fewshot(agent._build_agent_prompt()) + f'\\nCorrect answer: {agent.key}\\n\\n'\n\n log += '------------- BEGIN HALTED AGENTS -----------\\n\\n'\n for agent in halted:\n log += remove_fewshot(agent._build_agent_prompt()) + f'\\nCorrect answer: {agent.key}\\n\\n'\n\n return log\n\ndef save_agents(agents, dir: str):\n os.makedirs(dir, exist_ok=True)\n for i, agent in enumerate(agents):\n agent.enc = None\n joblib.dump(agent, os.path.join(dir, f'{i}.joblib'))\n\ndef load_agents(dir:str):\n import tiktoken\n agents = []\n for f in os.listdir(dir):\n agent = joblib.load(os.path.join(dir, f))\n agent.enc = tiktoken.encoding_for_model(\"text-davinci-003\")\n agents.append(agent)\n return agents","source_hash":"9220738be27af1d480e8fdf3271c5641bf8444325c3f3dee4b60446548825200","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.utils.summarize_trial","uri":"program://BOLAA/function/hotpotqa_run.utils.summarize_trial#L12-L16","kind":"function","name":"summarize_trial","path":"hotpotqa_run/utils.py","language":"python","start_line":12,"end_line":16,"context_start_line":1,"context_end_line":36,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport os\nimport joblib\nimport json\n\ndef summarize_trial(agents):\n correct = [a for a in agents if a.is_correct()]\n incorrect = [a for a in agents if a.is_finished() and not a.is_correct()]\n not_finish = [a for a in agents if not a.is_finished()]\n return correct, incorrect, not_finish\n\ndef remove_fewshot(prompt: str) -> str:\n prefix = prompt.split('Here are some examples:')[0]\n suffix = prompt.split('(END OF EXAMPLES)')[1]\n return prefix.strip('\\n').strip() + '\\n' + suffix.strip('\\n').strip()\n\ndef log_trial(agents, trial_n):\n correct, incorrect, not_finish = summarize_trial(agents)\n\n log = f\"\"\"\n########################################\nBEGIN TRIAL {trial_n}\nTrial summary: Correct: {len(correct)}, Incorrect: {len(incorrect)} , Not Finished: {len(not_finish)}\n#######################################\n\"\"\"\n\n log += '------------- BEGIN CORRECT AGENTS -------------\\n\\n'\n for agent in correct:\n # log += remove_fewshot(agent._build_agent_prompt()) + f'\\nCorrect answer: {agent.key}\\n\\n'\n log += agent._build_agent_prompt() + f'\\nCorrect answer: {agent.key}\\n\\n'","source_hash":"9220738be27af1d480e8fdf3271c5641bf8444325c3f3dee4b60446548825200","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.utils.remove_fewshot","uri":"program://BOLAA/function/hotpotqa_run.utils.remove_fewshot#L18-L21","kind":"function","name":"remove_fewshot","path":"hotpotqa_run/utils.py","language":"python","start_line":18,"end_line":21,"context_start_line":1,"context_end_line":41,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport os\nimport joblib\nimport json\n\ndef summarize_trial(agents):\n correct = [a for a in agents if a.is_correct()]\n incorrect = [a for a in agents if a.is_finished() and not a.is_correct()]\n not_finish = [a for a in agents if not a.is_finished()]\n return correct, incorrect, not_finish\n\ndef remove_fewshot(prompt: str) -> str:\n prefix = prompt.split('Here are some examples:')[0]\n suffix = prompt.split('(END OF EXAMPLES)')[1]\n return prefix.strip('\\n').strip() + '\\n' + suffix.strip('\\n').strip()\n\ndef log_trial(agents, trial_n):\n correct, incorrect, not_finish = summarize_trial(agents)\n\n log = f\"\"\"\n########################################\nBEGIN TRIAL {trial_n}\nTrial summary: Correct: {len(correct)}, Incorrect: {len(incorrect)} , Not Finished: {len(not_finish)}\n#######################################\n\"\"\"\n\n log += '------------- BEGIN CORRECT AGENTS -------------\\n\\n'\n for agent in correct:\n # log += remove_fewshot(agent._build_agent_prompt()) + f'\\nCorrect answer: {agent.key}\\n\\n'\n log += agent._build_agent_prompt() + f'\\nCorrect answer: {agent.key}\\n\\n'\n\n log += '------------- BEGIN INCORRECT AGENTS -----------\\n\\n'\n for agent in incorrect:\n # log += remove_fewshot(agent._build_agent_prompt()) + f'\\nCorrect answer: {agent.key}\\n\\n'\n log += agent._build_agent_prompt() + f'\\nCorrect answer: {agent.key}\\n\\n'","source_hash":"9220738be27af1d480e8fdf3271c5641bf8444325c3f3dee4b60446548825200","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.utils.log_trial","uri":"program://BOLAA/function/hotpotqa_run.utils.log_trial#L23-L47","kind":"function","name":"log_trial","path":"hotpotqa_run/utils.py","language":"python","start_line":23,"end_line":47,"context_start_line":3,"context_end_line":67,"code":" All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport os\nimport joblib\nimport json\n\ndef summarize_trial(agents):\n correct = [a for a in agents if a.is_correct()]\n incorrect = [a for a in agents if a.is_finished() and not a.is_correct()]\n not_finish = [a for a in agents if not a.is_finished()]\n return correct, incorrect, not_finish\n\ndef remove_fewshot(prompt: str) -> str:\n prefix = prompt.split('Here are some examples:')[0]\n suffix = prompt.split('(END OF EXAMPLES)')[1]\n return prefix.strip('\\n').strip() + '\\n' + suffix.strip('\\n').strip()\n\ndef log_trial(agents, trial_n):\n correct, incorrect, not_finish = summarize_trial(agents)\n\n log = f\"\"\"\n########################################\nBEGIN TRIAL {trial_n}\nTrial summary: Correct: {len(correct)}, Incorrect: {len(incorrect)} , Not Finished: {len(not_finish)}\n#######################################\n\"\"\"\n\n log += '------------- BEGIN CORRECT AGENTS -------------\\n\\n'\n for agent in correct:\n # log += remove_fewshot(agent._build_agent_prompt()) + f'\\nCorrect answer: {agent.key}\\n\\n'\n log += agent._build_agent_prompt() + f'\\nCorrect answer: {agent.key}\\n\\n'\n\n log += '------------- BEGIN INCORRECT AGENTS -----------\\n\\n'\n for agent in incorrect:\n # log += remove_fewshot(agent._build_agent_prompt()) + f'\\nCorrect answer: {agent.key}\\n\\n'\n log += agent._build_agent_prompt() + f'\\nCorrect answer: {agent.key}\\n\\n'\n \n log += '------------- BEGIN NOT_FINISH AGENTS -----------\\n\\n'\n for agent in not_finish:\n log += agent._build_agent_prompt() + f'\\nCorrect answer: {agent.key}\\n\\n'\n\n return log\n\ndef summarize_trial_detailed(agents):\n correct = [a.is_correct() for a in agents]\n reward = [a.reward()[0] for a in agents]\n halted = [a for a in agents if a.is_halted()]\n incorrect = [a for a in agents if a.is_finished() and not a.is_correct()]\n error = [a.run_error for a in agents]\n return correct, reward, error, halted, incorrect\n\ndef log_agent(agent, file_path):\n question = agent.question\n g_truth = agent.key\n correct = agent.is_correct()\n reward = agent.reward()[0]\n halted = agent.is_halted()\n error = agent.run_error\n prompt = agent._build_agent_prompt()\n save_dict = {\"question\":question, \"answer\":g_truth, \"correct\":correct, \"reward\":reward, \n \"halted\":halted, \"error\":error,\"prompt\":prompt}\n with open(file_path, 'a') as f:","source_hash":"9220738be27af1d480e8fdf3271c5641bf8444325c3f3dee4b60446548825200","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.utils.summarize_trial_detailed","uri":"program://BOLAA/function/hotpotqa_run.utils.summarize_trial_detailed#L49-L55","kind":"function","name":"summarize_trial_detailed","path":"hotpotqa_run/utils.py","language":"python","start_line":49,"end_line":55,"context_start_line":29,"context_end_line":75,"code":"Trial summary: Correct: {len(correct)}, Incorrect: {len(incorrect)} , Not Finished: {len(not_finish)}\n#######################################\n\"\"\"\n\n log += '------------- BEGIN CORRECT AGENTS -------------\\n\\n'\n for agent in correct:\n # log += remove_fewshot(agent._build_agent_prompt()) + f'\\nCorrect answer: {agent.key}\\n\\n'\n log += agent._build_agent_prompt() + f'\\nCorrect answer: {agent.key}\\n\\n'\n\n log += '------------- BEGIN INCORRECT AGENTS -----------\\n\\n'\n for agent in incorrect:\n # log += remove_fewshot(agent._build_agent_prompt()) + f'\\nCorrect answer: {agent.key}\\n\\n'\n log += agent._build_agent_prompt() + f'\\nCorrect answer: {agent.key}\\n\\n'\n \n log += '------------- BEGIN NOT_FINISH AGENTS -----------\\n\\n'\n for agent in not_finish:\n log += agent._build_agent_prompt() + f'\\nCorrect answer: {agent.key}\\n\\n'\n\n return log\n\ndef summarize_trial_detailed(agents):\n correct = [a.is_correct() for a in agents]\n reward = [a.reward()[0] for a in agents]\n halted = [a for a in agents if a.is_halted()]\n incorrect = [a for a in agents if a.is_finished() and not a.is_correct()]\n error = [a.run_error for a in agents]\n return correct, reward, error, halted, incorrect\n\ndef log_agent(agent, file_path):\n question = agent.question\n g_truth = agent.key\n correct = agent.is_correct()\n reward = agent.reward()[0]\n halted = agent.is_halted()\n error = agent.run_error\n prompt = agent._build_agent_prompt()\n save_dict = {\"question\":question, \"answer\":g_truth, \"correct\":correct, \"reward\":reward, \n \"halted\":halted, \"error\":error,\"prompt\":prompt}\n with open(file_path, 'a') as f:\n json.dump(save_dict, f)\n f.write(\"\\n\")\n\n\ndef get_all_agent_sessions(file_name):\n sessions = []\n with open(file_name) as f:\n for line in f:","source_hash":"9220738be27af1d480e8fdf3271c5641bf8444325c3f3dee4b60446548825200","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.utils.log_agent","uri":"program://BOLAA/function/hotpotqa_run.utils.log_agent#L57-L69","kind":"function","name":"log_agent","path":"hotpotqa_run/utils.py","language":"python","start_line":57,"end_line":69,"context_start_line":37,"context_end_line":89,"code":"\n log += '------------- BEGIN INCORRECT AGENTS -----------\\n\\n'\n for agent in incorrect:\n # log += remove_fewshot(agent._build_agent_prompt()) + f'\\nCorrect answer: {agent.key}\\n\\n'\n log += agent._build_agent_prompt() + f'\\nCorrect answer: {agent.key}\\n\\n'\n \n log += '------------- BEGIN NOT_FINISH AGENTS -----------\\n\\n'\n for agent in not_finish:\n log += agent._build_agent_prompt() + f'\\nCorrect answer: {agent.key}\\n\\n'\n\n return log\n\ndef summarize_trial_detailed(agents):\n correct = [a.is_correct() for a in agents]\n reward = [a.reward()[0] for a in agents]\n halted = [a for a in agents if a.is_halted()]\n incorrect = [a for a in agents if a.is_finished() and not a.is_correct()]\n error = [a.run_error for a in agents]\n return correct, reward, error, halted, incorrect\n\ndef log_agent(agent, file_path):\n question = agent.question\n g_truth = agent.key\n correct = agent.is_correct()\n reward = agent.reward()[0]\n halted = agent.is_halted()\n error = agent.run_error\n prompt = agent._build_agent_prompt()\n save_dict = {\"question\":question, \"answer\":g_truth, \"correct\":correct, \"reward\":reward, \n \"halted\":halted, \"error\":error,\"prompt\":prompt}\n with open(file_path, 'a') as f:\n json.dump(save_dict, f)\n f.write(\"\\n\")\n\n\ndef get_all_agent_sessions(file_name):\n sessions = []\n with open(file_name) as f:\n for line in f:\n session = json.loads(line)\n sessions.append(session)\n return sessions\n\ndef get_error_tasks(sessions):\n error_tasks = []\n for sess in sessions:\n if sess[\"error\"]:\n task = (sess[\"question\"], sess[\"answer\"])\n error_tasks.append(task)\n error_tasks = list(set(error_tasks))\n return error_tasks\n\ndef get_non_error_tasks(sessions):","source_hash":"9220738be27af1d480e8fdf3271c5641bf8444325c3f3dee4b60446548825200","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.utils.get_all_agent_sessions","uri":"program://BOLAA/function/hotpotqa_run.utils.get_all_agent_sessions#L72-L78","kind":"function","name":"get_all_agent_sessions","path":"hotpotqa_run/utils.py","language":"python","start_line":72,"end_line":78,"context_start_line":52,"context_end_line":98,"code":" halted = [a for a in agents if a.is_halted()]\n incorrect = [a for a in agents if a.is_finished() and not a.is_correct()]\n error = [a.run_error for a in agents]\n return correct, reward, error, halted, incorrect\n\ndef log_agent(agent, file_path):\n question = agent.question\n g_truth = agent.key\n correct = agent.is_correct()\n reward = agent.reward()[0]\n halted = agent.is_halted()\n error = agent.run_error\n prompt = agent._build_agent_prompt()\n save_dict = {\"question\":question, \"answer\":g_truth, \"correct\":correct, \"reward\":reward, \n \"halted\":halted, \"error\":error,\"prompt\":prompt}\n with open(file_path, 'a') as f:\n json.dump(save_dict, f)\n f.write(\"\\n\")\n\n\ndef get_all_agent_sessions(file_name):\n sessions = []\n with open(file_name) as f:\n for line in f:\n session = json.loads(line)\n sessions.append(session)\n return sessions\n\ndef get_error_tasks(sessions):\n error_tasks = []\n for sess in sessions:\n if sess[\"error\"]:\n task = (sess[\"question\"], sess[\"answer\"])\n error_tasks.append(task)\n error_tasks = list(set(error_tasks))\n return error_tasks\n\ndef get_non_error_tasks(sessions):\n tasks = []\n for sess in sessions: \n if not sess[\"error\"]: \n task = (sess[\"question\"], sess[\"answer\"])\n tasks.append(task)\n tasks = list(set(tasks))\n return tasks\n\ndef delete_error(file_name):","source_hash":"9220738be27af1d480e8fdf3271c5641bf8444325c3f3dee4b60446548825200","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.utils.get_error_tasks","uri":"program://BOLAA/function/hotpotqa_run.utils.get_error_tasks#L80-L87","kind":"function","name":"get_error_tasks","path":"hotpotqa_run/utils.py","language":"python","start_line":80,"end_line":87,"context_start_line":60,"context_end_line":107,"code":" correct = agent.is_correct()\n reward = agent.reward()[0]\n halted = agent.is_halted()\n error = agent.run_error\n prompt = agent._build_agent_prompt()\n save_dict = {\"question\":question, \"answer\":g_truth, \"correct\":correct, \"reward\":reward, \n \"halted\":halted, \"error\":error,\"prompt\":prompt}\n with open(file_path, 'a') as f:\n json.dump(save_dict, f)\n f.write(\"\\n\")\n\n\ndef get_all_agent_sessions(file_name):\n sessions = []\n with open(file_name) as f:\n for line in f:\n session = json.loads(line)\n sessions.append(session)\n return sessions\n\ndef get_error_tasks(sessions):\n error_tasks = []\n for sess in sessions:\n if sess[\"error\"]:\n task = (sess[\"question\"], sess[\"answer\"])\n error_tasks.append(task)\n error_tasks = list(set(error_tasks))\n return error_tasks\n\ndef get_non_error_tasks(sessions):\n tasks = []\n for sess in sessions: \n if not sess[\"error\"]: \n task = (sess[\"question\"], sess[\"answer\"])\n tasks.append(task)\n tasks = list(set(tasks))\n return tasks\n\ndef delete_error(file_name):\n sessions = get_all_agent_sessions(file_name)\n non_error_sessions = [sess for sess in sessions if not sess[\"error\"]]\n with open(file_name+'.back', 'a') as b_f:\n for sess in sessions:\n json.dump(sess, b_f)\n b_f.write('\\n')\n with open(file_name, 'w') as f:\n for sess in non_error_sessions:\n json.dump(sess, f)","source_hash":"9220738be27af1d480e8fdf3271c5641bf8444325c3f3dee4b60446548825200","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.utils.get_non_error_tasks","uri":"program://BOLAA/function/hotpotqa_run.utils.get_non_error_tasks#L89-L96","kind":"function","name":"get_non_error_tasks","path":"hotpotqa_run/utils.py","language":"python","start_line":89,"end_line":96,"context_start_line":69,"context_end_line":116,"code":" f.write(\"\\n\")\n\n\ndef get_all_agent_sessions(file_name):\n sessions = []\n with open(file_name) as f:\n for line in f:\n session = json.loads(line)\n sessions.append(session)\n return sessions\n\ndef get_error_tasks(sessions):\n error_tasks = []\n for sess in sessions:\n if sess[\"error\"]:\n task = (sess[\"question\"], sess[\"answer\"])\n error_tasks.append(task)\n error_tasks = list(set(error_tasks))\n return error_tasks\n\ndef get_non_error_tasks(sessions):\n tasks = []\n for sess in sessions: \n if not sess[\"error\"]: \n task = (sess[\"question\"], sess[\"answer\"])\n tasks.append(task)\n tasks = list(set(tasks))\n return tasks\n\ndef delete_error(file_name):\n sessions = get_all_agent_sessions(file_name)\n non_error_sessions = [sess for sess in sessions if not sess[\"error\"]]\n with open(file_name+'.back', 'a') as b_f:\n for sess in sessions:\n json.dump(sess, b_f)\n b_f.write('\\n')\n with open(file_name, 'w') as f:\n for sess in non_error_sessions:\n json.dump(sess, f)\n f.write('\\n')\n \ndef summarize_react_trial(agents):\n correct = [a for a in agents if a.is_correct()]\n halted = [a for a in agents if a.is_halted()]\n incorrect = [a for a in agents if a.is_finished() and not a.is_correct()]\n return correct, incorrect, halted\n\ndef summarize_react_trial_detailed(agents):","source_hash":"9220738be27af1d480e8fdf3271c5641bf8444325c3f3dee4b60446548825200","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.utils.delete_error","uri":"program://BOLAA/function/hotpotqa_run.utils.delete_error#L98-L108","kind":"function","name":"delete_error","path":"hotpotqa_run/utils.py","language":"python","start_line":98,"end_line":108,"context_start_line":78,"context_end_line":128,"code":" return sessions\n\ndef get_error_tasks(sessions):\n error_tasks = []\n for sess in sessions:\n if sess[\"error\"]:\n task = (sess[\"question\"], sess[\"answer\"])\n error_tasks.append(task)\n error_tasks = list(set(error_tasks))\n return error_tasks\n\ndef get_non_error_tasks(sessions):\n tasks = []\n for sess in sessions: \n if not sess[\"error\"]: \n task = (sess[\"question\"], sess[\"answer\"])\n tasks.append(task)\n tasks = list(set(tasks))\n return tasks\n\ndef delete_error(file_name):\n sessions = get_all_agent_sessions(file_name)\n non_error_sessions = [sess for sess in sessions if not sess[\"error\"]]\n with open(file_name+'.back', 'a') as b_f:\n for sess in sessions:\n json.dump(sess, b_f)\n b_f.write('\\n')\n with open(file_name, 'w') as f:\n for sess in non_error_sessions:\n json.dump(sess, f)\n f.write('\\n')\n \ndef summarize_react_trial(agents):\n correct = [a for a in agents if a.is_correct()]\n halted = [a for a in agents if a.is_halted()]\n incorrect = [a for a in agents if a.is_finished() and not a.is_correct()]\n return correct, incorrect, halted\n\ndef summarize_react_trial_detailed(agents):\n correct = [a.is_correct() for a in agents]\n reward = [a.reward()[0] for a in agents]\n return correct, reward\n\ndef log_react_trial(agents, trial_n):\n correct, incorrect, halted = summarize_react_trial(agents)\n\n log = f\"\"\"\n########################################\nBEGIN TRIAL {trial_n}\nTrial summary: Correct: {len(correct)}, Incorrect: {len(incorrect)}, Halted: {len(halted)}\n#######################################","source_hash":"9220738be27af1d480e8fdf3271c5641bf8444325c3f3dee4b60446548825200","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.utils.summarize_react_trial","uri":"program://BOLAA/function/hotpotqa_run.utils.summarize_react_trial#L110-L114","kind":"function","name":"summarize_react_trial","path":"hotpotqa_run/utils.py","language":"python","start_line":110,"end_line":114,"context_start_line":90,"context_end_line":134,"code":" tasks = []\n for sess in sessions: \n if not sess[\"error\"]: \n task = (sess[\"question\"], sess[\"answer\"])\n tasks.append(task)\n tasks = list(set(tasks))\n return tasks\n\ndef delete_error(file_name):\n sessions = get_all_agent_sessions(file_name)\n non_error_sessions = [sess for sess in sessions if not sess[\"error\"]]\n with open(file_name+'.back', 'a') as b_f:\n for sess in sessions:\n json.dump(sess, b_f)\n b_f.write('\\n')\n with open(file_name, 'w') as f:\n for sess in non_error_sessions:\n json.dump(sess, f)\n f.write('\\n')\n \ndef summarize_react_trial(agents):\n correct = [a for a in agents if a.is_correct()]\n halted = [a for a in agents if a.is_halted()]\n incorrect = [a for a in agents if a.is_finished() and not a.is_correct()]\n return correct, incorrect, halted\n\ndef summarize_react_trial_detailed(agents):\n correct = [a.is_correct() for a in agents]\n reward = [a.reward()[0] for a in agents]\n return correct, reward\n\ndef log_react_trial(agents, trial_n):\n correct, incorrect, halted = summarize_react_trial(agents)\n\n log = f\"\"\"\n########################################\nBEGIN TRIAL {trial_n}\nTrial summary: Correct: {len(correct)}, Incorrect: {len(incorrect)}, Halted: {len(halted)}\n#######################################\n\"\"\"\n\n log += '------------- BEGIN CORRECT AGENTS -------------\\n\\n'\n for agent in correct:\n log += remove_fewshot(agent._build_agent_prompt()) + f'\\nCorrect answer: {agent.key}\\n\\n'\n","source_hash":"9220738be27af1d480e8fdf3271c5641bf8444325c3f3dee4b60446548825200","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.utils.summarize_react_trial_detailed","uri":"program://BOLAA/function/hotpotqa_run.utils.summarize_react_trial_detailed#L116-L119","kind":"function","name":"summarize_react_trial_detailed","path":"hotpotqa_run/utils.py","language":"python","start_line":116,"end_line":119,"context_start_line":96,"context_end_line":139,"code":" return tasks\n\ndef delete_error(file_name):\n sessions = get_all_agent_sessions(file_name)\n non_error_sessions = [sess for sess in sessions if not sess[\"error\"]]\n with open(file_name+'.back', 'a') as b_f:\n for sess in sessions:\n json.dump(sess, b_f)\n b_f.write('\\n')\n with open(file_name, 'w') as f:\n for sess in non_error_sessions:\n json.dump(sess, f)\n f.write('\\n')\n \ndef summarize_react_trial(agents):\n correct = [a for a in agents if a.is_correct()]\n halted = [a for a in agents if a.is_halted()]\n incorrect = [a for a in agents if a.is_finished() and not a.is_correct()]\n return correct, incorrect, halted\n\ndef summarize_react_trial_detailed(agents):\n correct = [a.is_correct() for a in agents]\n reward = [a.reward()[0] for a in agents]\n return correct, reward\n\ndef log_react_trial(agents, trial_n):\n correct, incorrect, halted = summarize_react_trial(agents)\n\n log = f\"\"\"\n########################################\nBEGIN TRIAL {trial_n}\nTrial summary: Correct: {len(correct)}, Incorrect: {len(incorrect)}, Halted: {len(halted)}\n#######################################\n\"\"\"\n\n log += '------------- BEGIN CORRECT AGENTS -------------\\n\\n'\n for agent in correct:\n log += remove_fewshot(agent._build_agent_prompt()) + f'\\nCorrect answer: {agent.key}\\n\\n'\n\n log += '------------- BEGIN INCORRECT AGENTS -----------\\n\\n'\n for agent in incorrect:\n log += remove_fewshot(agent._build_agent_prompt()) + f'\\nCorrect answer: {agent.key}\\n\\n'\n\n log += '------------- BEGIN HALTED AGENTS -----------\\n\\n'","source_hash":"9220738be27af1d480e8fdf3271c5641bf8444325c3f3dee4b60446548825200","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.utils.log_react_trial","uri":"program://BOLAA/function/hotpotqa_run.utils.log_react_trial#L121-L143","kind":"function","name":"log_react_trial","path":"hotpotqa_run/utils.py","language":"python","start_line":121,"end_line":143,"context_start_line":101,"context_end_line":158,"code":" with open(file_name+'.back', 'a') as b_f:\n for sess in sessions:\n json.dump(sess, b_f)\n b_f.write('\\n')\n with open(file_name, 'w') as f:\n for sess in non_error_sessions:\n json.dump(sess, f)\n f.write('\\n')\n \ndef summarize_react_trial(agents):\n correct = [a for a in agents if a.is_correct()]\n halted = [a for a in agents if a.is_halted()]\n incorrect = [a for a in agents if a.is_finished() and not a.is_correct()]\n return correct, incorrect, halted\n\ndef summarize_react_trial_detailed(agents):\n correct = [a.is_correct() for a in agents]\n reward = [a.reward()[0] for a in agents]\n return correct, reward\n\ndef log_react_trial(agents, trial_n):\n correct, incorrect, halted = summarize_react_trial(agents)\n\n log = f\"\"\"\n########################################\nBEGIN TRIAL {trial_n}\nTrial summary: Correct: {len(correct)}, Incorrect: {len(incorrect)}, Halted: {len(halted)}\n#######################################\n\"\"\"\n\n log += '------------- BEGIN CORRECT AGENTS -------------\\n\\n'\n for agent in correct:\n log += remove_fewshot(agent._build_agent_prompt()) + f'\\nCorrect answer: {agent.key}\\n\\n'\n\n log += '------------- BEGIN INCORRECT AGENTS -----------\\n\\n'\n for agent in incorrect:\n log += remove_fewshot(agent._build_agent_prompt()) + f'\\nCorrect answer: {agent.key}\\n\\n'\n\n log += '------------- BEGIN HALTED AGENTS -----------\\n\\n'\n for agent in halted:\n log += remove_fewshot(agent._build_agent_prompt()) + f'\\nCorrect answer: {agent.key}\\n\\n'\n\n return log\n\ndef save_agents(agents, dir: str):\n os.makedirs(dir, exist_ok=True)\n for i, agent in enumerate(agents):\n agent.enc = None\n joblib.dump(agent, os.path.join(dir, f'{i}.joblib'))\n\ndef load_agents(dir:str):\n import tiktoken\n agents = []\n for f in os.listdir(dir):\n agent = joblib.load(os.path.join(dir, f))\n agent.enc = tiktoken.encoding_for_model(\"text-davinci-003\")\n agents.append(agent)\n return agents","source_hash":"9220738be27af1d480e8fdf3271c5641bf8444325c3f3dee4b60446548825200","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.utils.save_agents","uri":"program://BOLAA/function/hotpotqa_run.utils.save_agents#L145-L149","kind":"function","name":"save_agents","path":"hotpotqa_run/utils.py","language":"python","start_line":145,"end_line":149,"context_start_line":125,"context_end_line":158,"code":"########################################\nBEGIN TRIAL {trial_n}\nTrial summary: Correct: {len(correct)}, Incorrect: {len(incorrect)}, Halted: {len(halted)}\n#######################################\n\"\"\"\n\n log += '------------- BEGIN CORRECT AGENTS -------------\\n\\n'\n for agent in correct:\n log += remove_fewshot(agent._build_agent_prompt()) + f'\\nCorrect answer: {agent.key}\\n\\n'\n\n log += '------------- BEGIN INCORRECT AGENTS -----------\\n\\n'\n for agent in incorrect:\n log += remove_fewshot(agent._build_agent_prompt()) + f'\\nCorrect answer: {agent.key}\\n\\n'\n\n log += '------------- BEGIN HALTED AGENTS -----------\\n\\n'\n for agent in halted:\n log += remove_fewshot(agent._build_agent_prompt()) + f'\\nCorrect answer: {agent.key}\\n\\n'\n\n return log\n\ndef save_agents(agents, dir: str):\n os.makedirs(dir, exist_ok=True)\n for i, agent in enumerate(agents):\n agent.enc = None\n joblib.dump(agent, os.path.join(dir, f'{i}.joblib'))\n\ndef load_agents(dir:str):\n import tiktoken\n agents = []\n for f in os.listdir(dir):\n agent = joblib.load(os.path.join(dir, f))\n agent.enc = tiktoken.encoding_for_model(\"text-davinci-003\")\n agents.append(agent)\n return agents","source_hash":"9220738be27af1d480e8fdf3271c5641bf8444325c3f3dee4b60446548825200","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.utils.load_agents","uri":"program://BOLAA/function/hotpotqa_run.utils.load_agents#L151-L158","kind":"function","name":"load_agents","path":"hotpotqa_run/utils.py","language":"python","start_line":151,"end_line":158,"context_start_line":131,"context_end_line":158,"code":" log += '------------- BEGIN CORRECT AGENTS -------------\\n\\n'\n for agent in correct:\n log += remove_fewshot(agent._build_agent_prompt()) + f'\\nCorrect answer: {agent.key}\\n\\n'\n\n log += '------------- BEGIN INCORRECT AGENTS -----------\\n\\n'\n for agent in incorrect:\n log += remove_fewshot(agent._build_agent_prompt()) + f'\\nCorrect answer: {agent.key}\\n\\n'\n\n log += '------------- BEGIN HALTED AGENTS -----------\\n\\n'\n for agent in halted:\n log += remove_fewshot(agent._build_agent_prompt()) + f'\\nCorrect answer: {agent.key}\\n\\n'\n\n return log\n\ndef save_agents(agents, dir: str):\n os.makedirs(dir, exist_ok=True)\n for i, agent in enumerate(agents):\n agent.enc = None\n joblib.dump(agent, os.path.join(dir, f'{i}.joblib'))\n\ndef load_agents(dir:str):\n import tiktoken\n agents = []\n for f in os.listdir(dir):\n agent = joblib.load(os.path.join(dir, f))\n agent.enc = tiktoken.encoding_for_model(\"text-davinci-003\")\n agents.append(agent)\n return agents","source_hash":"9220738be27af1d480e8fdf3271c5641bf8444325c3f3dee4b60446548825200","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wrappers","uri":"program://BOLAA/module/hotpotqa_run.wrappers#L1-L247","kind":"module","name":"hotpotqa_run.wrappers","path":"hotpotqa_run/wrappers.py","language":"python","start_line":1,"end_line":247,"context_start_line":1,"context_end_line":247,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport json\nimport os\nimport gym\nimport numpy as np\nimport re\nimport string\nfrom collections import Counter\n\n \nDATA_DIR = \"data\"\nHOTPOTQA_SPLIT_FILE = {\n \"train\": \"hotpot_train_v1.1_simplified.json\",\n \"dev\": \"hotpot_dev_v1_simplified.json\",\n \"test\": \"hotpot_test_v1_simplified.json\",\n}\n\nFEVER_SPLIT_FILE = {\n \"train\": \"train.jsonl\",\n \"dev\": \"paper_dev.jsonl\",\n}\n\n\nclass HistoryWrapper(gym.ObservationWrapper):\n def __init__(self, env, obs_format, prompt=None):\n super().__init__(env)\n assert obs_format in [\"obs\", \"history\"]\n if obs_format == \"history\":\n assert hasattr(self.env, \"traj\")\n self.obs_format = obs_format\n self.prompt = prompt if prompt is not None else \"\"\n\n def observation(self, obs):\n if self.obs_format == \"obs\":\n return obs\n elif self.obs_format == \"history\":\n observation = self.env.traj[\"observations\"][0] + \"\\n\"\n for i, (o, a) in enumerate(zip(self.env.traj[\"observations\"][1:], self.env.traj[\"actions\"]), 1):\n observation += f\"Action {i}: {a}\\nObservation {i}: {o}\\n\\n\"\n return self.prompt + observation\n \n\ndef normalize_answer(s):\n def remove_articles(text):\n return re.sub(r\"\\b(a|an|the)\\b\", \" \", text)\n \n def white_space_fix(text):\n return \" \".join(text.split())\n\n def remove_punc(text):\n exclude = set(string.punctuation)\n return \"\".join(ch for ch in text if ch not in exclude)\n\n def lower(text):\n return text.lower()\n\n return white_space_fix(remove_articles(remove_punc(lower(s))))\n\ndef f1_score(prediction, ground_truth):\n normalized_prediction = normalize_answer(prediction)\n normalized_ground_truth = normalize_answer(ground_truth)\n\n ZERO_METRIC = (0, 0, 0)\n\n if normalized_prediction in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n if normalized_ground_truth in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n \n prediction_tokens = normalized_prediction.split()\n ground_truth_tokens = normalized_ground_truth.split()\n common = Counter(prediction_tokens) & Counter(ground_truth_tokens)\n num_same = sum(common.values())\n if num_same == 0:\n return ZERO_METRIC\n precision = 1.0 * num_same / len(prediction_tokens)\n recall = 1.0 * num_same / len(ground_truth_tokens)\n f1 = (2 * precision * recall) / (precision + recall)\n return f1, precision, recall\n \nclass HotPotQAWrapper(gym.Wrapper):\n def __init__(self, env, split):\n super().__init__(env)\n data_file = f\"{DATA_DIR}/{HOTPOTQA_SPLIT_FILE[split]}\"\n self.data = json.load(open(data_file))\n self.data = [(d['question'], d['answer']) for d in self.data]\n self.data_idx = 0\n self.split = split\n\n def reset(self, seed=None, return_info=False, options=None, idx=None):\n self.env.reset(seed=seed, return_info=return_info, options=options)\n try:\n self.env.step('')\n except:\n pass\n self.env.reset(seed=seed, return_info=return_info, options=options)\n self.data_idx = int(np.random.randint(len(self.data))) if idx is None else idx\n observation = f\"Question: {self.data[self.data_idx][0]}\"\n info = self._get_info()\n return (observation, info) if return_info else observation\n\n def _get_info(self):\n return {\n \"steps\": self.steps, \n \"answer\": self.answer,\n \"question\": self.data[self.data_idx][0], \n \"hotpot_split\": self.split\n }\n\n def get_reward(self, info):\n if info['answer'] is not None:\n pred = normalize_answer(self.data[self.data_idx][1])\n gt = normalize_answer(info['answer'])\n score = (pred == gt)\n return int(score)\n return 0\n \n def get_metrics(self, info):\n if info['answer'] is not None:\n pred = normalize_answer(self.data[self.data_idx][1])\n gt = normalize_answer(info['answer'])\n em = (pred == gt)\n f1 = f1_score(pred, gt)[0]\n return {'reward': em, 'em': em, 'f1': f1}\n return {'reward': 0, 'em': 0, 'f1': 0}\n\n def step(self, action):\n # TODO: first step obs does not have question. \n obs, _, done, info = self.env.step(action)\n reward = self.get_reward(info)\n if done:\n obs = f\"Episode finished, reward = {reward}\\n\"\n info.update({\"gt_answer\": self.data[self.data_idx][1], \"question_idx\": self.data_idx})\n info.update(self.get_metrics(info))\n return obs, reward, done, info\n \n def __len__(self):\n return len(self.data)\n\nclass FeverWrapper(gym.Wrapper):\n def __init__(self, env, split):\n super().__init__(env)\n \n data_path = f\"./data/{FEVER_SPLIT_FILE[split]}\"\n with open(data_path, \"r\") as json_file:\n json_list = list(json_file)\n\n data = []\n for json_str in json_list:\n json_str = json.loads(json_str)\n label = json_str[\"label\"]\n claim = json_str[\"claim\"]\n data.append((claim, label))\n\n self.data = data\n self.data_idx = 0\n self.split = split\n\n def reset(self, seed=None, return_info=False, options=None, idx=None):\n self.env.reset(seed=seed, return_info=return_info, options=options)\n try:\n self.env.step('')\n except:\n pass\n self.env.reset(seed=seed, return_info=return_info, options=options)\n self.data_idx = int(np.random.randint(len(self.data))) if idx is None else idx\n observation = f\"Claim: {self.data[self.data_idx][0]}\"\n info = self._get_info()\n return (observation, info) if return_info else observation\n\n def _get_info(self):\n return {\n \"steps\": self.steps, \n \"answer\": self.answer,\n \"question\": self.data[self.data_idx][0], \n \"fever_split\": self.split\n }\n\n def get_reward(self, info):\n if info['answer'] is not None:\n label = normalize_answer(self.data[self.data_idx][1])\n pred = normalize_answer(info['answer'])\n if label == pred:\n return 1\n return 0\n\n def step(self, action):\n # TODO: first step obs does not have question. \n obs, _, done, info = self.env.step(action)\n reward = self.get_reward(info)\n if done:\n obs = f\"Episode finished, reward = {reward}\\n\"\n info.update({\"gt_answer\": self.data[self.data_idx][1], \"question_idx\": self.data_idx})\n info.update({'em': reward, 'reward': reward, 'f1': reward})\n return obs, reward, done, info\n \n def __len__(self):\n return len(self.data)\n \n \nclass LoggingWrapper(gym.Wrapper):\n def __init__(self, env, folder=\"trajs\", file_id=None):\n super().__init__(env)\n self.trajs = []\n self.traj = {\"observations\": [], \"actions\": []}\n self.folder = folder\n self.file_id = np.random.randint(0, 10000000) if file_id is None else file_id\n self.file_path = f\"{self.folder}/{self.file_id}.json\"\n os.makedirs(\"trajs\", exist_ok=True)\n\n def __len__(self):\n return len(self.env.data)\n \n\n def reset(self, seed=None, return_info=False, options=None, idx=None):\n output = self.env.reset(seed=seed, return_info=return_info, options=options, idx=idx)\n observation = output[0] if return_info else output\n self.traj = {\"observations\": [observation], \"actions\": []}\n return output\n\n def step(self, action):\n obs, reward, done, info = self.env.step(action)\n self.traj[\"observations\"].append(obs)\n self.traj[\"actions\"].append(action)\n if done:\n self.traj.update(info)\n return obs, reward, done, info\n\n def update_record(self):\n if len(self.traj) > 0:\n self.trajs.append(self.traj)\n self.traj = {\"observations\": [], \"actions\": []}\n \n def write(self):\n self.update_record()\n with open(self.file_path, \"w\") as f:\n json.dump(self.trajs, f)\n print(f\"Saved trajs to trajs/{self.file_id}.json\")\n \n def close(self):\n self.write()","source_hash":"0deac649089a79f9de23297850a143449c31b5988a57c2b5507287b0004116e8","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wrappers.HistoryWrapper","uri":"program://BOLAA/class/hotpotqa_run.wrappers.HistoryWrapper#L30-L46","kind":"class","name":"HistoryWrapper","path":"hotpotqa_run/wrappers.py","language":"python","start_line":30,"end_line":46,"context_start_line":10,"context_end_line":66,"code":"import gym\nimport numpy as np\nimport re\nimport string\nfrom collections import Counter\n\n \nDATA_DIR = \"data\"\nHOTPOTQA_SPLIT_FILE = {\n \"train\": \"hotpot_train_v1.1_simplified.json\",\n \"dev\": \"hotpot_dev_v1_simplified.json\",\n \"test\": \"hotpot_test_v1_simplified.json\",\n}\n\nFEVER_SPLIT_FILE = {\n \"train\": \"train.jsonl\",\n \"dev\": \"paper_dev.jsonl\",\n}\n\n\nclass HistoryWrapper(gym.ObservationWrapper):\n def __init__(self, env, obs_format, prompt=None):\n super().__init__(env)\n assert obs_format in [\"obs\", \"history\"]\n if obs_format == \"history\":\n assert hasattr(self.env, \"traj\")\n self.obs_format = obs_format\n self.prompt = prompt if prompt is not None else \"\"\n\n def observation(self, obs):\n if self.obs_format == \"obs\":\n return obs\n elif self.obs_format == \"history\":\n observation = self.env.traj[\"observations\"][0] + \"\\n\"\n for i, (o, a) in enumerate(zip(self.env.traj[\"observations\"][1:], self.env.traj[\"actions\"]), 1):\n observation += f\"Action {i}: {a}\\nObservation {i}: {o}\\n\\n\"\n return self.prompt + observation\n \n\ndef normalize_answer(s):\n def remove_articles(text):\n return re.sub(r\"\\b(a|an|the)\\b\", \" \", text)\n \n def white_space_fix(text):\n return \" \".join(text.split())\n\n def remove_punc(text):\n exclude = set(string.punctuation)\n return \"\".join(ch for ch in text if ch not in exclude)\n\n def lower(text):\n return text.lower()\n\n return white_space_fix(remove_articles(remove_punc(lower(s))))\n\ndef f1_score(prediction, ground_truth):\n normalized_prediction = normalize_answer(prediction)","source_hash":"0deac649089a79f9de23297850a143449c31b5988a57c2b5507287b0004116e8","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wrappers.normalize_answer","uri":"program://BOLAA/function/hotpotqa_run.wrappers.normalize_answer#L49-L63","kind":"function","name":"normalize_answer","path":"hotpotqa_run/wrappers.py","language":"python","start_line":49,"end_line":63,"context_start_line":29,"context_end_line":83,"code":"\nclass HistoryWrapper(gym.ObservationWrapper):\n def __init__(self, env, obs_format, prompt=None):\n super().__init__(env)\n assert obs_format in [\"obs\", \"history\"]\n if obs_format == \"history\":\n assert hasattr(self.env, \"traj\")\n self.obs_format = obs_format\n self.prompt = prompt if prompt is not None else \"\"\n\n def observation(self, obs):\n if self.obs_format == \"obs\":\n return obs\n elif self.obs_format == \"history\":\n observation = self.env.traj[\"observations\"][0] + \"\\n\"\n for i, (o, a) in enumerate(zip(self.env.traj[\"observations\"][1:], self.env.traj[\"actions\"]), 1):\n observation += f\"Action {i}: {a}\\nObservation {i}: {o}\\n\\n\"\n return self.prompt + observation\n \n\ndef normalize_answer(s):\n def remove_articles(text):\n return re.sub(r\"\\b(a|an|the)\\b\", \" \", text)\n \n def white_space_fix(text):\n return \" \".join(text.split())\n\n def remove_punc(text):\n exclude = set(string.punctuation)\n return \"\".join(ch for ch in text if ch not in exclude)\n\n def lower(text):\n return text.lower()\n\n return white_space_fix(remove_articles(remove_punc(lower(s))))\n\ndef f1_score(prediction, ground_truth):\n normalized_prediction = normalize_answer(prediction)\n normalized_ground_truth = normalize_answer(ground_truth)\n\n ZERO_METRIC = (0, 0, 0)\n\n if normalized_prediction in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n if normalized_ground_truth in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n \n prediction_tokens = normalized_prediction.split()\n ground_truth_tokens = normalized_ground_truth.split()\n common = Counter(prediction_tokens) & Counter(ground_truth_tokens)\n num_same = sum(common.values())\n if num_same == 0:\n return ZERO_METRIC\n precision = 1.0 * num_same / len(prediction_tokens)\n recall = 1.0 * num_same / len(ground_truth_tokens)","source_hash":"0deac649089a79f9de23297850a143449c31b5988a57c2b5507287b0004116e8","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wrappers.f1_score","uri":"program://BOLAA/function/hotpotqa_run.wrappers.f1_score#L65-L85","kind":"function","name":"f1_score","path":"hotpotqa_run/wrappers.py","language":"python","start_line":65,"end_line":85,"context_start_line":45,"context_end_line":105,"code":" observation += f\"Action {i}: {a}\\nObservation {i}: {o}\\n\\n\"\n return self.prompt + observation\n \n\ndef normalize_answer(s):\n def remove_articles(text):\n return re.sub(r\"\\b(a|an|the)\\b\", \" \", text)\n \n def white_space_fix(text):\n return \" \".join(text.split())\n\n def remove_punc(text):\n exclude = set(string.punctuation)\n return \"\".join(ch for ch in text if ch not in exclude)\n\n def lower(text):\n return text.lower()\n\n return white_space_fix(remove_articles(remove_punc(lower(s))))\n\ndef f1_score(prediction, ground_truth):\n normalized_prediction = normalize_answer(prediction)\n normalized_ground_truth = normalize_answer(ground_truth)\n\n ZERO_METRIC = (0, 0, 0)\n\n if normalized_prediction in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n if normalized_ground_truth in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n \n prediction_tokens = normalized_prediction.split()\n ground_truth_tokens = normalized_ground_truth.split()\n common = Counter(prediction_tokens) & Counter(ground_truth_tokens)\n num_same = sum(common.values())\n if num_same == 0:\n return ZERO_METRIC\n precision = 1.0 * num_same / len(prediction_tokens)\n recall = 1.0 * num_same / len(ground_truth_tokens)\n f1 = (2 * precision * recall) / (precision + recall)\n return f1, precision, recall\n \nclass HotPotQAWrapper(gym.Wrapper):\n def __init__(self, env, split):\n super().__init__(env)\n data_file = f\"{DATA_DIR}/{HOTPOTQA_SPLIT_FILE[split]}\"\n self.data = json.load(open(data_file))\n self.data = [(d['question'], d['answer']) for d in self.data]\n self.data_idx = 0\n self.split = split\n\n def reset(self, seed=None, return_info=False, options=None, idx=None):\n self.env.reset(seed=seed, return_info=return_info, options=options)\n try:\n self.env.step('')\n except:\n pass\n self.env.reset(seed=seed, return_info=return_info, options=options)\n self.data_idx = int(np.random.randint(len(self.data))) if idx is None else idx\n observation = f\"Question: {self.data[self.data_idx][0]}\"\n info = self._get_info()","source_hash":"0deac649089a79f9de23297850a143449c31b5988a57c2b5507287b0004116e8","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wrappers.HotPotQAWrapper","uri":"program://BOLAA/class/hotpotqa_run.wrappers.HotPotQAWrapper#L87-L144","kind":"class","name":"HotPotQAWrapper","path":"hotpotqa_run/wrappers.py","language":"python","start_line":87,"end_line":144,"context_start_line":67,"context_end_line":164,"code":" normalized_ground_truth = normalize_answer(ground_truth)\n\n ZERO_METRIC = (0, 0, 0)\n\n if normalized_prediction in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n if normalized_ground_truth in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n \n prediction_tokens = normalized_prediction.split()\n ground_truth_tokens = normalized_ground_truth.split()\n common = Counter(prediction_tokens) & Counter(ground_truth_tokens)\n num_same = sum(common.values())\n if num_same == 0:\n return ZERO_METRIC\n precision = 1.0 * num_same / len(prediction_tokens)\n recall = 1.0 * num_same / len(ground_truth_tokens)\n f1 = (2 * precision * recall) / (precision + recall)\n return f1, precision, recall\n \nclass HotPotQAWrapper(gym.Wrapper):\n def __init__(self, env, split):\n super().__init__(env)\n data_file = f\"{DATA_DIR}/{HOTPOTQA_SPLIT_FILE[split]}\"\n self.data = json.load(open(data_file))\n self.data = [(d['question'], d['answer']) for d in self.data]\n self.data_idx = 0\n self.split = split\n\n def reset(self, seed=None, return_info=False, options=None, idx=None):\n self.env.reset(seed=seed, return_info=return_info, options=options)\n try:\n self.env.step('')\n except:\n pass\n self.env.reset(seed=seed, return_info=return_info, options=options)\n self.data_idx = int(np.random.randint(len(self.data))) if idx is None else idx\n observation = f\"Question: {self.data[self.data_idx][0]}\"\n info = self._get_info()\n return (observation, info) if return_info else observation\n\n def _get_info(self):\n return {\n \"steps\": self.steps, \n \"answer\": self.answer,\n \"question\": self.data[self.data_idx][0], \n \"hotpot_split\": self.split\n }\n\n def get_reward(self, info):\n if info['answer'] is not None:\n pred = normalize_answer(self.data[self.data_idx][1])\n gt = normalize_answer(info['answer'])\n score = (pred == gt)\n return int(score)\n return 0\n \n def get_metrics(self, info):\n if info['answer'] is not None:\n pred = normalize_answer(self.data[self.data_idx][1])\n gt = normalize_answer(info['answer'])\n em = (pred == gt)\n f1 = f1_score(pred, gt)[0]\n return {'reward': em, 'em': em, 'f1': f1}\n return {'reward': 0, 'em': 0, 'f1': 0}\n\n def step(self, action):\n # TODO: first step obs does not have question. \n obs, _, done, info = self.env.step(action)\n reward = self.get_reward(info)\n if done:\n obs = f\"Episode finished, reward = {reward}\\n\"\n info.update({\"gt_answer\": self.data[self.data_idx][1], \"question_idx\": self.data_idx})\n info.update(self.get_metrics(info))\n return obs, reward, done, info\n \n def __len__(self):\n return len(self.data)\n\nclass FeverWrapper(gym.Wrapper):\n def __init__(self, env, split):\n super().__init__(env)\n \n data_path = f\"./data/{FEVER_SPLIT_FILE[split]}\"\n with open(data_path, \"r\") as json_file:\n json_list = list(json_file)\n\n data = []\n for json_str in json_list:\n json_str = json.loads(json_str)\n label = json_str[\"label\"]\n claim = json_str[\"claim\"]\n data.append((claim, label))\n\n self.data = data\n self.data_idx = 0\n self.split = split\n","source_hash":"0deac649089a79f9de23297850a143449c31b5988a57c2b5507287b0004116e8","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wrappers.FeverWrapper","uri":"program://BOLAA/class/hotpotqa_run.wrappers.FeverWrapper#L146-L204","kind":"class","name":"FeverWrapper","path":"hotpotqa_run/wrappers.py","language":"python","start_line":146,"end_line":204,"context_start_line":126,"context_end_line":224,"code":" pred = normalize_answer(self.data[self.data_idx][1])\n gt = normalize_answer(info['answer'])\n em = (pred == gt)\n f1 = f1_score(pred, gt)[0]\n return {'reward': em, 'em': em, 'f1': f1}\n return {'reward': 0, 'em': 0, 'f1': 0}\n\n def step(self, action):\n # TODO: first step obs does not have question. \n obs, _, done, info = self.env.step(action)\n reward = self.get_reward(info)\n if done:\n obs = f\"Episode finished, reward = {reward}\\n\"\n info.update({\"gt_answer\": self.data[self.data_idx][1], \"question_idx\": self.data_idx})\n info.update(self.get_metrics(info))\n return obs, reward, done, info\n \n def __len__(self):\n return len(self.data)\n\nclass FeverWrapper(gym.Wrapper):\n def __init__(self, env, split):\n super().__init__(env)\n \n data_path = f\"./data/{FEVER_SPLIT_FILE[split]}\"\n with open(data_path, \"r\") as json_file:\n json_list = list(json_file)\n\n data = []\n for json_str in json_list:\n json_str = json.loads(json_str)\n label = json_str[\"label\"]\n claim = json_str[\"claim\"]\n data.append((claim, label))\n\n self.data = data\n self.data_idx = 0\n self.split = split\n\n def reset(self, seed=None, return_info=False, options=None, idx=None):\n self.env.reset(seed=seed, return_info=return_info, options=options)\n try:\n self.env.step('')\n except:\n pass\n self.env.reset(seed=seed, return_info=return_info, options=options)\n self.data_idx = int(np.random.randint(len(self.data))) if idx is None else idx\n observation = f\"Claim: {self.data[self.data_idx][0]}\"\n info = self._get_info()\n return (observation, info) if return_info else observation\n\n def _get_info(self):\n return {\n \"steps\": self.steps, \n \"answer\": self.answer,\n \"question\": self.data[self.data_idx][0], \n \"fever_split\": self.split\n }\n\n def get_reward(self, info):\n if info['answer'] is not None:\n label = normalize_answer(self.data[self.data_idx][1])\n pred = normalize_answer(info['answer'])\n if label == pred:\n return 1\n return 0\n\n def step(self, action):\n # TODO: first step obs does not have question. \n obs, _, done, info = self.env.step(action)\n reward = self.get_reward(info)\n if done:\n obs = f\"Episode finished, reward = {reward}\\n\"\n info.update({\"gt_answer\": self.data[self.data_idx][1], \"question_idx\": self.data_idx})\n info.update({'em': reward, 'reward': reward, 'f1': reward})\n return obs, reward, done, info\n \n def __len__(self):\n return len(self.data)\n \n \nclass LoggingWrapper(gym.Wrapper):\n def __init__(self, env, folder=\"trajs\", file_id=None):\n super().__init__(env)\n self.trajs = []\n self.traj = {\"observations\": [], \"actions\": []}\n self.folder = folder\n self.file_id = np.random.randint(0, 10000000) if file_id is None else file_id\n self.file_path = f\"{self.folder}/{self.file_id}.json\"\n os.makedirs(\"trajs\", exist_ok=True)\n\n def __len__(self):\n return len(self.env.data)\n \n\n def reset(self, seed=None, return_info=False, options=None, idx=None):\n output = self.env.reset(seed=seed, return_info=return_info, options=options, idx=idx)\n observation = output[0] if return_info else output\n self.traj = {\"observations\": [observation], \"actions\": []}","source_hash":"0deac649089a79f9de23297850a143449c31b5988a57c2b5507287b0004116e8","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wrappers.LoggingWrapper","uri":"program://BOLAA/class/hotpotqa_run.wrappers.LoggingWrapper#L207-L247","kind":"class","name":"LoggingWrapper","path":"hotpotqa_run/wrappers.py","language":"python","start_line":207,"end_line":247,"context_start_line":187,"context_end_line":247,"code":" label = normalize_answer(self.data[self.data_idx][1])\n pred = normalize_answer(info['answer'])\n if label == pred:\n return 1\n return 0\n\n def step(self, action):\n # TODO: first step obs does not have question. \n obs, _, done, info = self.env.step(action)\n reward = self.get_reward(info)\n if done:\n obs = f\"Episode finished, reward = {reward}\\n\"\n info.update({\"gt_answer\": self.data[self.data_idx][1], \"question_idx\": self.data_idx})\n info.update({'em': reward, 'reward': reward, 'f1': reward})\n return obs, reward, done, info\n \n def __len__(self):\n return len(self.data)\n \n \nclass LoggingWrapper(gym.Wrapper):\n def __init__(self, env, folder=\"trajs\", file_id=None):\n super().__init__(env)\n self.trajs = []\n self.traj = {\"observations\": [], \"actions\": []}\n self.folder = folder\n self.file_id = np.random.randint(0, 10000000) if file_id is None else file_id\n self.file_path = f\"{self.folder}/{self.file_id}.json\"\n os.makedirs(\"trajs\", exist_ok=True)\n\n def __len__(self):\n return len(self.env.data)\n \n\n def reset(self, seed=None, return_info=False, options=None, idx=None):\n output = self.env.reset(seed=seed, return_info=return_info, options=options, idx=idx)\n observation = output[0] if return_info else output\n self.traj = {\"observations\": [observation], \"actions\": []}\n return output\n\n def step(self, action):\n obs, reward, done, info = self.env.step(action)\n self.traj[\"observations\"].append(obs)\n self.traj[\"actions\"].append(action)\n if done:\n self.traj.update(info)\n return obs, reward, done, info\n\n def update_record(self):\n if len(self.traj) > 0:\n self.trajs.append(self.traj)\n self.traj = {\"observations\": [], \"actions\": []}\n \n def write(self):\n self.update_record()\n with open(self.file_path, \"w\") as f:\n json.dump(self.trajs, f)\n print(f\"Saved trajs to trajs/{self.file_id}.json\")\n \n def close(self):\n self.write()","source_hash":"0deac649089a79f9de23297850a143449c31b5988a57c2b5507287b0004116e8","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wrappers.__init__","uri":"program://BOLAA/function/hotpotqa_run.wrappers.__init__#L208-L215","kind":"function","name":"__init__","path":"hotpotqa_run/wrappers.py","language":"python","start_line":208,"end_line":215,"context_start_line":188,"context_end_line":235,"code":" pred = normalize_answer(info['answer'])\n if label == pred:\n return 1\n return 0\n\n def step(self, action):\n # TODO: first step obs does not have question. \n obs, _, done, info = self.env.step(action)\n reward = self.get_reward(info)\n if done:\n obs = f\"Episode finished, reward = {reward}\\n\"\n info.update({\"gt_answer\": self.data[self.data_idx][1], \"question_idx\": self.data_idx})\n info.update({'em': reward, 'reward': reward, 'f1': reward})\n return obs, reward, done, info\n \n def __len__(self):\n return len(self.data)\n \n \nclass LoggingWrapper(gym.Wrapper):\n def __init__(self, env, folder=\"trajs\", file_id=None):\n super().__init__(env)\n self.trajs = []\n self.traj = {\"observations\": [], \"actions\": []}\n self.folder = folder\n self.file_id = np.random.randint(0, 10000000) if file_id is None else file_id\n self.file_path = f\"{self.folder}/{self.file_id}.json\"\n os.makedirs(\"trajs\", exist_ok=True)\n\n def __len__(self):\n return len(self.env.data)\n \n\n def reset(self, seed=None, return_info=False, options=None, idx=None):\n output = self.env.reset(seed=seed, return_info=return_info, options=options, idx=idx)\n observation = output[0] if return_info else output\n self.traj = {\"observations\": [observation], \"actions\": []}\n return output\n\n def step(self, action):\n obs, reward, done, info = self.env.step(action)\n self.traj[\"observations\"].append(obs)\n self.traj[\"actions\"].append(action)\n if done:\n self.traj.update(info)\n return obs, reward, done, info\n\n def update_record(self):","source_hash":"0deac649089a79f9de23297850a143449c31b5988a57c2b5507287b0004116e8","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wrappers.observation","uri":"program://BOLAA/function/hotpotqa_run.wrappers.observation#L39-L46","kind":"function","name":"observation","path":"hotpotqa_run/wrappers.py","language":"python","start_line":39,"end_line":46,"context_start_line":19,"context_end_line":66,"code":" \"train\": \"hotpot_train_v1.1_simplified.json\",\n \"dev\": \"hotpot_dev_v1_simplified.json\",\n \"test\": \"hotpot_test_v1_simplified.json\",\n}\n\nFEVER_SPLIT_FILE = {\n \"train\": \"train.jsonl\",\n \"dev\": \"paper_dev.jsonl\",\n}\n\n\nclass HistoryWrapper(gym.ObservationWrapper):\n def __init__(self, env, obs_format, prompt=None):\n super().__init__(env)\n assert obs_format in [\"obs\", \"history\"]\n if obs_format == \"history\":\n assert hasattr(self.env, \"traj\")\n self.obs_format = obs_format\n self.prompt = prompt if prompt is not None else \"\"\n\n def observation(self, obs):\n if self.obs_format == \"obs\":\n return obs\n elif self.obs_format == \"history\":\n observation = self.env.traj[\"observations\"][0] + \"\\n\"\n for i, (o, a) in enumerate(zip(self.env.traj[\"observations\"][1:], self.env.traj[\"actions\"]), 1):\n observation += f\"Action {i}: {a}\\nObservation {i}: {o}\\n\\n\"\n return self.prompt + observation\n \n\ndef normalize_answer(s):\n def remove_articles(text):\n return re.sub(r\"\\b(a|an|the)\\b\", \" \", text)\n \n def white_space_fix(text):\n return \" \".join(text.split())\n\n def remove_punc(text):\n exclude = set(string.punctuation)\n return \"\".join(ch for ch in text if ch not in exclude)\n\n def lower(text):\n return text.lower()\n\n return white_space_fix(remove_articles(remove_punc(lower(s))))\n\ndef f1_score(prediction, ground_truth):\n normalized_prediction = normalize_answer(prediction)","source_hash":"0deac649089a79f9de23297850a143449c31b5988a57c2b5507287b0004116e8","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wrappers.remove_articles","uri":"program://BOLAA/function/hotpotqa_run.wrappers.remove_articles#L50-L51","kind":"function","name":"remove_articles","path":"hotpotqa_run/wrappers.py","language":"python","start_line":50,"end_line":51,"context_start_line":30,"context_end_line":71,"code":"class HistoryWrapper(gym.ObservationWrapper):\n def __init__(self, env, obs_format, prompt=None):\n super().__init__(env)\n assert obs_format in [\"obs\", \"history\"]\n if obs_format == \"history\":\n assert hasattr(self.env, \"traj\")\n self.obs_format = obs_format\n self.prompt = prompt if prompt is not None else \"\"\n\n def observation(self, obs):\n if self.obs_format == \"obs\":\n return obs\n elif self.obs_format == \"history\":\n observation = self.env.traj[\"observations\"][0] + \"\\n\"\n for i, (o, a) in enumerate(zip(self.env.traj[\"observations\"][1:], self.env.traj[\"actions\"]), 1):\n observation += f\"Action {i}: {a}\\nObservation {i}: {o}\\n\\n\"\n return self.prompt + observation\n \n\ndef normalize_answer(s):\n def remove_articles(text):\n return re.sub(r\"\\b(a|an|the)\\b\", \" \", text)\n \n def white_space_fix(text):\n return \" \".join(text.split())\n\n def remove_punc(text):\n exclude = set(string.punctuation)\n return \"\".join(ch for ch in text if ch not in exclude)\n\n def lower(text):\n return text.lower()\n\n return white_space_fix(remove_articles(remove_punc(lower(s))))\n\ndef f1_score(prediction, ground_truth):\n normalized_prediction = normalize_answer(prediction)\n normalized_ground_truth = normalize_answer(ground_truth)\n\n ZERO_METRIC = (0, 0, 0)\n\n if normalized_prediction in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:","source_hash":"0deac649089a79f9de23297850a143449c31b5988a57c2b5507287b0004116e8","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wrappers.white_space_fix","uri":"program://BOLAA/function/hotpotqa_run.wrappers.white_space_fix#L53-L54","kind":"function","name":"white_space_fix","path":"hotpotqa_run/wrappers.py","language":"python","start_line":53,"end_line":54,"context_start_line":33,"context_end_line":74,"code":" assert obs_format in [\"obs\", \"history\"]\n if obs_format == \"history\":\n assert hasattr(self.env, \"traj\")\n self.obs_format = obs_format\n self.prompt = prompt if prompt is not None else \"\"\n\n def observation(self, obs):\n if self.obs_format == \"obs\":\n return obs\n elif self.obs_format == \"history\":\n observation = self.env.traj[\"observations\"][0] + \"\\n\"\n for i, (o, a) in enumerate(zip(self.env.traj[\"observations\"][1:], self.env.traj[\"actions\"]), 1):\n observation += f\"Action {i}: {a}\\nObservation {i}: {o}\\n\\n\"\n return self.prompt + observation\n \n\ndef normalize_answer(s):\n def remove_articles(text):\n return re.sub(r\"\\b(a|an|the)\\b\", \" \", text)\n \n def white_space_fix(text):\n return \" \".join(text.split())\n\n def remove_punc(text):\n exclude = set(string.punctuation)\n return \"\".join(ch for ch in text if ch not in exclude)\n\n def lower(text):\n return text.lower()\n\n return white_space_fix(remove_articles(remove_punc(lower(s))))\n\ndef f1_score(prediction, ground_truth):\n normalized_prediction = normalize_answer(prediction)\n normalized_ground_truth = normalize_answer(ground_truth)\n\n ZERO_METRIC = (0, 0, 0)\n\n if normalized_prediction in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n if normalized_ground_truth in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC","source_hash":"0deac649089a79f9de23297850a143449c31b5988a57c2b5507287b0004116e8","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wrappers.remove_punc","uri":"program://BOLAA/function/hotpotqa_run.wrappers.remove_punc#L56-L58","kind":"function","name":"remove_punc","path":"hotpotqa_run/wrappers.py","language":"python","start_line":56,"end_line":58,"context_start_line":36,"context_end_line":78,"code":" self.obs_format = obs_format\n self.prompt = prompt if prompt is not None else \"\"\n\n def observation(self, obs):\n if self.obs_format == \"obs\":\n return obs\n elif self.obs_format == \"history\":\n observation = self.env.traj[\"observations\"][0] + \"\\n\"\n for i, (o, a) in enumerate(zip(self.env.traj[\"observations\"][1:], self.env.traj[\"actions\"]), 1):\n observation += f\"Action {i}: {a}\\nObservation {i}: {o}\\n\\n\"\n return self.prompt + observation\n \n\ndef normalize_answer(s):\n def remove_articles(text):\n return re.sub(r\"\\b(a|an|the)\\b\", \" \", text)\n \n def white_space_fix(text):\n return \" \".join(text.split())\n\n def remove_punc(text):\n exclude = set(string.punctuation)\n return \"\".join(ch for ch in text if ch not in exclude)\n\n def lower(text):\n return text.lower()\n\n return white_space_fix(remove_articles(remove_punc(lower(s))))\n\ndef f1_score(prediction, ground_truth):\n normalized_prediction = normalize_answer(prediction)\n normalized_ground_truth = normalize_answer(ground_truth)\n\n ZERO_METRIC = (0, 0, 0)\n\n if normalized_prediction in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n if normalized_ground_truth in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n \n prediction_tokens = normalized_prediction.split()\n ground_truth_tokens = normalized_ground_truth.split()\n common = Counter(prediction_tokens) & Counter(ground_truth_tokens)","source_hash":"0deac649089a79f9de23297850a143449c31b5988a57c2b5507287b0004116e8","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wrappers.lower","uri":"program://BOLAA/function/hotpotqa_run.wrappers.lower#L60-L61","kind":"function","name":"lower","path":"hotpotqa_run/wrappers.py","language":"python","start_line":60,"end_line":61,"context_start_line":40,"context_end_line":81,"code":" if self.obs_format == \"obs\":\n return obs\n elif self.obs_format == \"history\":\n observation = self.env.traj[\"observations\"][0] + \"\\n\"\n for i, (o, a) in enumerate(zip(self.env.traj[\"observations\"][1:], self.env.traj[\"actions\"]), 1):\n observation += f\"Action {i}: {a}\\nObservation {i}: {o}\\n\\n\"\n return self.prompt + observation\n \n\ndef normalize_answer(s):\n def remove_articles(text):\n return re.sub(r\"\\b(a|an|the)\\b\", \" \", text)\n \n def white_space_fix(text):\n return \" \".join(text.split())\n\n def remove_punc(text):\n exclude = set(string.punctuation)\n return \"\".join(ch for ch in text if ch not in exclude)\n\n def lower(text):\n return text.lower()\n\n return white_space_fix(remove_articles(remove_punc(lower(s))))\n\ndef f1_score(prediction, ground_truth):\n normalized_prediction = normalize_answer(prediction)\n normalized_ground_truth = normalize_answer(ground_truth)\n\n ZERO_METRIC = (0, 0, 0)\n\n if normalized_prediction in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n if normalized_ground_truth in ['yes', 'no', 'noanswer'] and normalized_prediction != normalized_ground_truth:\n return ZERO_METRIC\n \n prediction_tokens = normalized_prediction.split()\n ground_truth_tokens = normalized_ground_truth.split()\n common = Counter(prediction_tokens) & Counter(ground_truth_tokens)\n num_same = sum(common.values())\n if num_same == 0:\n return ZERO_METRIC","source_hash":"0deac649089a79f9de23297850a143449c31b5988a57c2b5507287b0004116e8","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wrappers.reset","uri":"program://BOLAA/function/hotpotqa_run.wrappers.reset#L221-L225","kind":"function","name":"reset","path":"hotpotqa_run/wrappers.py","language":"python","start_line":221,"end_line":225,"context_start_line":201,"context_end_line":245,"code":" return obs, reward, done, info\n \n def __len__(self):\n return len(self.data)\n \n \nclass LoggingWrapper(gym.Wrapper):\n def __init__(self, env, folder=\"trajs\", file_id=None):\n super().__init__(env)\n self.trajs = []\n self.traj = {\"observations\": [], \"actions\": []}\n self.folder = folder\n self.file_id = np.random.randint(0, 10000000) if file_id is None else file_id\n self.file_path = f\"{self.folder}/{self.file_id}.json\"\n os.makedirs(\"trajs\", exist_ok=True)\n\n def __len__(self):\n return len(self.env.data)\n \n\n def reset(self, seed=None, return_info=False, options=None, idx=None):\n output = self.env.reset(seed=seed, return_info=return_info, options=options, idx=idx)\n observation = output[0] if return_info else output\n self.traj = {\"observations\": [observation], \"actions\": []}\n return output\n\n def step(self, action):\n obs, reward, done, info = self.env.step(action)\n self.traj[\"observations\"].append(obs)\n self.traj[\"actions\"].append(action)\n if done:\n self.traj.update(info)\n return obs, reward, done, info\n\n def update_record(self):\n if len(self.traj) > 0:\n self.trajs.append(self.traj)\n self.traj = {\"observations\": [], \"actions\": []}\n \n def write(self):\n self.update_record()\n with open(self.file_path, \"w\") as f:\n json.dump(self.trajs, f)\n print(f\"Saved trajs to trajs/{self.file_id}.json\")\n ","source_hash":"0deac649089a79f9de23297850a143449c31b5988a57c2b5507287b0004116e8","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wrappers._get_info","uri":"program://BOLAA/function/hotpotqa_run.wrappers._get_info#L177-L183","kind":"function","name":"_get_info","path":"hotpotqa_run/wrappers.py","language":"python","start_line":177,"end_line":183,"context_start_line":157,"context_end_line":203,"code":" label = json_str[\"label\"]\n claim = json_str[\"claim\"]\n data.append((claim, label))\n\n self.data = data\n self.data_idx = 0\n self.split = split\n\n def reset(self, seed=None, return_info=False, options=None, idx=None):\n self.env.reset(seed=seed, return_info=return_info, options=options)\n try:\n self.env.step('')\n except:\n pass\n self.env.reset(seed=seed, return_info=return_info, options=options)\n self.data_idx = int(np.random.randint(len(self.data))) if idx is None else idx\n observation = f\"Claim: {self.data[self.data_idx][0]}\"\n info = self._get_info()\n return (observation, info) if return_info else observation\n\n def _get_info(self):\n return {\n \"steps\": self.steps, \n \"answer\": self.answer,\n \"question\": self.data[self.data_idx][0], \n \"fever_split\": self.split\n }\n\n def get_reward(self, info):\n if info['answer'] is not None:\n label = normalize_answer(self.data[self.data_idx][1])\n pred = normalize_answer(info['answer'])\n if label == pred:\n return 1\n return 0\n\n def step(self, action):\n # TODO: first step obs does not have question. \n obs, _, done, info = self.env.step(action)\n reward = self.get_reward(info)\n if done:\n obs = f\"Episode finished, reward = {reward}\\n\"\n info.update({\"gt_answer\": self.data[self.data_idx][1], \"question_idx\": self.data_idx})\n info.update({'em': reward, 'reward': reward, 'f1': reward})\n return obs, reward, done, info\n \n def __len__(self):","source_hash":"0deac649089a79f9de23297850a143449c31b5988a57c2b5507287b0004116e8","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wrappers.get_reward","uri":"program://BOLAA/function/hotpotqa_run.wrappers.get_reward#L185-L191","kind":"function","name":"get_reward","path":"hotpotqa_run/wrappers.py","language":"python","start_line":185,"end_line":191,"context_start_line":165,"context_end_line":211,"code":" def reset(self, seed=None, return_info=False, options=None, idx=None):\n self.env.reset(seed=seed, return_info=return_info, options=options)\n try:\n self.env.step('')\n except:\n pass\n self.env.reset(seed=seed, return_info=return_info, options=options)\n self.data_idx = int(np.random.randint(len(self.data))) if idx is None else idx\n observation = f\"Claim: {self.data[self.data_idx][0]}\"\n info = self._get_info()\n return (observation, info) if return_info else observation\n\n def _get_info(self):\n return {\n \"steps\": self.steps, \n \"answer\": self.answer,\n \"question\": self.data[self.data_idx][0], \n \"fever_split\": self.split\n }\n\n def get_reward(self, info):\n if info['answer'] is not None:\n label = normalize_answer(self.data[self.data_idx][1])\n pred = normalize_answer(info['answer'])\n if label == pred:\n return 1\n return 0\n\n def step(self, action):\n # TODO: first step obs does not have question. \n obs, _, done, info = self.env.step(action)\n reward = self.get_reward(info)\n if done:\n obs = f\"Episode finished, reward = {reward}\\n\"\n info.update({\"gt_answer\": self.data[self.data_idx][1], \"question_idx\": self.data_idx})\n info.update({'em': reward, 'reward': reward, 'f1': reward})\n return obs, reward, done, info\n \n def __len__(self):\n return len(self.data)\n \n \nclass LoggingWrapper(gym.Wrapper):\n def __init__(self, env, folder=\"trajs\", file_id=None):\n super().__init__(env)\n self.trajs = []\n self.traj = {\"observations\": [], \"actions\": []}","source_hash":"0deac649089a79f9de23297850a143449c31b5988a57c2b5507287b0004116e8","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wrappers.get_metrics","uri":"program://BOLAA/function/hotpotqa_run.wrappers.get_metrics#L124-L131","kind":"function","name":"get_metrics","path":"hotpotqa_run/wrappers.py","language":"python","start_line":124,"end_line":131,"context_start_line":104,"context_end_line":151,"code":" observation = f\"Question: {self.data[self.data_idx][0]}\"\n info = self._get_info()\n return (observation, info) if return_info else observation\n\n def _get_info(self):\n return {\n \"steps\": self.steps, \n \"answer\": self.answer,\n \"question\": self.data[self.data_idx][0], \n \"hotpot_split\": self.split\n }\n\n def get_reward(self, info):\n if info['answer'] is not None:\n pred = normalize_answer(self.data[self.data_idx][1])\n gt = normalize_answer(info['answer'])\n score = (pred == gt)\n return int(score)\n return 0\n \n def get_metrics(self, info):\n if info['answer'] is not None:\n pred = normalize_answer(self.data[self.data_idx][1])\n gt = normalize_answer(info['answer'])\n em = (pred == gt)\n f1 = f1_score(pred, gt)[0]\n return {'reward': em, 'em': em, 'f1': f1}\n return {'reward': 0, 'em': 0, 'f1': 0}\n\n def step(self, action):\n # TODO: first step obs does not have question. \n obs, _, done, info = self.env.step(action)\n reward = self.get_reward(info)\n if done:\n obs = f\"Episode finished, reward = {reward}\\n\"\n info.update({\"gt_answer\": self.data[self.data_idx][1], \"question_idx\": self.data_idx})\n info.update(self.get_metrics(info))\n return obs, reward, done, info\n \n def __len__(self):\n return len(self.data)\n\nclass FeverWrapper(gym.Wrapper):\n def __init__(self, env, split):\n super().__init__(env)\n \n data_path = f\"./data/{FEVER_SPLIT_FILE[split]}\"\n with open(data_path, \"r\") as json_file:","source_hash":"0deac649089a79f9de23297850a143449c31b5988a57c2b5507287b0004116e8","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wrappers.step","uri":"program://BOLAA/function/hotpotqa_run.wrappers.step#L227-L233","kind":"function","name":"step","path":"hotpotqa_run/wrappers.py","language":"python","start_line":227,"end_line":233,"context_start_line":207,"context_end_line":247,"code":"class LoggingWrapper(gym.Wrapper):\n def __init__(self, env, folder=\"trajs\", file_id=None):\n super().__init__(env)\n self.trajs = []\n self.traj = {\"observations\": [], \"actions\": []}\n self.folder = folder\n self.file_id = np.random.randint(0, 10000000) if file_id is None else file_id\n self.file_path = f\"{self.folder}/{self.file_id}.json\"\n os.makedirs(\"trajs\", exist_ok=True)\n\n def __len__(self):\n return len(self.env.data)\n \n\n def reset(self, seed=None, return_info=False, options=None, idx=None):\n output = self.env.reset(seed=seed, return_info=return_info, options=options, idx=idx)\n observation = output[0] if return_info else output\n self.traj = {\"observations\": [observation], \"actions\": []}\n return output\n\n def step(self, action):\n obs, reward, done, info = self.env.step(action)\n self.traj[\"observations\"].append(obs)\n self.traj[\"actions\"].append(action)\n if done:\n self.traj.update(info)\n return obs, reward, done, info\n\n def update_record(self):\n if len(self.traj) > 0:\n self.trajs.append(self.traj)\n self.traj = {\"observations\": [], \"actions\": []}\n \n def write(self):\n self.update_record()\n with open(self.file_path, \"w\") as f:\n json.dump(self.trajs, f)\n print(f\"Saved trajs to trajs/{self.file_id}.json\")\n \n def close(self):\n self.write()","source_hash":"0deac649089a79f9de23297850a143449c31b5988a57c2b5507287b0004116e8","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wrappers.__len__","uri":"program://BOLAA/function/hotpotqa_run.wrappers.__len__#L217-L218","kind":"function","name":"__len__","path":"hotpotqa_run/wrappers.py","language":"python","start_line":217,"end_line":218,"context_start_line":197,"context_end_line":238,"code":" if done:\n obs = f\"Episode finished, reward = {reward}\\n\"\n info.update({\"gt_answer\": self.data[self.data_idx][1], \"question_idx\": self.data_idx})\n info.update({'em': reward, 'reward': reward, 'f1': reward})\n return obs, reward, done, info\n \n def __len__(self):\n return len(self.data)\n \n \nclass LoggingWrapper(gym.Wrapper):\n def __init__(self, env, folder=\"trajs\", file_id=None):\n super().__init__(env)\n self.trajs = []\n self.traj = {\"observations\": [], \"actions\": []}\n self.folder = folder\n self.file_id = np.random.randint(0, 10000000) if file_id is None else file_id\n self.file_path = f\"{self.folder}/{self.file_id}.json\"\n os.makedirs(\"trajs\", exist_ok=True)\n\n def __len__(self):\n return len(self.env.data)\n \n\n def reset(self, seed=None, return_info=False, options=None, idx=None):\n output = self.env.reset(seed=seed, return_info=return_info, options=options, idx=idx)\n observation = output[0] if return_info else output\n self.traj = {\"observations\": [observation], \"actions\": []}\n return output\n\n def step(self, action):\n obs, reward, done, info = self.env.step(action)\n self.traj[\"observations\"].append(obs)\n self.traj[\"actions\"].append(action)\n if done:\n self.traj.update(info)\n return obs, reward, done, info\n\n def update_record(self):\n if len(self.traj) > 0:\n self.trajs.append(self.traj)\n self.traj = {\"observations\": [], \"actions\": []}","source_hash":"0deac649089a79f9de23297850a143449c31b5988a57c2b5507287b0004116e8","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wrappers.update_record","uri":"program://BOLAA/function/hotpotqa_run.wrappers.update_record#L235-L238","kind":"function","name":"update_record","path":"hotpotqa_run/wrappers.py","language":"python","start_line":235,"end_line":238,"context_start_line":215,"context_end_line":247,"code":" os.makedirs(\"trajs\", exist_ok=True)\n\n def __len__(self):\n return len(self.env.data)\n \n\n def reset(self, seed=None, return_info=False, options=None, idx=None):\n output = self.env.reset(seed=seed, return_info=return_info, options=options, idx=idx)\n observation = output[0] if return_info else output\n self.traj = {\"observations\": [observation], \"actions\": []}\n return output\n\n def step(self, action):\n obs, reward, done, info = self.env.step(action)\n self.traj[\"observations\"].append(obs)\n self.traj[\"actions\"].append(action)\n if done:\n self.traj.update(info)\n return obs, reward, done, info\n\n def update_record(self):\n if len(self.traj) > 0:\n self.trajs.append(self.traj)\n self.traj = {\"observations\": [], \"actions\": []}\n \n def write(self):\n self.update_record()\n with open(self.file_path, \"w\") as f:\n json.dump(self.trajs, f)\n print(f\"Saved trajs to trajs/{self.file_id}.json\")\n \n def close(self):\n self.write()","source_hash":"0deac649089a79f9de23297850a143449c31b5988a57c2b5507287b0004116e8","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wrappers.write","uri":"program://BOLAA/function/hotpotqa_run.wrappers.write#L240-L244","kind":"function","name":"write","path":"hotpotqa_run/wrappers.py","language":"python","start_line":240,"end_line":244,"context_start_line":220,"context_end_line":247,"code":"\n def reset(self, seed=None, return_info=False, options=None, idx=None):\n output = self.env.reset(seed=seed, return_info=return_info, options=options, idx=idx)\n observation = output[0] if return_info else output\n self.traj = {\"observations\": [observation], \"actions\": []}\n return output\n\n def step(self, action):\n obs, reward, done, info = self.env.step(action)\n self.traj[\"observations\"].append(obs)\n self.traj[\"actions\"].append(action)\n if done:\n self.traj.update(info)\n return obs, reward, done, info\n\n def update_record(self):\n if len(self.traj) > 0:\n self.trajs.append(self.traj)\n self.traj = {\"observations\": [], \"actions\": []}\n \n def write(self):\n self.update_record()\n with open(self.file_path, \"w\") as f:\n json.dump(self.trajs, f)\n print(f\"Saved trajs to trajs/{self.file_id}.json\")\n \n def close(self):\n self.write()","source_hash":"0deac649089a79f9de23297850a143449c31b5988a57c2b5507287b0004116e8","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.wrappers.close","uri":"program://BOLAA/function/hotpotqa_run.wrappers.close#L246-L247","kind":"function","name":"close","path":"hotpotqa_run/wrappers.py","language":"python","start_line":246,"end_line":247,"context_start_line":226,"context_end_line":247,"code":"\n def step(self, action):\n obs, reward, done, info = self.env.step(action)\n self.traj[\"observations\"].append(obs)\n self.traj[\"actions\"].append(action)\n if done:\n self.traj.update(info)\n return obs, reward, done, info\n\n def update_record(self):\n if len(self.traj) > 0:\n self.trajs.append(self.traj)\n self.traj = {\"observations\": [], \"actions\": []}\n \n def write(self):\n self.update_record()\n with open(self.file_path, \"w\") as f:\n json.dump(self.trajs, f)\n print(f\"Saved trajs to trajs/{self.file_id}.json\")\n \n def close(self):\n self.write()","source_hash":"0deac649089a79f9de23297850a143449c31b5988a57c2b5507287b0004116e8","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.pre_prompt","uri":"program://BOLAA/module/hotpotqa_run.pre_prompt#L1-L83","kind":"module","name":"hotpotqa_run.pre_prompt","path":"hotpotqa_run/pre_prompt.py","language":"python","start_line":1,"end_line":83,"context_start_line":1,"context_end_line":83,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nfrom langchain.prompts import PromptTemplate\n\nZEROSHOT_INSTRUCTION = \"\"\"Solve a question answering task with interleaving Thought, Action, Observation steps. Thought can reason about the current situation, and Action can be three types: \n(1) Search[entity], which searches the exact entity on Wikipedia and returns the first paragraph if it exists. If not, it will return some similar entities to search. For example, Search[Milhouse]\n(2) Lookup[keyword], which returns the next sentence containing keyword in the last passage successfully found by Search. For example, Lookup[named after]\n(3) Finish[answer], which returns the answer and finishes the task. For example, Finish[Richard Nixon] \nYou may take as many steps as necessary.\nQuestion: {question}{scratchpad}\"\"\"\n\nzeroshot_agent_prompt = PromptTemplate(\n input_variables=[\"question\", \"scratchpad\"],\n template = ZEROSHOT_INSTRUCTION,\n )\n\nREACT_INSTRUCTION = \"\"\"Solve a question answering task with interleaving Thought, Action, Observation steps. Thought can reason about the current situation, and Action can be three types: \n(1) Search[entity], which searches the exact entity on Wikipedia and returns the first paragraph if it exists. If not, it will return some similar entities to search.\n(2) Lookup[keyword], which returns the next sentence containing keyword in the last passage successfully found by Search.\n(3) Finish[answer], which returns the answer and finishes the task.\nYou may take as many steps as necessary.\nHere are some examples:\n{examples}\n(END OF EXAMPLES)\nQuestion: {question}{scratchpad}\"\"\"\n\nreact_agent_prompt = PromptTemplate(\n input_variables=[\"examples\", \"question\", \"scratchpad\"],\n template = REACT_INSTRUCTION,\n )\n\nPLAN_INSTRUCTION = \"\"\"Setup a plan for answering question with Actions. Action can be three types: \n(1) Search[entity], which searches the exact entity on Wikipedia and returns the first paragraph if it exists. If not, it will return some similar entities to search.\n(2) Lookup[keyword], which returns the next sentence containing keyword in the last passage successfully found by Search.\n(3) Finish[answer], which returns the answer and finishes the task.\n{examples}\n(END OF EXAMPLES)\nQuestion: {question}\nPlan:\"\"\"\n\nplan_prompt = PromptTemplate(\n input_variables=[\"examples\", \"question\"],\n template = PLAN_INSTRUCTION,\n )\n\nPLANNER_INSTRUCTION = \"\"\"Solve a question answering task with Plan, interleaving Action, Observation steps. Plan is decided ahead of Actions. Action can be three types: \n(1) Search[entity], which searches the exact entity on Wikipedia and returns the first paragraph if it exists. If not, it will return some similar entities to search.\n(2) Lookup[keyword], which returns the next sentence containing keyword in the last passage successfully found by Search.\n(3) Finish[answer], which returns the answer and finishes the task.\nYou may take as many steps as necessary.\nHere are some examples:\n{examples}\n(END OF EXAMPLES)\nQuestion: {question}\nPlan: {plan}{scratchpad}\"\"\"\n\nplanner_agent_prompt = PromptTemplate(\n input_variables=[\"examples\", \"question\", \"plan\", \"scratchpad\"],\n template = PLANNER_INSTRUCTION,\n )\n\nPLANNERREACT_INSTRUCTION = \"\"\"Solve a question answering task with Plan, interleaving Thought, Action, Observation steps. Plan is decided ahead of Actions. Thought can reason about the current situation. Action can be three types: \n(1) Search[entity], which searches the exact entity on Wikipedia and returns the first paragraph if it exists. If not, it will return some similar entities to search.\n(2) Lookup[keyword], which returns the next sentence containing keyword in the last passage successfully found by Search.\n(3) Finish[answer], which returns the answer and finishes the task.\nYou may take as many steps as necessary.\nHere are some examples:\n{examples}\n(END OF EXAMPLES)\nQuestion: {question}\nPlan: {plan}{scratchpad}\"\"\"\n\nplannerreact_agent_prompt = PromptTemplate(\n input_variables=[\"examples\", \"question\", \"plan\", \"scratchpad\"],\n template = PLANNERREACT_INSTRUCTION,\n )\n\n","source_hash":"a0f91ffc099bc5baaa174497fc6aa25d7b316a083a3ff8aa89a5d86335a222eb","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.fewshots","uri":"program://BOLAA/module/hotpotqa_run.fewshots#L1-L276","kind":"module","name":"hotpotqa_run.fewshots","path":"hotpotqa_run/fewshots.py","language":"python","start_line":1,"end_line":276,"context_start_line":1,"context_end_line":276,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nREACT_EXAMPLE = \"\"\"Question: Musician and satirist Allie Goertz wrote a song about the \"The Simpsons\" character Milhouse, who Matt Groening named after who?\nThought 1: The question simplifies to \"The Simpsons\" character Milhouse is named after who. I only need to search Milhouse and find who it is named after.\nAction 1: Search[Milhouse]\nObservation 1: Milhouse Mussolini Van Houten is a recurring character in the Fox animated television series The Simpsons voiced by Pamela Hayden and created by Matt Groening.\nThought 2: The paragraph does not tell who Milhouse is named after, maybe I can look up \"named after\".\nAction 2: Lookup[named after]\nObservation 2: (Result 1 / 1) Milhouse was named after U.S. president Richard Nixon, whose middle name was Milhous. \nThought 3: Milhouse was named after U.S. president Richard Nixon, so the answer is Richard Nixon.\nAction 3: Finish[Richard Nixon]\n\nQuestion: Were Pavel Urysohn and Leonid Levin known for the same type of work?\nThought 1: I need to search Pavel Urysohn and Leonid Levin, find their types of work, then find if they are the same.\nAction 1: Search[Pavel Urysohn]\nObservation 1: Pavel Samuilovich Urysohn (February 3, 1898 – August 17, 1924) was a Soviet mathematician who is best known for his contributions in dimension theory.\nThought 2: Pavel Urysohn is a mathematician. I need to search Leonid Levin next and find its type of work.\nAction 2: Search[Leonid Levin]\nObservation 2: Leonid Anatolievich Levin is a Soviet-American mathematician and computer scientist. \nThought 3: Leonid Levin is a mathematician and computer scientist. So Pavel Urysohn and Leonid Levin have the same type of work. \nAction 3: Finish[yes]\n\"\"\"\n\nPLAN_EXAMPLE = \"\"\"Question: Musician and satirist Allie Goertz wrote a song about the \"The Simpsons\" character Milhouse, who Matt Groening named after who?\nPlan: I need to first need to Search[Milhouse] to find who it is named after with Lookup[named after]. Then I will collect the information to Finish[answer].\n\nQuestion: Were Pavel Urysohn and Leonid Levin known for the same type of work?\nPlan: I need to first Search[Pavel Urysohn] and then Search[Leonid Levin] to get more information. Then I will check their work type. If they are known for the same type of work, I will Finish[yes]. Otherwise I will Finish[no].\n\nQuestion: Which documentary is about Finnish rock groups, Adam Clayton Powell or The Saimaa Gesture?\nPlan: I need to Search[Adam Clayton Powell] and Search[The Saimaa Gesture] to collect their information. If I find the answer, I will Finish[Adam Clayton Powell] or Finish[The Saimaa Gesture]. If I cannot find the answer, I will Lookup[rock groups] in both results. \n\"\"\"\n\nPLANNER_EXAMPLE = \"\"\"Question: Musician and satirist Allie Goertz wrote a song about the \"The Simpsons\" character Milhouse, who Matt Groening named after who?\nPlan: I need to first need to Search[Milhouse] to find who it is named after with Lookup[named after]. Then I will collect the information to Finish[answer].\nAction 1: Search[Milhouse]\nObservation 1: Milhouse Mussolini Van Houten is a recurring character in the Fox animated television series The Simpsons voiced by Pamela Hayden and created by Matt Groening.\nAction 2: Lookup[named after]\nObservation 2: (Result 1 / 1) Milhouse was named after U.S. president Richard Nixon, whose middle name was Milhous. \nAction 3: Finish[Richard Nixon]\n\nQuestion: Were Pavel Urysohn and Leonid Levin known for the same type of work?\nPlan: I need to first Search[Pavel Urysohn] and then Search[Leonid Levin] to get more information. Then I will check their work type. If they are known for the same type of work, I will Finish[yes]. Otherwise I will Finish[no].\nAction 1: Search[Pavel Urysohn]\nObservation 1: Pavel Samuilovich Urysohn (February 3, 1898 – August 17, 1924) was a Soviet mathematician who is best known for his contributions in dimension theory.\nAction 2: Search[Leonid Levin]\nObservation 2: Leonid Anatolievich Levin is a Soviet-American mathematician and computer scientist. \nAction 3: Finish[yes]\n\"\"\"\n\nPLANNERREACT_EXAMPLE = \"\"\"Question: Musician and satirist Allie Goertz wrote a song about the \"The Simpsons\" character Milhouse, who Matt Groening named after who?\nPlan: I need to first need to Search[Milhouse] to find who it is named after with Lookup[named after]. Then I will collect the information to Finish[answer].\nThought 1: The question simplifies to \"The Simpsons\" character Milhouse is named after who. I only need to search Milhouse and find who it is named after.\nAction 1: Search[Milhouse]\nObservation 1: Milhouse Mussolini Van Houten is a recurring character in the Fox animated television series The Simpsons voiced by Pamela Hayden and created by Matt Groening.\nThought 2: The paragraph does not tell who Milhouse is named after, maybe I can look up \"named after\".\nAction 2: Lookup[named after]\nObservation 2: (Result 1 / 1) Milhouse was named after U.S. president Richard Nixon, whose middle name was Milhous. \nThought 3: Milhouse was named after U.S. president Richard Nixon, so the answer is Richard Nixon.\nAction 3: Finish[Richard Nixon]\n\nQuestion: Were Pavel Urysohn and Leonid Levin known for the same type of work?\nPlan: I need to first Search[Pavel Urysohn] and then Search[Leonid Levin] to get more information. Then I will check their work type. If they are known for the same type of work, I will Finish[yes]. Otherwise I will Finish[no].\nThought 1: I need to search Pavel Urysohn and Leonid Levin, find their types of work, then find if they are the same.\nAction 1: Search[Pavel Urysohn]\nObservation 1: Pavel Samuilovich Urysohn (February 3, 1898 – August 17, 1924) was a Soviet mathematician who is best known for his contributions in dimension theory.\nThought 2: Pavel Urysohn is a mathematician. I need to search Leonid Levin next and find its type of work.\nAction 2: Search[Leonid Levin]\nObservation 2: Leonid Anatolievich Levin is a Soviet-American mathematician and computer scientist. \nThought 3: Leonid Levin is a mathematician and computer scientist. So Pavel Urysohn and Leonid Levin have the same type of work. \nAction 3: Finish[yes]\n\"\"\"\n\nWEBTHINK_SIMPLE6 = \"\"\"Question: What is the elevation range for the area that the eastern sector of the Colorado orogeny extends into?\nThought 1: I need to search Colorado orogeny, find the area that the eastern sector of the Colorado orogeny extends into, then find the elevation range of the area.\nAction 1: Search[Colorado orogeny]\nObservation 1: The Colorado orogeny was an episode of mountain building (an orogeny) in Colorado and surrounding areas.\nThought 2: It does not mention the eastern sector. So I need to look up eastern sector.\nAction 2: Lookup[eastern sector]\nObservation 2: (Result 1 / 1) The eastern sector extends into the High Plains and is called the Central Plains orogeny.\nThought 3: The eastern sector of Colorado orogeny extends into the High Plains. So I need to search High Plains and find its elevation range.\nAction 3: Search[High Plains]\nObservation 3: High Plains refers to one of two distinct land regions:\nThought 4: I need to instead search High Plains (United States).\nAction 4: Search[High Plains (United States)]\nObservation 4: The High Plains are a subregion of the Great Plains. From east to west, the High Plains rise in elevation from around 1,800 to 7,000 ft (550 to 2,130 m).[3]\nThought 5: High Plains rise in elevation from around 1,800 to 7,000 ft, so the answer is 1,800 to 7,000 ft.\nAction 5: Finish[1,800 to 7,000 ft]\n\nQuestion: Musician and satirist Allie Goertz wrote a song about the \"The Simpsons\" character Milhouse, who Matt Groening named after who?\nThought 1: The question simplifies to \"The Simpsons\" character Milhouse is named after who. I only need to search Milhouse and find who it is named after.\nAction 1: Search[Milhouse]\nObservation 1: Milhouse Mussolini Van Houten is a recurring character in the Fox animated television series The Simpsons voiced by Pamela Hayden and created by Matt Groening.\nThought 2: The paragraph does not tell who Milhouse is named after, maybe I can look up \"named after\".\nAction 2: Lookup[named after]\nObservation 2: (Result 1 / 1) Milhouse was named after U.S. president Richard Nixon, whose middle name was Milhous. \nThought 3: Milhouse was named after U.S. president Richard Nixon, so the answer is Richard Nixon.\nAction 3: Finish[Richard Nixon]\n\nQuestion: Which documentary is about Finnish rock groups, Adam Clayton Powell or The Saimaa Gesture?\nThought 1: I need to search Adam Clayton Powell and The Saimaa Gesture, and find which documentary is about Finnish rock groups.\nAction 1: Search[Adam Clayton Powell]\nObservation 1: Could not find [Adam Clayton Powell]. Similar: ['Adam Clayton Powell III', 'Seventh Avenue (Manhattan)', 'Adam Clayton Powell Jr. State Office Building', 'Isabel Washington Powell', 'Adam Powell', 'Adam Clayton Powell (film)', 'Giancarlo Esposito'].\nThought 2: To find the documentary, I can search Adam Clayton Powell (film).\nAction 2: Search[Adam Clayton Powell (film)]\nObservation 2: Adam Clayton Powell is a 1989 American documentary film directed by Richard Kilberg.\nThe film is about the rise and fall of influential African-American politician Adam Clayton Powell Jr.[3][4] It was later aired as part of the PBS series The American Experience.\nThought 3: Adam Clayton Powell (film) is a documentary about an African-American politician, not Finnish rock groups. So the documentary about Finnish rock groups must instead be The Saimaa Gesture.\nAction 3: Finish[The Saimaa Gesture]\n\nQuestion: What profession does Nicholas Ray and Elia Kazan have in common?\nThought 1: I need to search Nicholas Ray and Elia Kazan, find their professions, then find the profession they have in common.\nAction 1: Search[Nicholas Ray]\nObservation 1: Nicholas Ray (born Raymond Nicholas Kienzle Jr., August 7, 1911 – June 16, 1979) was an American film director, screenwriter, and actor best known for the 1955 film Rebel Without a Cause.\nThought 2: Professions of Nicholas Ray are director, screenwriter, and actor. I need to search Elia Kazan next and find his professions.\nAction 2: Search[Elia Kazan]\nObservation 2: Elia Kazan was an American film and theatre director, producer, screenwriter and actor.\nThought 3: Professions of Elia Kazan are director, producer, screenwriter, and actor. So profession Nicholas Ray and Elia Kazan have in common is director, screenwriter, and actor.\nAction 3: Finish[director, screenwriter, actor]\n\nQuestion: Which magazine was started first Arthur's Magazine or First for Women?\nThought 1: I need to search Arthur's Magazine and First for Women, and find which was started first.\nAction 1: Search[Arthur's Magazine]\nObservation 1: Arthur's Magazine (1844-€“1846) was an American literary periodical published in Philadelphia in the 19th century. \nThought 2: Arthur's Magazine was started in 1844. I need to search First for Women next.\nAction 2: Search[First for Women]\nObservation 2: First for Women is a woman's magazine published by Bauer Media Group in the USA.[1] The magazine was started in 1989. \nThought 3: First for Women was started in 1989. 1844 (Arthur's Magazine) < 1989 (First for Women), so Arthur's Magazine was started first.\nAction 3: Finish[Arthur's Magazine]\n\nQuestion: Were Pavel Urysohn and Leonid Levin known for the same type of work?\nThought 1: I need to search Pavel Urysohn and Leonid Levin, find their types of work, then find if they are the same.\nAction 1: Search[Pavel Urysohn]\nObservation 1: Pavel Samuilovich Urysohn (February 3, 1898 – August 17, 1924) was a Soviet mathematician who is best known for his contributions in dimension theory.\nThought 2: Pavel Urysohn is a mathematician. I need to search Leonid Levin next and find its type of work.\nAction 2: Search[Leonid Levin]\nObservation 2: Leonid Anatolievich Levin is a Soviet-American mathematician and computer scientist. \nThought 3: Leonid Levin is a mathematician and computer scientist. So Pavel Urysohn and Leonid Levin have the same type of work. \nAction 3: Finish[yes]\"\"\"\n\nREFLECTIONS = \"\"\"\nPrevious Trial:\nQuestion: The Rome Protocols were signed by three Prime Ministers one of which was assassinated as part of what?\nThought 1: I need to search Rome Protocols, find the three Prime Ministers, then find what they were assassinated as part of.\nAction 1: Search[Rome Protocols]\nObservation 1: The Rome Protocols were a series of three international agreements concluded in Rome on 17 March 1934 between the governments of Austria, Hungary and Italy. They were signed by Italian Prime Minister Benito Mussolini, Austrian Chancellor Engelbert Dollfuss and Hungarian Prime Minister Gyula Gömbös. All of the protocols went into effect on 12 July 1934 and were registered in League of Nations Treaty Series on 12 December 1934.\nThought 2: The three Prime Ministers were Benito Mussolini, Engelbert Dollfuss, and Gyula Gömbös. I need to search Benito Mussolini and find what he was assassinated as part of.\nAction 2: Search[Benito Mussolini]\nObservation 2: Benito Amilcare Andrea Mussolini (UK: MU(U)SS-ə-LEE-nee, US: MOOSS-, Italian: [beˈniːto aˈmilkare anˈdrɛːa mussoˈliːni]; 29 July 1883 – 28 April 1945) was an Italian politician and journalist who founded and led the National Fascist Party (PNF). He was Prime Minister of Italy from the March on Rome in 1922 until his deposition in 1943, as well as \"Duce\" of Italian fascism from the establishment of the Italian Fasces of Combat in 1919 until his summary execution in 1945 by Italian partisans. As dictator of Italy and principal founder of fascism, Mussolini inspired and supported the international spread of fascist movements during the inter-war period.Mussolini was originally a socialist politician and a journalist at the Avanti! newspaper. In 1912, he became a member of the National Directorate of the Italian Socialist Party (PSI), but he was expelled from the PSI for advocating military intervention in World War I, in opposition to the party's stance on neutrality. In 1914, Mussolini founded a new journal, Il Popolo d'Italia, and served in the Royal Italian Army during the war until he was wounded and discharged in 1917. Mussolini denounced the PSI, his views now centering on Italian nationalism instead of socialism, and later founded the fascist movement which came to oppose egalitarianism and class conflict, instead advocating \"revolutionary nationalism\" transcending class lines. On 31 October 1922, following the March on Rome (28–30 October), Mussolini was appointed prime minister by King Victor Emmanuel III, becoming the youngest individual to hold the office up to that time. After removing all political opposition through his secret police and outlawing labor strikes, Mussolini and his followers consolidated power through a series of laws that transformed the nation into a one-party dictatorship. Within five years, Mussolini had established dictatorial authority by both legal and illegal means and aspired to create a totalitarian state. In 1929, Mussolini signed the Lateran Treaty with the Holy See to establish Vatican City.\nMussolini's foreign policy aimed to restore the ancient grandeur of the Roman Empire by expanding Italian colonial possessions and the fascist sphere of influence. In the 1920s, he ordered the Pacification of Libya, instructed the bombing of Corfu over an incident with Greece, established a protectorate over Albania, and incorporated the city of Fiume into the Italian state via agreements with Yugoslavia. In 1936, Ethiopia was conquered following the Second Italo-Ethiopian War and merged into Italian East Africa (AOI) with Eritrea and Somalia. In 1939, Italian forces annexed Albania. Between 1936 and 1939, Mussolini ordered the successful Italian military intervention in Spain in favor of Francisco Franco during the Spanish Civil War. Mussolini's Italy initially tried to avoid the outbreak of a second global war, sending troops at the Brenner Pass to delay Anschluss and taking part in the Stresa Front, the Lytton Report, the Treaty of Lausanne, the Four-Power Pact and the Munich Agreement. However, Italy then alienated itself from Britain and France by aligning with Germany and Japan. Germany invaded Poland on 1 September 1939, resulting in declarations of war by France and the UK and the start of World War II.\nOn 10 June 1940, Mussolini decided to enter the war on the Axis side. Despite initial success, the subsequent Axis collapse on multiple fronts and eventual Allied invasion of Sicily made Mussolini lose the support of the population and members of the Fascist Party. As a consequence, early on 25 July 1943, the Grand Council of Fascism passed a motion of no confidence in Mussolini; later that day King Victor Emmanuel III dismissed him as head of government and had him placed in custody, appointing Pietro Badoglio to succeed him as Prime Minister. After the king agreed to an armistice with the Allies, on 12 September 1943 Mussolini was rescued from captivity in the Gran Sasso raid by German paratroopers and Waffen-SS commandos led by Major Otto-Harald Mors. Adolf Hitler, after meeting with the rescued former dictator, then put Mussolini in charge of a puppet regime in northern Italy, the Italian Social Republic (Italian: Repubblica Sociale Italiana, RSI), informally known as the Salò Republic, causing a civil war. In late April 1945, in the wake of near total defeat, Mussolini and his mistress Clara Petacci attempted to flee to Switzerland, but both were captured by Italian communist partisans and summarily executed by firing squad on 28 April 1945 near Lake Como. The bodies of Mussolini and his mistress were then taken to Milan, where they were hung upside down at a service station to publicly confirm their demise.\nThought 3: Benito Mussolini was assassinated as part of the collapse of the Axis powers during World War II. So the Rome Protocols were signed by three Prime Ministers one of which was assassinated as part of World War II.\nAction 3: Finish[World War II]\n\nReflection: I searched one of the prime ministers involved in the signing, then attemted to answer right away. I should have searched each of the prime ministers, then looked up 'death' on each of their pages in order to get more information before answering.\n\nPrevious Trial:\nQuestion: Kam Heskin plays Paige Morgan in a 2004 film directed by who?\nThought 1: I need to search Kam Heskin and Paige Morgan, find the 2004 film they are in, then find the director of the film.\nAction 1: Search[Kam Heskin]\nObservation 1: Kam Erika Heskin (born May 8, 1973) is an American actress. She began her career playing Caitlin Deschanel on the NBC daytime soap opera Sunset Beach (1998–1999), before appearing in films Planet of the Apes (2001) and Catch Me If You Can (2002). Heskin went on in 2003 to play Elizabeth Bennet in an independent film Pride & Prejudice: A Latter-Day Comedy, Robin in Charmed (2004), and Paige Morgan in The Prince and Me film franchise (2006–2010).\nThought 2: Kam Heskin plays Paige Morgan in The Prince and Me film franchise. I need to search The Prince and Me film franchise and find the director of the 2004 film.\nAction 2: Search[The Prince and Me film franchise]\nObservation 2: Could not find [The Prince and Me film franchise]. Similar: ['Kam Heskin', 'Prince of Persia', 'Harry Potter and the Half-Blood Prince (film)', 'Prince of Persia: The Sands of Time (film)', 'The Chronicles of Narnia (film series)', 'Majestic Prince (franchise)', 'Kingsman (franchise)', 'The Little Prince (2015 film)', 'Shrek (franchise)', 'Harry Potter (film series)']\nThought 3: I need to search The Prince and Me (2004 film) instead.\nAction 3: Search[The Prince and Me (2004 film)]\nObservation 3: Could not find [The Prince and Me (2004 film)].\n# ... truncated ...","source_hash":"579a805ef628546cdec407356c2d8d7302322a601972dea9bfb362ce1ea45547","truncated":true} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.evaluate","uri":"program://BOLAA/module/hotpotqa_run.evaluate#L1-L71","kind":"module","name":"hotpotqa_run.evaluate","path":"hotpotqa_run/evaluate.py","language":"python","start_line":1,"end_line":71,"context_start_line":1,"context_end_line":71,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport json\nimport os\nimport re \nfrom collections import defaultdict\nimport pandas as pd\nimport hotpotqa_run.utils as utils\n\ndef eval_success(result_file) -> list:\n df = pd.read_csv(result_file)\n return df['success'].tolist()\n\ndef eval_reward(result_file) -> list:\n df = pd.read_csv(result_file)\n return df['reward'].tolist()\n\ndef eval_llm_agent(llm_name, agent_name):\n levels = ['easy','medium','hard']\n all_reward = []\n all_success = []\n for l in levels:\n file_name = f\"execution_data/hotpotqa/{l}_{agent_name}_{llm_name}.csv\"\n all_reward += eval_reward(file_name)\n all_success += eval_success(file_name)\n avg_reward = sum(all_reward)/len(all_reward)\n avg_success = sum(all_success)/len(all_success)\n return avg_reward, avg_success\n\ndef eval_llm_agent_level(llm_name, agent_name, level):\n file_name = f\"execution_data/hotpotqa/{level}_{agent_name}_{llm_name}.csv\"\n all_reward = eval_reward(file_name)\n all_success = eval_success(file_name)\n avg_reward = sum(all_reward)/len(all_reward)\n avg_success = sum(all_success)/len(all_success)\n return avg_reward, avg_success\n\ndef eval_sessions(llm_name, agent_name):\n levels = ['easy','medium','hard']\n all_reward = []\n all_success = []\n for l in levels:\n reward, success = eval_sessions_level((llm_name, agent_name,l))\n all_reward += reward\n all_success += success\n avg_reward = sum(all_reward)/len(all_reward)\n avg_success = sum(all_success)/len(all_success)\n return avg_reward, avg_success\n\ndef eval_sessions_level(llm_name, agent_name,level):\n file_name = f\"execution_data/hotpotqa/{level}_{agent_name}_{llm_name}.jsonl\"\n sessions = utils.get_all_agent_sessions(file_name)\n all_reward = [sess[\"reward\"] for sess in sessions]\n all_success = [sess[\"correct\"] for sess in sessions]\n avg_reward = sum(all_reward)/len(all_reward)\n avg_success = sum(all_success)/len(all_success)\n return avg_reward, avg_success\n\ndef get_reward_w_level(llm_name, agent_name):\n levels = ['easy','medium','hard']\n ret = []\n for l in levels:\n reward, _ = eval_sessions_level(llm_name, agent_name, l)\n ret.append(reward)\n return ret\n ","source_hash":"e857485617da3ecbc25db4fa9345a8692f777abcb0d4c14dccc729e8b5119d63","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.evaluate.eval_success","uri":"program://BOLAA/function/hotpotqa_run.evaluate.eval_success#L15-L17","kind":"function","name":"eval_success","path":"hotpotqa_run/evaluate.py","language":"python","start_line":15,"end_line":17,"context_start_line":1,"context_end_line":37,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport json\nimport os\nimport re \nfrom collections import defaultdict\nimport pandas as pd\nimport hotpotqa_run.utils as utils\n\ndef eval_success(result_file) -> list:\n df = pd.read_csv(result_file)\n return df['success'].tolist()\n\ndef eval_reward(result_file) -> list:\n df = pd.read_csv(result_file)\n return df['reward'].tolist()\n\ndef eval_llm_agent(llm_name, agent_name):\n levels = ['easy','medium','hard']\n all_reward = []\n all_success = []\n for l in levels:\n file_name = f\"execution_data/hotpotqa/{l}_{agent_name}_{llm_name}.csv\"\n all_reward += eval_reward(file_name)\n all_success += eval_success(file_name)\n avg_reward = sum(all_reward)/len(all_reward)\n avg_success = sum(all_success)/len(all_success)\n return avg_reward, avg_success\n\ndef eval_llm_agent_level(llm_name, agent_name, level):\n file_name = f\"execution_data/hotpotqa/{level}_{agent_name}_{llm_name}.csv\"\n all_reward = eval_reward(file_name)","source_hash":"e857485617da3ecbc25db4fa9345a8692f777abcb0d4c14dccc729e8b5119d63","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.evaluate.eval_reward","uri":"program://BOLAA/function/hotpotqa_run.evaluate.eval_reward#L19-L21","kind":"function","name":"eval_reward","path":"hotpotqa_run/evaluate.py","language":"python","start_line":19,"end_line":21,"context_start_line":1,"context_end_line":41,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport json\nimport os\nimport re \nfrom collections import defaultdict\nimport pandas as pd\nimport hotpotqa_run.utils as utils\n\ndef eval_success(result_file) -> list:\n df = pd.read_csv(result_file)\n return df['success'].tolist()\n\ndef eval_reward(result_file) -> list:\n df = pd.read_csv(result_file)\n return df['reward'].tolist()\n\ndef eval_llm_agent(llm_name, agent_name):\n levels = ['easy','medium','hard']\n all_reward = []\n all_success = []\n for l in levels:\n file_name = f\"execution_data/hotpotqa/{l}_{agent_name}_{llm_name}.csv\"\n all_reward += eval_reward(file_name)\n all_success += eval_success(file_name)\n avg_reward = sum(all_reward)/len(all_reward)\n avg_success = sum(all_success)/len(all_success)\n return avg_reward, avg_success\n\ndef eval_llm_agent_level(llm_name, agent_name, level):\n file_name = f\"execution_data/hotpotqa/{level}_{agent_name}_{llm_name}.csv\"\n all_reward = eval_reward(file_name)\n all_success = eval_success(file_name)\n avg_reward = sum(all_reward)/len(all_reward)\n avg_success = sum(all_success)/len(all_success)\n return avg_reward, avg_success","source_hash":"e857485617da3ecbc25db4fa9345a8692f777abcb0d4c14dccc729e8b5119d63","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.evaluate.eval_llm_agent","uri":"program://BOLAA/function/hotpotqa_run.evaluate.eval_llm_agent#L23-L33","kind":"function","name":"eval_llm_agent","path":"hotpotqa_run/evaluate.py","language":"python","start_line":23,"end_line":33,"context_start_line":3,"context_end_line":53,"code":" All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport json\nimport os\nimport re \nfrom collections import defaultdict\nimport pandas as pd\nimport hotpotqa_run.utils as utils\n\ndef eval_success(result_file) -> list:\n df = pd.read_csv(result_file)\n return df['success'].tolist()\n\ndef eval_reward(result_file) -> list:\n df = pd.read_csv(result_file)\n return df['reward'].tolist()\n\ndef eval_llm_agent(llm_name, agent_name):\n levels = ['easy','medium','hard']\n all_reward = []\n all_success = []\n for l in levels:\n file_name = f\"execution_data/hotpotqa/{l}_{agent_name}_{llm_name}.csv\"\n all_reward += eval_reward(file_name)\n all_success += eval_success(file_name)\n avg_reward = sum(all_reward)/len(all_reward)\n avg_success = sum(all_success)/len(all_success)\n return avg_reward, avg_success\n\ndef eval_llm_agent_level(llm_name, agent_name, level):\n file_name = f\"execution_data/hotpotqa/{level}_{agent_name}_{llm_name}.csv\"\n all_reward = eval_reward(file_name)\n all_success = eval_success(file_name)\n avg_reward = sum(all_reward)/len(all_reward)\n avg_success = sum(all_success)/len(all_success)\n return avg_reward, avg_success\n\ndef eval_sessions(llm_name, agent_name):\n levels = ['easy','medium','hard']\n all_reward = []\n all_success = []\n for l in levels:\n reward, success = eval_sessions_level((llm_name, agent_name,l))\n all_reward += reward\n all_success += success\n avg_reward = sum(all_reward)/len(all_reward)\n avg_success = sum(all_success)/len(all_success)\n return avg_reward, avg_success","source_hash":"e857485617da3ecbc25db4fa9345a8692f777abcb0d4c14dccc729e8b5119d63","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.evaluate.eval_llm_agent_level","uri":"program://BOLAA/function/hotpotqa_run.evaluate.eval_llm_agent_level#L35-L41","kind":"function","name":"eval_llm_agent_level","path":"hotpotqa_run/evaluate.py","language":"python","start_line":35,"end_line":41,"context_start_line":15,"context_end_line":61,"code":"def eval_success(result_file) -> list:\n df = pd.read_csv(result_file)\n return df['success'].tolist()\n\ndef eval_reward(result_file) -> list:\n df = pd.read_csv(result_file)\n return df['reward'].tolist()\n\ndef eval_llm_agent(llm_name, agent_name):\n levels = ['easy','medium','hard']\n all_reward = []\n all_success = []\n for l in levels:\n file_name = f\"execution_data/hotpotqa/{l}_{agent_name}_{llm_name}.csv\"\n all_reward += eval_reward(file_name)\n all_success += eval_success(file_name)\n avg_reward = sum(all_reward)/len(all_reward)\n avg_success = sum(all_success)/len(all_success)\n return avg_reward, avg_success\n\ndef eval_llm_agent_level(llm_name, agent_name, level):\n file_name = f\"execution_data/hotpotqa/{level}_{agent_name}_{llm_name}.csv\"\n all_reward = eval_reward(file_name)\n all_success = eval_success(file_name)\n avg_reward = sum(all_reward)/len(all_reward)\n avg_success = sum(all_success)/len(all_success)\n return avg_reward, avg_success\n\ndef eval_sessions(llm_name, agent_name):\n levels = ['easy','medium','hard']\n all_reward = []\n all_success = []\n for l in levels:\n reward, success = eval_sessions_level((llm_name, agent_name,l))\n all_reward += reward\n all_success += success\n avg_reward = sum(all_reward)/len(all_reward)\n avg_success = sum(all_success)/len(all_success)\n return avg_reward, avg_success\n\ndef eval_sessions_level(llm_name, agent_name,level):\n file_name = f\"execution_data/hotpotqa/{level}_{agent_name}_{llm_name}.jsonl\"\n sessions = utils.get_all_agent_sessions(file_name)\n all_reward = [sess[\"reward\"] for sess in sessions]\n all_success = [sess[\"correct\"] for sess in sessions]\n avg_reward = sum(all_reward)/len(all_reward)\n avg_success = sum(all_success)/len(all_success)","source_hash":"e857485617da3ecbc25db4fa9345a8692f777abcb0d4c14dccc729e8b5119d63","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.evaluate.eval_sessions","uri":"program://BOLAA/function/hotpotqa_run.evaluate.eval_sessions#L43-L53","kind":"function","name":"eval_sessions","path":"hotpotqa_run/evaluate.py","language":"python","start_line":43,"end_line":53,"context_start_line":23,"context_end_line":71,"code":"def eval_llm_agent(llm_name, agent_name):\n levels = ['easy','medium','hard']\n all_reward = []\n all_success = []\n for l in levels:\n file_name = f\"execution_data/hotpotqa/{l}_{agent_name}_{llm_name}.csv\"\n all_reward += eval_reward(file_name)\n all_success += eval_success(file_name)\n avg_reward = sum(all_reward)/len(all_reward)\n avg_success = sum(all_success)/len(all_success)\n return avg_reward, avg_success\n\ndef eval_llm_agent_level(llm_name, agent_name, level):\n file_name = f\"execution_data/hotpotqa/{level}_{agent_name}_{llm_name}.csv\"\n all_reward = eval_reward(file_name)\n all_success = eval_success(file_name)\n avg_reward = sum(all_reward)/len(all_reward)\n avg_success = sum(all_success)/len(all_success)\n return avg_reward, avg_success\n\ndef eval_sessions(llm_name, agent_name):\n levels = ['easy','medium','hard']\n all_reward = []\n all_success = []\n for l in levels:\n reward, success = eval_sessions_level((llm_name, agent_name,l))\n all_reward += reward\n all_success += success\n avg_reward = sum(all_reward)/len(all_reward)\n avg_success = sum(all_success)/len(all_success)\n return avg_reward, avg_success\n\ndef eval_sessions_level(llm_name, agent_name,level):\n file_name = f\"execution_data/hotpotqa/{level}_{agent_name}_{llm_name}.jsonl\"\n sessions = utils.get_all_agent_sessions(file_name)\n all_reward = [sess[\"reward\"] for sess in sessions]\n all_success = [sess[\"correct\"] for sess in sessions]\n avg_reward = sum(all_reward)/len(all_reward)\n avg_success = sum(all_success)/len(all_success)\n return avg_reward, avg_success\n\ndef get_reward_w_level(llm_name, agent_name):\n levels = ['easy','medium','hard']\n ret = []\n for l in levels:\n reward, _ = eval_sessions_level(llm_name, agent_name, l)\n ret.append(reward)\n return ret\n ","source_hash":"e857485617da3ecbc25db4fa9345a8692f777abcb0d4c14dccc729e8b5119d63","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.evaluate.eval_sessions_level","uri":"program://BOLAA/function/hotpotqa_run.evaluate.eval_sessions_level#L55-L62","kind":"function","name":"eval_sessions_level","path":"hotpotqa_run/evaluate.py","language":"python","start_line":55,"end_line":62,"context_start_line":35,"context_end_line":71,"code":"def eval_llm_agent_level(llm_name, agent_name, level):\n file_name = f\"execution_data/hotpotqa/{level}_{agent_name}_{llm_name}.csv\"\n all_reward = eval_reward(file_name)\n all_success = eval_success(file_name)\n avg_reward = sum(all_reward)/len(all_reward)\n avg_success = sum(all_success)/len(all_success)\n return avg_reward, avg_success\n\ndef eval_sessions(llm_name, agent_name):\n levels = ['easy','medium','hard']\n all_reward = []\n all_success = []\n for l in levels:\n reward, success = eval_sessions_level((llm_name, agent_name,l))\n all_reward += reward\n all_success += success\n avg_reward = sum(all_reward)/len(all_reward)\n avg_success = sum(all_success)/len(all_success)\n return avg_reward, avg_success\n\ndef eval_sessions_level(llm_name, agent_name,level):\n file_name = f\"execution_data/hotpotqa/{level}_{agent_name}_{llm_name}.jsonl\"\n sessions = utils.get_all_agent_sessions(file_name)\n all_reward = [sess[\"reward\"] for sess in sessions]\n all_success = [sess[\"correct\"] for sess in sessions]\n avg_reward = sum(all_reward)/len(all_reward)\n avg_success = sum(all_success)/len(all_success)\n return avg_reward, avg_success\n\ndef get_reward_w_level(llm_name, agent_name):\n levels = ['easy','medium','hard']\n ret = []\n for l in levels:\n reward, _ = eval_sessions_level(llm_name, agent_name, l)\n ret.append(reward)\n return ret\n ","source_hash":"e857485617da3ecbc25db4fa9345a8692f777abcb0d4c14dccc729e8b5119d63","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.evaluate.get_reward_w_level","uri":"program://BOLAA/function/hotpotqa_run.evaluate.get_reward_w_level#L64-L70","kind":"function","name":"get_reward_w_level","path":"hotpotqa_run/evaluate.py","language":"python","start_line":64,"end_line":70,"context_start_line":44,"context_end_line":71,"code":" levels = ['easy','medium','hard']\n all_reward = []\n all_success = []\n for l in levels:\n reward, success = eval_sessions_level((llm_name, agent_name,l))\n all_reward += reward\n all_success += success\n avg_reward = sum(all_reward)/len(all_reward)\n avg_success = sum(all_success)/len(all_success)\n return avg_reward, avg_success\n\ndef eval_sessions_level(llm_name, agent_name,level):\n file_name = f\"execution_data/hotpotqa/{level}_{agent_name}_{llm_name}.jsonl\"\n sessions = utils.get_all_agent_sessions(file_name)\n all_reward = [sess[\"reward\"] for sess in sessions]\n all_success = [sess[\"correct\"] for sess in sessions]\n avg_reward = sum(all_reward)/len(all_reward)\n avg_success = sum(all_success)/len(all_success)\n return avg_reward, avg_success\n\ndef get_reward_w_level(llm_name, agent_name):\n levels = ['easy','medium','hard']\n ret = []\n for l in levels:\n reward, _ = eval_sessions_level(llm_name, agent_name, l)\n ret.append(reward)\n return ret\n ","source_hash":"e857485617da3ecbc25db4fa9345a8692f777abcb0d4c14dccc729e8b5119d63","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.llms","uri":"program://BOLAA/module/hotpotqa_run.llms#L1-L80","kind":"module","name":"hotpotqa_run.llms","path":"hotpotqa_run/llms.py","language":"python","start_line":1,"end_line":80,"context_start_line":1,"context_end_line":80,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport os\nimport sys\nimport json\nimport random\nimport tiktoken\ntoken_enc = tiktoken.get_encoding(\"cl100k_base\")\nimport openai\nfrom langchain import PromptTemplate, OpenAI, LLMChain\nfrom transformers import AutoTokenizer, AutoModelForCausalLM\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.chains import LLMChain\nfrom langchain import PromptTemplate\nfrom langchain.prompts.chat import (\n ChatPromptTemplate,\n SystemMessagePromptTemplate,\n AIMessagePromptTemplate,\n HumanMessagePromptTemplate,\n)\nfrom web_run.config import OPENAI_API_KEY\n\nOPENAI_CHAT_MODELS = [\"gpt-3.5-turbo\",\"gpt-3.5-turbo-16k-0613\",\"gpt-3.5-turbo-16k\",\"gpt-4-0613\",\"gpt-4-32k-0613\"]\nOPENAI_LLM_MODELS = [\"text-davinci-003\",\"text-ada-001\"]\nFASTCHAT_MODELS = [\"vicuna-7b\"]\n\n \nclass langchain_openai_chatllm:\n def __init__(self, llm_name):\n openai.api_key = OPENAI_API_KEY\n self.llm_name = llm_name\n human_template=\"{prompt}\"\n human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)\n self.chat_prompt = ChatPromptTemplate.from_messages([human_message_prompt])\n \n def run(self, prompt, temperature=1, stop=['\\n'], max_tokens=128):\n chat = ChatOpenAI(model=self.llm_name, temperature=temperature, stop=stop, max_tokens=max_tokens)\n self.chain = LLMChain(llm=chat, prompt=self.chat_prompt)\n return self.chain.run(prompt)\n \nclass langchain_openai_llm:\n def __init__(self, llm_name):\n openai.api_key = OPENAI_API_KEY\n self.prompt_temp = PromptTemplate(\n input_variables=[\"prompt\"], template=\"{prompt}\"\n )\n self.llm_name = llm_name\n \n def run(self, prompt, temperature=0.9, stop=['\\n'], max_tokens=128):\n llm = OpenAI(model=self.llm_name, temperature=temperature, stop=['\\n'], max_tokens=max_tokens)\n chain = LLMChain(llm=llm, prompt=self.prompt_temp)\n return chain.run(prompt)\n\n\nclass langchain_fastchat_llm:\n def __init__(self, llm_name):\n openai.api_key = \"EMPTY\" # Not support yet\n openai.api_base = \"http://localhost:8000/v1\"\n self.prompt_temp = PromptTemplate(\n input_variables=[\"prompt\"], template=\"{prompt}\"\n )\n self.llm_name = llm_name\n \n def run(self, prompt, temperature=0.9, stop=['\\n'], max_tokens=128):\n llm = OpenAI(model=self.llm_name, temperature=temperature, stop=['\\n'], max_tokens=max_tokens)\n chain = LLMChain(llm=llm, prompt=self.prompt_temp)\n return chain.run(prompt)\n\ndef get_llm_backend(llm_name):\n if llm_name in OPENAI_CHAT_MODELS:\n return langchain_openai_chatllm(llm_name)\n elif llm_name in OPENAI_LLM_MODELS:\n return langchain_openai_llm(llm_name)\n else:\n return langchain_fastchat_llm(llm_name)","source_hash":"e8dadcd5c975227c22060fdc5519cc6907b63536aec6f5814eafb56dd95eef88","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.llms.langchain_openai_chatllm","uri":"program://BOLAA/class/hotpotqa_run.llms.langchain_openai_chatllm#L33-L44","kind":"class","name":"langchain_openai_chatllm","path":"hotpotqa_run/llms.py","language":"python","start_line":33,"end_line":44,"context_start_line":13,"context_end_line":64,"code":"token_enc = tiktoken.get_encoding(\"cl100k_base\")\nimport openai\nfrom langchain import PromptTemplate, OpenAI, LLMChain\nfrom transformers import AutoTokenizer, AutoModelForCausalLM\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.chains import LLMChain\nfrom langchain import PromptTemplate\nfrom langchain.prompts.chat import (\n ChatPromptTemplate,\n SystemMessagePromptTemplate,\n AIMessagePromptTemplate,\n HumanMessagePromptTemplate,\n)\nfrom web_run.config import OPENAI_API_KEY\n\nOPENAI_CHAT_MODELS = [\"gpt-3.5-turbo\",\"gpt-3.5-turbo-16k-0613\",\"gpt-3.5-turbo-16k\",\"gpt-4-0613\",\"gpt-4-32k-0613\"]\nOPENAI_LLM_MODELS = [\"text-davinci-003\",\"text-ada-001\"]\nFASTCHAT_MODELS = [\"vicuna-7b\"]\n\n \nclass langchain_openai_chatllm:\n def __init__(self, llm_name):\n openai.api_key = OPENAI_API_KEY\n self.llm_name = llm_name\n human_template=\"{prompt}\"\n human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)\n self.chat_prompt = ChatPromptTemplate.from_messages([human_message_prompt])\n \n def run(self, prompt, temperature=1, stop=['\\n'], max_tokens=128):\n chat = ChatOpenAI(model=self.llm_name, temperature=temperature, stop=stop, max_tokens=max_tokens)\n self.chain = LLMChain(llm=chat, prompt=self.chat_prompt)\n return self.chain.run(prompt)\n \nclass langchain_openai_llm:\n def __init__(self, llm_name):\n openai.api_key = OPENAI_API_KEY\n self.prompt_temp = PromptTemplate(\n input_variables=[\"prompt\"], template=\"{prompt}\"\n )\n self.llm_name = llm_name\n \n def run(self, prompt, temperature=0.9, stop=['\\n'], max_tokens=128):\n llm = OpenAI(model=self.llm_name, temperature=temperature, stop=['\\n'], max_tokens=max_tokens)\n chain = LLMChain(llm=llm, prompt=self.prompt_temp)\n return chain.run(prompt)\n\n\nclass langchain_fastchat_llm:\n def __init__(self, llm_name):\n openai.api_key = \"EMPTY\" # Not support yet\n openai.api_base = \"http://localhost:8000/v1\"\n self.prompt_temp = PromptTemplate(","source_hash":"e8dadcd5c975227c22060fdc5519cc6907b63536aec6f5814eafb56dd95eef88","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.llms.langchain_openai_llm","uri":"program://BOLAA/class/hotpotqa_run.llms.langchain_openai_llm#L46-L57","kind":"class","name":"langchain_openai_llm","path":"hotpotqa_run/llms.py","language":"python","start_line":46,"end_line":57,"context_start_line":26,"context_end_line":77,"code":"from web_run.config import OPENAI_API_KEY\n\nOPENAI_CHAT_MODELS = [\"gpt-3.5-turbo\",\"gpt-3.5-turbo-16k-0613\",\"gpt-3.5-turbo-16k\",\"gpt-4-0613\",\"gpt-4-32k-0613\"]\nOPENAI_LLM_MODELS = [\"text-davinci-003\",\"text-ada-001\"]\nFASTCHAT_MODELS = [\"vicuna-7b\"]\n\n \nclass langchain_openai_chatllm:\n def __init__(self, llm_name):\n openai.api_key = OPENAI_API_KEY\n self.llm_name = llm_name\n human_template=\"{prompt}\"\n human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)\n self.chat_prompt = ChatPromptTemplate.from_messages([human_message_prompt])\n \n def run(self, prompt, temperature=1, stop=['\\n'], max_tokens=128):\n chat = ChatOpenAI(model=self.llm_name, temperature=temperature, stop=stop, max_tokens=max_tokens)\n self.chain = LLMChain(llm=chat, prompt=self.chat_prompt)\n return self.chain.run(prompt)\n \nclass langchain_openai_llm:\n def __init__(self, llm_name):\n openai.api_key = OPENAI_API_KEY\n self.prompt_temp = PromptTemplate(\n input_variables=[\"prompt\"], template=\"{prompt}\"\n )\n self.llm_name = llm_name\n \n def run(self, prompt, temperature=0.9, stop=['\\n'], max_tokens=128):\n llm = OpenAI(model=self.llm_name, temperature=temperature, stop=['\\n'], max_tokens=max_tokens)\n chain = LLMChain(llm=llm, prompt=self.prompt_temp)\n return chain.run(prompt)\n\n\nclass langchain_fastchat_llm:\n def __init__(self, llm_name):\n openai.api_key = \"EMPTY\" # Not support yet\n openai.api_base = \"http://localhost:8000/v1\"\n self.prompt_temp = PromptTemplate(\n input_variables=[\"prompt\"], template=\"{prompt}\"\n )\n self.llm_name = llm_name\n \n def run(self, prompt, temperature=0.9, stop=['\\n'], max_tokens=128):\n llm = OpenAI(model=self.llm_name, temperature=temperature, stop=['\\n'], max_tokens=max_tokens)\n chain = LLMChain(llm=llm, prompt=self.prompt_temp)\n return chain.run(prompt)\n\ndef get_llm_backend(llm_name):\n if llm_name in OPENAI_CHAT_MODELS:\n return langchain_openai_chatllm(llm_name)\n elif llm_name in OPENAI_LLM_MODELS:","source_hash":"e8dadcd5c975227c22060fdc5519cc6907b63536aec6f5814eafb56dd95eef88","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.llms.langchain_fastchat_llm","uri":"program://BOLAA/class/hotpotqa_run.llms.langchain_fastchat_llm#L60-L72","kind":"class","name":"langchain_fastchat_llm","path":"hotpotqa_run/llms.py","language":"python","start_line":60,"end_line":72,"context_start_line":40,"context_end_line":80,"code":" \n def run(self, prompt, temperature=1, stop=['\\n'], max_tokens=128):\n chat = ChatOpenAI(model=self.llm_name, temperature=temperature, stop=stop, max_tokens=max_tokens)\n self.chain = LLMChain(llm=chat, prompt=self.chat_prompt)\n return self.chain.run(prompt)\n \nclass langchain_openai_llm:\n def __init__(self, llm_name):\n openai.api_key = OPENAI_API_KEY\n self.prompt_temp = PromptTemplate(\n input_variables=[\"prompt\"], template=\"{prompt}\"\n )\n self.llm_name = llm_name\n \n def run(self, prompt, temperature=0.9, stop=['\\n'], max_tokens=128):\n llm = OpenAI(model=self.llm_name, temperature=temperature, stop=['\\n'], max_tokens=max_tokens)\n chain = LLMChain(llm=llm, prompt=self.prompt_temp)\n return chain.run(prompt)\n\n\nclass langchain_fastchat_llm:\n def __init__(self, llm_name):\n openai.api_key = \"EMPTY\" # Not support yet\n openai.api_base = \"http://localhost:8000/v1\"\n self.prompt_temp = PromptTemplate(\n input_variables=[\"prompt\"], template=\"{prompt}\"\n )\n self.llm_name = llm_name\n \n def run(self, prompt, temperature=0.9, stop=['\\n'], max_tokens=128):\n llm = OpenAI(model=self.llm_name, temperature=temperature, stop=['\\n'], max_tokens=max_tokens)\n chain = LLMChain(llm=llm, prompt=self.prompt_temp)\n return chain.run(prompt)\n\ndef get_llm_backend(llm_name):\n if llm_name in OPENAI_CHAT_MODELS:\n return langchain_openai_chatllm(llm_name)\n elif llm_name in OPENAI_LLM_MODELS:\n return langchain_openai_llm(llm_name)\n else:\n return langchain_fastchat_llm(llm_name)","source_hash":"e8dadcd5c975227c22060fdc5519cc6907b63536aec6f5814eafb56dd95eef88","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.llms.get_llm_backend","uri":"program://BOLAA/function/hotpotqa_run.llms.get_llm_backend#L74-L80","kind":"function","name":"get_llm_backend","path":"hotpotqa_run/llms.py","language":"python","start_line":74,"end_line":80,"context_start_line":54,"context_end_line":80,"code":" def run(self, prompt, temperature=0.9, stop=['\\n'], max_tokens=128):\n llm = OpenAI(model=self.llm_name, temperature=temperature, stop=['\\n'], max_tokens=max_tokens)\n chain = LLMChain(llm=llm, prompt=self.prompt_temp)\n return chain.run(prompt)\n\n\nclass langchain_fastchat_llm:\n def __init__(self, llm_name):\n openai.api_key = \"EMPTY\" # Not support yet\n openai.api_base = \"http://localhost:8000/v1\"\n self.prompt_temp = PromptTemplate(\n input_variables=[\"prompt\"], template=\"{prompt}\"\n )\n self.llm_name = llm_name\n \n def run(self, prompt, temperature=0.9, stop=['\\n'], max_tokens=128):\n llm = OpenAI(model=self.llm_name, temperature=temperature, stop=['\\n'], max_tokens=max_tokens)\n chain = LLMChain(llm=llm, prompt=self.prompt_temp)\n return chain.run(prompt)\n\ndef get_llm_backend(llm_name):\n if llm_name in OPENAI_CHAT_MODELS:\n return langchain_openai_chatllm(llm_name)\n elif llm_name in OPENAI_LLM_MODELS:\n return langchain_openai_llm(llm_name)\n else:\n return langchain_fastchat_llm(llm_name)","source_hash":"e8dadcd5c975227c22060fdc5519cc6907b63536aec6f5814eafb56dd95eef88","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.llms.__init__","uri":"program://BOLAA/function/hotpotqa_run.llms.__init__#L61-L67","kind":"function","name":"__init__","path":"hotpotqa_run/llms.py","language":"python","start_line":61,"end_line":67,"context_start_line":41,"context_end_line":80,"code":" def run(self, prompt, temperature=1, stop=['\\n'], max_tokens=128):\n chat = ChatOpenAI(model=self.llm_name, temperature=temperature, stop=stop, max_tokens=max_tokens)\n self.chain = LLMChain(llm=chat, prompt=self.chat_prompt)\n return self.chain.run(prompt)\n \nclass langchain_openai_llm:\n def __init__(self, llm_name):\n openai.api_key = OPENAI_API_KEY\n self.prompt_temp = PromptTemplate(\n input_variables=[\"prompt\"], template=\"{prompt}\"\n )\n self.llm_name = llm_name\n \n def run(self, prompt, temperature=0.9, stop=['\\n'], max_tokens=128):\n llm = OpenAI(model=self.llm_name, temperature=temperature, stop=['\\n'], max_tokens=max_tokens)\n chain = LLMChain(llm=llm, prompt=self.prompt_temp)\n return chain.run(prompt)\n\n\nclass langchain_fastchat_llm:\n def __init__(self, llm_name):\n openai.api_key = \"EMPTY\" # Not support yet\n openai.api_base = \"http://localhost:8000/v1\"\n self.prompt_temp = PromptTemplate(\n input_variables=[\"prompt\"], template=\"{prompt}\"\n )\n self.llm_name = llm_name\n \n def run(self, prompt, temperature=0.9, stop=['\\n'], max_tokens=128):\n llm = OpenAI(model=self.llm_name, temperature=temperature, stop=['\\n'], max_tokens=max_tokens)\n chain = LLMChain(llm=llm, prompt=self.prompt_temp)\n return chain.run(prompt)\n\ndef get_llm_backend(llm_name):\n if llm_name in OPENAI_CHAT_MODELS:\n return langchain_openai_chatllm(llm_name)\n elif llm_name in OPENAI_LLM_MODELS:\n return langchain_openai_llm(llm_name)\n else:\n return langchain_fastchat_llm(llm_name)","source_hash":"e8dadcd5c975227c22060fdc5519cc6907b63536aec6f5814eafb56dd95eef88","truncated":false} {"repo_id":"BOLAA","entity_id":"py:hotpotqa_run.llms.run","uri":"program://BOLAA/function/hotpotqa_run.llms.run#L69-L72","kind":"function","name":"run","path":"hotpotqa_run/llms.py","language":"python","start_line":69,"end_line":72,"context_start_line":49,"context_end_line":80,"code":" self.prompt_temp = PromptTemplate(\n input_variables=[\"prompt\"], template=\"{prompt}\"\n )\n self.llm_name = llm_name\n \n def run(self, prompt, temperature=0.9, stop=['\\n'], max_tokens=128):\n llm = OpenAI(model=self.llm_name, temperature=temperature, stop=['\\n'], max_tokens=max_tokens)\n chain = LLMChain(llm=llm, prompt=self.prompt_temp)\n return chain.run(prompt)\n\n\nclass langchain_fastchat_llm:\n def __init__(self, llm_name):\n openai.api_key = \"EMPTY\" # Not support yet\n openai.api_base = \"http://localhost:8000/v1\"\n self.prompt_temp = PromptTemplate(\n input_variables=[\"prompt\"], template=\"{prompt}\"\n )\n self.llm_name = llm_name\n \n def run(self, prompt, temperature=0.9, stop=['\\n'], max_tokens=128):\n llm = OpenAI(model=self.llm_name, temperature=temperature, stop=['\\n'], max_tokens=max_tokens)\n chain = LLMChain(llm=llm, prompt=self.prompt_temp)\n return chain.run(prompt)\n\ndef get_llm_backend(llm_name):\n if llm_name in OPENAI_CHAT_MODELS:\n return langchain_openai_chatllm(llm_name)\n elif llm_name in OPENAI_LLM_MODELS:\n return langchain_openai_llm(llm_name)\n else:\n return langchain_fastchat_llm(llm_name)","source_hash":"e8dadcd5c975227c22060fdc5519cc6907b63536aec6f5814eafb56dd95eef88","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.test","uri":"program://BOLAA/module/webshop.test#L1-L13","kind":"module","name":"webshop.test","path":"webshop/test.py","language":"python","start_line":1,"end_line":13,"context_start_line":1,"context_end_line":13,"code":"import re \ndef idx_parser(text):\n pattern = r\"\\d\\s\\w*\" # Matches a word boundary, followed by a digit, and then any word characters\n\n match = re.search(pattern, text)\n if match:\n return int(match.group(0))\n else:\n return None\n \ntext = \"5\\n\\nAction: Buy Now\"\nidx = idx_parser(text)\nprint(idx)","source_hash":"ba979dead6cc1961eaa058c989dc89ba4c931ac62050f3c82434e6c50d93f394","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.test.idx_parser","uri":"program://BOLAA/function/webshop.test.idx_parser#L2-L9","kind":"function","name":"idx_parser","path":"webshop/test.py","language":"python","start_line":2,"end_line":9,"context_start_line":1,"context_end_line":13,"code":"import re \ndef idx_parser(text):\n pattern = r\"\\d\\s\\w*\" # Matches a word boundary, followed by a digit, and then any word characters\n\n match = re.search(pattern, text)\n if match:\n return int(match.group(0))\n else:\n return None\n \ntext = \"5\\n\\nAction: Buy Now\"\nidx = idx_parser(text)\nprint(idx)","source_hash":"ba979dead6cc1961eaa058c989dc89ba4c931ac62050f3c82434e6c50d93f394","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.tests.web-agent-site.test_utils","uri":"program://BOLAA/module/webshop.tests.web-agent-site.test_utils#L1-L49","kind":"module","name":"webshop.tests.web-agent-site.test_utils","path":"webshop/tests/web-agent-site/test_utils.py","language":"python","start_line":1,"end_line":49,"context_start_line":1,"context_end_line":49,"code":"import logging\nimport pytest\nimport random\nimport shutil\nfrom pathlib import Path\nfrom web_agent_site.utils import *\n\ndef test_random_idx():\n random.seed(24)\n weights = [random.randint(0, 10) for _ in range(0, 50)]\n cml_weights = [0]\n for w in weights:\n cml_weights.append(cml_weights[-1] + w)\n idx_1, expected_1 = random_idx(cml_weights), 44\n idx_2, expected_2 = random_idx(cml_weights), 15\n idx_3, expected_3 = random_idx(cml_weights), 36\n assert idx_1 == expected_1\n assert idx_2 == expected_2\n assert idx_3 == expected_3\n\ndef test_setup_logger():\n LOG_DIR = 'user_session_logs_test/'\n user_log_dir = Path(LOG_DIR)\n user_log_dir.mkdir(parents=True, exist_ok=True)\n session_id = \"ABC\"\n\n logger = setup_logger(session_id, user_log_dir)\n log_file = Path(LOG_DIR + \"/\" + session_id + \".jsonl\")\n assert Path(log_file).is_file()\n assert logger.level == logging.INFO\n\n content = \"Hello there\"\n logger.info(content)\n assert log_file.read_text().strip(\"\\n\") == content\n\n shutil.rmtree(LOG_DIR)\n\ndef test_generate_mturk_code():\n suite = [\n ('', 'DA39A3EE5E'),\n ('ABC', '3C01BDBB26'),\n ('123', '40BD001563'),\n ('1A1', '10E7DB0A44'),\n ('$%^ABC', '5D5607D24E')\n ]\n for session_id, expected in suite:\n output = generate_mturk_code(session_id)\n assert type(expected) is str\n assert output == expected","source_hash":"67a6212e65db7a6a13a9d284d1468cdd28458582664d9af94ec3c5a5443449d5","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.tests.web-agent-site.test_utils.test_random_idx","uri":"program://BOLAA/function/webshop.tests.web-agent-site.test_utils.test_random_idx#L8-L19","kind":"function","name":"test_random_idx","path":"webshop/tests/web-agent-site/test_utils.py","language":"python","start_line":8,"end_line":19,"context_start_line":1,"context_end_line":39,"code":"import logging\nimport pytest\nimport random\nimport shutil\nfrom pathlib import Path\nfrom web_agent_site.utils import *\n\ndef test_random_idx():\n random.seed(24)\n weights = [random.randint(0, 10) for _ in range(0, 50)]\n cml_weights = [0]\n for w in weights:\n cml_weights.append(cml_weights[-1] + w)\n idx_1, expected_1 = random_idx(cml_weights), 44\n idx_2, expected_2 = random_idx(cml_weights), 15\n idx_3, expected_3 = random_idx(cml_weights), 36\n assert idx_1 == expected_1\n assert idx_2 == expected_2\n assert idx_3 == expected_3\n\ndef test_setup_logger():\n LOG_DIR = 'user_session_logs_test/'\n user_log_dir = Path(LOG_DIR)\n user_log_dir.mkdir(parents=True, exist_ok=True)\n session_id = \"ABC\"\n\n logger = setup_logger(session_id, user_log_dir)\n log_file = Path(LOG_DIR + \"/\" + session_id + \".jsonl\")\n assert Path(log_file).is_file()\n assert logger.level == logging.INFO\n\n content = \"Hello there\"\n logger.info(content)\n assert log_file.read_text().strip(\"\\n\") == content\n\n shutil.rmtree(LOG_DIR)\n\ndef test_generate_mturk_code():\n suite = [","source_hash":"67a6212e65db7a6a13a9d284d1468cdd28458582664d9af94ec3c5a5443449d5","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.tests.web-agent-site.test_utils.test_setup_logger","uri":"program://BOLAA/function/webshop.tests.web-agent-site.test_utils.test_setup_logger#L21-L36","kind":"function","name":"test_setup_logger","path":"webshop/tests/web-agent-site/test_utils.py","language":"python","start_line":21,"end_line":36,"context_start_line":1,"context_end_line":49,"code":"import logging\nimport pytest\nimport random\nimport shutil\nfrom pathlib import Path\nfrom web_agent_site.utils import *\n\ndef test_random_idx():\n random.seed(24)\n weights = [random.randint(0, 10) for _ in range(0, 50)]\n cml_weights = [0]\n for w in weights:\n cml_weights.append(cml_weights[-1] + w)\n idx_1, expected_1 = random_idx(cml_weights), 44\n idx_2, expected_2 = random_idx(cml_weights), 15\n idx_3, expected_3 = random_idx(cml_weights), 36\n assert idx_1 == expected_1\n assert idx_2 == expected_2\n assert idx_3 == expected_3\n\ndef test_setup_logger():\n LOG_DIR = 'user_session_logs_test/'\n user_log_dir = Path(LOG_DIR)\n user_log_dir.mkdir(parents=True, exist_ok=True)\n session_id = \"ABC\"\n\n logger = setup_logger(session_id, user_log_dir)\n log_file = Path(LOG_DIR + \"/\" + session_id + \".jsonl\")\n assert Path(log_file).is_file()\n assert logger.level == logging.INFO\n\n content = \"Hello there\"\n logger.info(content)\n assert log_file.read_text().strip(\"\\n\") == content\n\n shutil.rmtree(LOG_DIR)\n\ndef test_generate_mturk_code():\n suite = [\n ('', 'DA39A3EE5E'),\n ('ABC', '3C01BDBB26'),\n ('123', '40BD001563'),\n ('1A1', '10E7DB0A44'),\n ('$%^ABC', '5D5607D24E')\n ]\n for session_id, expected in suite:\n output = generate_mturk_code(session_id)\n assert type(expected) is str\n assert output == expected","source_hash":"67a6212e65db7a6a13a9d284d1468cdd28458582664d9af94ec3c5a5443449d5","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.tests.web-agent-site.test_utils.test_generate_mturk_code","uri":"program://BOLAA/function/webshop.tests.web-agent-site.test_utils.test_generate_mturk_code#L38-L49","kind":"function","name":"test_generate_mturk_code","path":"webshop/tests/web-agent-site/test_utils.py","language":"python","start_line":38,"end_line":49,"context_start_line":18,"context_end_line":49,"code":" assert idx_2 == expected_2\n assert idx_3 == expected_3\n\ndef test_setup_logger():\n LOG_DIR = 'user_session_logs_test/'\n user_log_dir = Path(LOG_DIR)\n user_log_dir.mkdir(parents=True, exist_ok=True)\n session_id = \"ABC\"\n\n logger = setup_logger(session_id, user_log_dir)\n log_file = Path(LOG_DIR + \"/\" + session_id + \".jsonl\")\n assert Path(log_file).is_file()\n assert logger.level == logging.INFO\n\n content = \"Hello there\"\n logger.info(content)\n assert log_file.read_text().strip(\"\\n\") == content\n\n shutil.rmtree(LOG_DIR)\n\ndef test_generate_mturk_code():\n suite = [\n ('', 'DA39A3EE5E'),\n ('ABC', '3C01BDBB26'),\n ('123', '40BD001563'),\n ('1A1', '10E7DB0A44'),\n ('$%^ABC', '5D5607D24E')\n ]\n for session_id, expected in suite:\n output = generate_mturk_code(session_id)\n assert type(expected) is str\n assert output == expected","source_hash":"67a6212e65db7a6a13a9d284d1468cdd28458582664d9af94ec3c5a5443449d5","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.tests.web-agent-site.engine.test_goal","uri":"program://BOLAA/module/webshop.tests.web-agent-site.engine.test_goal#L1-L200","kind":"module","name":"webshop.tests.web-agent-site.engine.test_goal","path":"webshop/tests/web-agent-site/engine/test_goal.py","language":"python","start_line":1,"end_line":200,"context_start_line":1,"context_end_line":200,"code":"import pytest\nfrom math import isclose\nfrom web_agent_site.engine.goal import *\n\ndef test_get_type_reward():\n # Exact Match\n goal = {\n 'query': \"Query 1\",\n 'product_category': \"a › b › c\",\n 'name': \"Name 1\"\n }\n purchased = {\n 'query': \"Query 1\",\n 'product_category': \"a › b › c\",\n 'name': \"Name 1\"\n }\n result = get_type_reward(purchased, goal)\n assert result['r_type'] == 1.\n assert result['query_match'] == True\n assert result['category_match'] == True\n assert result['title_score'] == 1\n\n # Query Mismatch\n purchased['query'] = 'Query 2'\n result = get_type_reward(purchased, goal)\n assert result['query_match'] == False\n\n # Out of order / non-matching / partially matching / duplicate categories\n purchased['product_category'] = \"b › c › a\"\n result = get_type_reward(purchased, goal)\n assert result['category_match'] == True\n purchased['product_category'] = \"d › e › f\"\n result = get_type_reward(purchased, goal)\n assert result['category_match'] == False\n purchased['product_category'] = \"a › d › b\"\n result = get_type_reward(purchased, goal)\n assert result['category_match'] == True\n purchased['product_category'] = \"a › a › b\"\n result = get_type_reward(purchased, goal)\n assert result['category_match'] == True\n purchased['product_category'] = \"a › a › d\"\n result = get_type_reward(purchased, goal)\n assert result['category_match'] == False\n\n # Similar product names\n goal['name'] = \"Mens D.O.N. Issue 2 Gca Basketball Sneakers Shoes Casual - Off White\"\n purchased['name'] = \"PEAK High Top Mens Basketball Shoes Lou Williams Streetball Master Breathable Non Slip Outdoor Sneakers\"\n result = get_type_reward(purchased, goal)\n assert isclose(result['title_score'], 0.333, abs_tol=1e-2)\n\n # Slightly similar product names\n goal['name'] = \"Saireed UL Listed 2 Prong Power Cord for JBL Bar 3.1 Bar 2.1 Channel 4K Ultra HD Soundbar Home Theater System Subwoofer\"\n purchased['name'] = \"BRST AC Power Cord Outlet Socket Cable Plug Lead for Panasonic SC-HT830V DVD/VCR Combo Home Theater System\"\n result = get_type_reward(purchased, goal)\n assert isclose(result['title_score'], 0.3, abs_tol=1e-2)\n\n goal['name'] = \"Saireed UL Listed 2 Prong Power Cord for JBL Bar 3.1 Bar 2.1 Channel 4K Ultra HD Soundbar\"\n purchased['name'] = \"BRST AC Power Cord Outlet Socket Cable Plug Lead for Panasonic SC-HT830V DVD/VCR Combo Home Theater System\"\n result = get_type_reward(purchased, goal)\n assert isclose(result['title_score'], 0.15, abs_tol=1e-2)\n\n # Completely different product names\n goal['name'] = \"Rusticware 921ORB Kitchen and Bath Cabinet Knob\"\n purchased['name'] = \"Minkissy 2pcs Stainless Steel Eyebrow Tweezers Blackhead Acne Remover Portable Makeup Tweezers (Silver)\"\n result = get_type_reward(purchased, goal)\n assert result['title_score'] < 0.05\n\ndef test_get_attribute_reward():\n # Exact Match\n goal = {\n 'attributes': [\"tea tree\", \"essential oils\", \"natural ingredients\"],\n }\n purchased = {\n 'Attributes': [\"tea tree\", \"essential oil\", \"natural ingredients\"]\n }\n r_attr, num_attr_matches = get_attribute_reward(purchased, goal)\n assert r_attr == 1\n assert num_attr_matches == 3\n\n # Partial Match\n goal = {\n 'attributes': [\"tea tree\", \"essential oils\", \"natural ingredients\"]\n }\n purchased = {\n 'Attributes': [\"essential oil\", \"natural ingredients\"],\n 'Title': \"\",\n 'BulletPoints': [],\n 'Description': \"\"\n }\n r_attr, num_attr_matches = get_attribute_reward(purchased, goal)\n assert r_attr == 2./3.\n assert num_attr_matches == 2\n\n # Goal attributes found in purchased non-goals\n goal = {\n 'attributes': [\"tea tree\", \"essential oils\", \"natural ingredients\"]\n }\n purchased = {\n 'Attributes': [],\n 'Title': \"\",\n 'BulletPoints': [\"This shampoo has essential oils and smells like lemons\"],\n 'Description': \"Best shampoo on the market, made with natural ingredients\"\n }\n r_attr, num_attr_matches = get_attribute_reward(purchased, goal)\n assert r_attr == 2./3.\n assert num_attr_matches == 2\n\n # No match\n goal = {\n 'attributes': [\"tea tree\", \"essential oils\", \"natural ingredients\"]\n }\n purchased = {\n 'Attributes': [\"tea bag\", \"earl gray\", \"lipton\"],\n 'Title': \"English tea for breakfast\",\n 'BulletPoints': [\"Soothing aroma\", \"Calming, great feeling\"],\n 'Description': \"Best tea made by Lipton, great to pair with breakfast\"\n }\n r_attr, num_attr_matches = get_attribute_reward(purchased, goal)\n assert r_attr == 0\n assert num_attr_matches == 0\n\ndef test_get_option_reward():\n # Exact Match\n goal = [\"grey\", \"XL\", \"pack of 12\"]\n purchased = [\"pack of 12\", \"grey\", \"XL\"]\n r_option, matches = get_option_reward(purchased, goal)\n assert matches == len(goal)\n assert r_option == 1\n\n # Partial Match\n goal = [\"grey\", \"XL\", \"pack of 12\"]\n purchased = [\"pack of 12\", \"blue\", \"XL\"]\n r_option, matches = get_option_reward(purchased, goal)\n assert matches == len(goal) - 1\n assert r_option == 2./3.\n\n # Fuzzy Match\n goal = [\"cool powder snow\", \"XL\", \"pack of 12\"]\n purchased = [\"pack of 12\", \"powder snow\", \"XL\"]\n r_option, matches = get_option_reward(purchased, goal)\n assert matches == len(goal)\n assert r_option == 1\n\n # Empty Goal Options\n goal = []\n purchased = [\"goal 1\", \"goal 2\"]\n r_option, matches = get_option_reward(purchased, goal)\n assert matches == 0\n assert r_option == None\n\n # Empty Purchased Options\n goal = [\"goal 1\", \"goal 2\"]\n purchased = []\n r_option, matches = get_option_reward(purchased, goal)\n assert matches == 0\n assert r_option == 0\n\ndef test_get_reward():\n # Exact Match\n goal = {\n 'query': \"Query 1\",\n 'product_category': \"a › b › c\",\n 'name': \"Mens D.O.N. Issue 2 Gca Basketball Sneakers Shoes Casual - Off White\",\n 'attributes': [\"tea tree\", \"essential oils\", \"natural ingredients\"],\n 'goal_options': {\"color\": \"grey\", \"size\": \"XL\"},\n 'price_upper': 40.00\n }\n purchased = {\n 'query': \"Query 1\",\n 'product_category': \"a › b › c\",\n 'name': \"Mens D.O.N. Issue 2 Gca Basketball Sneakers Shoes Casual - Off White\",\n 'Attributes': [\"tea tree\", \"essential oil\", \"natural ingredients\"],\n 'Title': \"\",\n 'BulletPoints': [],\n 'Description': \"\",\n 'goal_options': {\"color\": \"grey\", \"size\": \"XL\"}\n }\n total_reward = get_reward(purchased, goal, 35, purchased['goal_options'])\n assert total_reward == 1\n\n # Variation in r_attributes reward\n purchased['Attributes'] = []\n purchased['Title'] = \"\"\n purchased['BulletPoints'] = \"This shampoo has essential oils and smells like lemons\"\n purchased['Description'] = \"Best shampoo on the market, made with natural ingredients\"\n total_reward = get_reward(purchased, goal, 35, purchased['goal_options'])\n assert isclose(total_reward, 2./3., abs_tol=1e-2)\n\n # Variation in r_option reward\n goal['goal_options'] = {\"color\": \"grey\", \"size\": \"XL\", \"amount\": \"pack of 12\"}\n total_reward = get_reward(purchased, goal, 35, purchased['goal_options'])\n assert isclose(total_reward, 0.5714, abs_tol=1e-2)\n\n # Variation in r_type reward\n goal['name'] = \"Saireed UL Listed 2 Prong Power Cord for JBL Bar 3.1 Bar 2.1 Channel 4K Ultra HD Soundbar\"\n purchased['name'] = \"BRST AC Power Cord Outlet Socket Cable Plug Lead for Panasonic SC-HT830V DVD/VCR Combo Home Theater System\"\n purchased['query'] = \"Query 2\"\n purchased['product_category'] = \"a › d › e\"\n total_reward = get_reward(purchased, goal, 35, purchased['goal_options'])\n assert isclose(total_reward, 0.2857, abs_tol=1e-2)","source_hash":"f10b97ca81eb2f4ffd8a3a0b377f421d3c0ce50ee2d5e80d7e1f39fab228055e","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.tests.web-agent-site.engine.test_goal.test_get_type_reward","uri":"program://BOLAA/function/webshop.tests.web-agent-site.engine.test_goal.test_get_type_reward#L5-L66","kind":"function","name":"test_get_type_reward","path":"webshop/tests/web-agent-site/engine/test_goal.py","language":"python","start_line":5,"end_line":66,"context_start_line":1,"context_end_line":86,"code":"import pytest\nfrom math import isclose\nfrom web_agent_site.engine.goal import *\n\ndef test_get_type_reward():\n # Exact Match\n goal = {\n 'query': \"Query 1\",\n 'product_category': \"a › b › c\",\n 'name': \"Name 1\"\n }\n purchased = {\n 'query': \"Query 1\",\n 'product_category': \"a › b › c\",\n 'name': \"Name 1\"\n }\n result = get_type_reward(purchased, goal)\n assert result['r_type'] == 1.\n assert result['query_match'] == True\n assert result['category_match'] == True\n assert result['title_score'] == 1\n\n # Query Mismatch\n purchased['query'] = 'Query 2'\n result = get_type_reward(purchased, goal)\n assert result['query_match'] == False\n\n # Out of order / non-matching / partially matching / duplicate categories\n purchased['product_category'] = \"b › c › a\"\n result = get_type_reward(purchased, goal)\n assert result['category_match'] == True\n purchased['product_category'] = \"d › e › f\"\n result = get_type_reward(purchased, goal)\n assert result['category_match'] == False\n purchased['product_category'] = \"a › d › b\"\n result = get_type_reward(purchased, goal)\n assert result['category_match'] == True\n purchased['product_category'] = \"a › a › b\"\n result = get_type_reward(purchased, goal)\n assert result['category_match'] == True\n purchased['product_category'] = \"a › a › d\"\n result = get_type_reward(purchased, goal)\n assert result['category_match'] == False\n\n # Similar product names\n goal['name'] = \"Mens D.O.N. Issue 2 Gca Basketball Sneakers Shoes Casual - Off White\"\n purchased['name'] = \"PEAK High Top Mens Basketball Shoes Lou Williams Streetball Master Breathable Non Slip Outdoor Sneakers\"\n result = get_type_reward(purchased, goal)\n assert isclose(result['title_score'], 0.333, abs_tol=1e-2)\n\n # Slightly similar product names\n goal['name'] = \"Saireed UL Listed 2 Prong Power Cord for JBL Bar 3.1 Bar 2.1 Channel 4K Ultra HD Soundbar Home Theater System Subwoofer\"\n purchased['name'] = \"BRST AC Power Cord Outlet Socket Cable Plug Lead for Panasonic SC-HT830V DVD/VCR Combo Home Theater System\"\n result = get_type_reward(purchased, goal)\n assert isclose(result['title_score'], 0.3, abs_tol=1e-2)\n\n goal['name'] = \"Saireed UL Listed 2 Prong Power Cord for JBL Bar 3.1 Bar 2.1 Channel 4K Ultra HD Soundbar\"\n purchased['name'] = \"BRST AC Power Cord Outlet Socket Cable Plug Lead for Panasonic SC-HT830V DVD/VCR Combo Home Theater System\"\n result = get_type_reward(purchased, goal)\n assert isclose(result['title_score'], 0.15, abs_tol=1e-2)\n\n # Completely different product names\n goal['name'] = \"Rusticware 921ORB Kitchen and Bath Cabinet Knob\"\n purchased['name'] = \"Minkissy 2pcs Stainless Steel Eyebrow Tweezers Blackhead Acne Remover Portable Makeup Tweezers (Silver)\"\n result = get_type_reward(purchased, goal)\n assert result['title_score'] < 0.05\n\ndef test_get_attribute_reward():\n # Exact Match\n goal = {\n 'attributes': [\"tea tree\", \"essential oils\", \"natural ingredients\"],\n }\n purchased = {\n 'Attributes': [\"tea tree\", \"essential oil\", \"natural ingredients\"]\n }\n r_attr, num_attr_matches = get_attribute_reward(purchased, goal)\n assert r_attr == 1\n assert num_attr_matches == 3\n\n # Partial Match\n goal = {\n 'attributes': [\"tea tree\", \"essential oils\", \"natural ingredients\"]\n }\n purchased = {\n 'Attributes': [\"essential oil\", \"natural ingredients\"],\n 'Title': \"\",","source_hash":"f10b97ca81eb2f4ffd8a3a0b377f421d3c0ce50ee2d5e80d7e1f39fab228055e","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.tests.web-agent-site.engine.test_goal.test_get_attribute_reward","uri":"program://BOLAA/function/webshop.tests.web-agent-site.engine.test_goal.test_get_attribute_reward#L68-L120","kind":"function","name":"test_get_attribute_reward","path":"webshop/tests/web-agent-site/engine/test_goal.py","language":"python","start_line":68,"end_line":120,"context_start_line":48,"context_end_line":140,"code":" result = get_type_reward(purchased, goal)\n assert isclose(result['title_score'], 0.333, abs_tol=1e-2)\n\n # Slightly similar product names\n goal['name'] = \"Saireed UL Listed 2 Prong Power Cord for JBL Bar 3.1 Bar 2.1 Channel 4K Ultra HD Soundbar Home Theater System Subwoofer\"\n purchased['name'] = \"BRST AC Power Cord Outlet Socket Cable Plug Lead for Panasonic SC-HT830V DVD/VCR Combo Home Theater System\"\n result = get_type_reward(purchased, goal)\n assert isclose(result['title_score'], 0.3, abs_tol=1e-2)\n\n goal['name'] = \"Saireed UL Listed 2 Prong Power Cord for JBL Bar 3.1 Bar 2.1 Channel 4K Ultra HD Soundbar\"\n purchased['name'] = \"BRST AC Power Cord Outlet Socket Cable Plug Lead for Panasonic SC-HT830V DVD/VCR Combo Home Theater System\"\n result = get_type_reward(purchased, goal)\n assert isclose(result['title_score'], 0.15, abs_tol=1e-2)\n\n # Completely different product names\n goal['name'] = \"Rusticware 921ORB Kitchen and Bath Cabinet Knob\"\n purchased['name'] = \"Minkissy 2pcs Stainless Steel Eyebrow Tweezers Blackhead Acne Remover Portable Makeup Tweezers (Silver)\"\n result = get_type_reward(purchased, goal)\n assert result['title_score'] < 0.05\n\ndef test_get_attribute_reward():\n # Exact Match\n goal = {\n 'attributes': [\"tea tree\", \"essential oils\", \"natural ingredients\"],\n }\n purchased = {\n 'Attributes': [\"tea tree\", \"essential oil\", \"natural ingredients\"]\n }\n r_attr, num_attr_matches = get_attribute_reward(purchased, goal)\n assert r_attr == 1\n assert num_attr_matches == 3\n\n # Partial Match\n goal = {\n 'attributes': [\"tea tree\", \"essential oils\", \"natural ingredients\"]\n }\n purchased = {\n 'Attributes': [\"essential oil\", \"natural ingredients\"],\n 'Title': \"\",\n 'BulletPoints': [],\n 'Description': \"\"\n }\n r_attr, num_attr_matches = get_attribute_reward(purchased, goal)\n assert r_attr == 2./3.\n assert num_attr_matches == 2\n\n # Goal attributes found in purchased non-goals\n goal = {\n 'attributes': [\"tea tree\", \"essential oils\", \"natural ingredients\"]\n }\n purchased = {\n 'Attributes': [],\n 'Title': \"\",\n 'BulletPoints': [\"This shampoo has essential oils and smells like lemons\"],\n 'Description': \"Best shampoo on the market, made with natural ingredients\"\n }\n r_attr, num_attr_matches = get_attribute_reward(purchased, goal)\n assert r_attr == 2./3.\n assert num_attr_matches == 2\n\n # No match\n goal = {\n 'attributes': [\"tea tree\", \"essential oils\", \"natural ingredients\"]\n }\n purchased = {\n 'Attributes': [\"tea bag\", \"earl gray\", \"lipton\"],\n 'Title': \"English tea for breakfast\",\n 'BulletPoints': [\"Soothing aroma\", \"Calming, great feeling\"],\n 'Description': \"Best tea made by Lipton, great to pair with breakfast\"\n }\n r_attr, num_attr_matches = get_attribute_reward(purchased, goal)\n assert r_attr == 0\n assert num_attr_matches == 0\n\ndef test_get_option_reward():\n # Exact Match\n goal = [\"grey\", \"XL\", \"pack of 12\"]\n purchased = [\"pack of 12\", \"grey\", \"XL\"]\n r_option, matches = get_option_reward(purchased, goal)\n assert matches == len(goal)\n assert r_option == 1\n\n # Partial Match\n goal = [\"grey\", \"XL\", \"pack of 12\"]\n purchased = [\"pack of 12\", \"blue\", \"XL\"]\n r_option, matches = get_option_reward(purchased, goal)\n assert matches == len(goal) - 1\n assert r_option == 2./3.\n\n # Fuzzy Match\n goal = [\"cool powder snow\", \"XL\", \"pack of 12\"]\n purchased = [\"pack of 12\", \"powder snow\", \"XL\"]\n r_option, matches = get_option_reward(purchased, goal)","source_hash":"f10b97ca81eb2f4ffd8a3a0b377f421d3c0ce50ee2d5e80d7e1f39fab228055e","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.tests.web-agent-site.engine.test_goal.test_get_option_reward","uri":"program://BOLAA/function/webshop.tests.web-agent-site.engine.test_goal.test_get_option_reward#L122-L156","kind":"function","name":"test_get_option_reward","path":"webshop/tests/web-agent-site/engine/test_goal.py","language":"python","start_line":122,"end_line":156,"context_start_line":102,"context_end_line":176,"code":" 'Description': \"Best shampoo on the market, made with natural ingredients\"\n }\n r_attr, num_attr_matches = get_attribute_reward(purchased, goal)\n assert r_attr == 2./3.\n assert num_attr_matches == 2\n\n # No match\n goal = {\n 'attributes': [\"tea tree\", \"essential oils\", \"natural ingredients\"]\n }\n purchased = {\n 'Attributes': [\"tea bag\", \"earl gray\", \"lipton\"],\n 'Title': \"English tea for breakfast\",\n 'BulletPoints': [\"Soothing aroma\", \"Calming, great feeling\"],\n 'Description': \"Best tea made by Lipton, great to pair with breakfast\"\n }\n r_attr, num_attr_matches = get_attribute_reward(purchased, goal)\n assert r_attr == 0\n assert num_attr_matches == 0\n\ndef test_get_option_reward():\n # Exact Match\n goal = [\"grey\", \"XL\", \"pack of 12\"]\n purchased = [\"pack of 12\", \"grey\", \"XL\"]\n r_option, matches = get_option_reward(purchased, goal)\n assert matches == len(goal)\n assert r_option == 1\n\n # Partial Match\n goal = [\"grey\", \"XL\", \"pack of 12\"]\n purchased = [\"pack of 12\", \"blue\", \"XL\"]\n r_option, matches = get_option_reward(purchased, goal)\n assert matches == len(goal) - 1\n assert r_option == 2./3.\n\n # Fuzzy Match\n goal = [\"cool powder snow\", \"XL\", \"pack of 12\"]\n purchased = [\"pack of 12\", \"powder snow\", \"XL\"]\n r_option, matches = get_option_reward(purchased, goal)\n assert matches == len(goal)\n assert r_option == 1\n\n # Empty Goal Options\n goal = []\n purchased = [\"goal 1\", \"goal 2\"]\n r_option, matches = get_option_reward(purchased, goal)\n assert matches == 0\n assert r_option == None\n\n # Empty Purchased Options\n goal = [\"goal 1\", \"goal 2\"]\n purchased = []\n r_option, matches = get_option_reward(purchased, goal)\n assert matches == 0\n assert r_option == 0\n\ndef test_get_reward():\n # Exact Match\n goal = {\n 'query': \"Query 1\",\n 'product_category': \"a › b › c\",\n 'name': \"Mens D.O.N. Issue 2 Gca Basketball Sneakers Shoes Casual - Off White\",\n 'attributes': [\"tea tree\", \"essential oils\", \"natural ingredients\"],\n 'goal_options': {\"color\": \"grey\", \"size\": \"XL\"},\n 'price_upper': 40.00\n }\n purchased = {\n 'query': \"Query 1\",\n 'product_category': \"a › b › c\",\n 'name': \"Mens D.O.N. Issue 2 Gca Basketball Sneakers Shoes Casual - Off White\",\n 'Attributes': [\"tea tree\", \"essential oil\", \"natural ingredients\"],\n 'Title': \"\",\n 'BulletPoints': [],\n 'Description': \"\",\n 'goal_options': {\"color\": \"grey\", \"size\": \"XL\"}","source_hash":"f10b97ca81eb2f4ffd8a3a0b377f421d3c0ce50ee2d5e80d7e1f39fab228055e","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.tests.web-agent-site.engine.test_goal.test_get_reward","uri":"program://BOLAA/function/webshop.tests.web-agent-site.engine.test_goal.test_get_reward#L158-L200","kind":"function","name":"test_get_reward","path":"webshop/tests/web-agent-site/engine/test_goal.py","language":"python","start_line":158,"end_line":200,"context_start_line":138,"context_end_line":200,"code":" goal = [\"cool powder snow\", \"XL\", \"pack of 12\"]\n purchased = [\"pack of 12\", \"powder snow\", \"XL\"]\n r_option, matches = get_option_reward(purchased, goal)\n assert matches == len(goal)\n assert r_option == 1\n\n # Empty Goal Options\n goal = []\n purchased = [\"goal 1\", \"goal 2\"]\n r_option, matches = get_option_reward(purchased, goal)\n assert matches == 0\n assert r_option == None\n\n # Empty Purchased Options\n goal = [\"goal 1\", \"goal 2\"]\n purchased = []\n r_option, matches = get_option_reward(purchased, goal)\n assert matches == 0\n assert r_option == 0\n\ndef test_get_reward():\n # Exact Match\n goal = {\n 'query': \"Query 1\",\n 'product_category': \"a › b › c\",\n 'name': \"Mens D.O.N. Issue 2 Gca Basketball Sneakers Shoes Casual - Off White\",\n 'attributes': [\"tea tree\", \"essential oils\", \"natural ingredients\"],\n 'goal_options': {\"color\": \"grey\", \"size\": \"XL\"},\n 'price_upper': 40.00\n }\n purchased = {\n 'query': \"Query 1\",\n 'product_category': \"a › b › c\",\n 'name': \"Mens D.O.N. Issue 2 Gca Basketball Sneakers Shoes Casual - Off White\",\n 'Attributes': [\"tea tree\", \"essential oil\", \"natural ingredients\"],\n 'Title': \"\",\n 'BulletPoints': [],\n 'Description': \"\",\n 'goal_options': {\"color\": \"grey\", \"size\": \"XL\"}\n }\n total_reward = get_reward(purchased, goal, 35, purchased['goal_options'])\n assert total_reward == 1\n\n # Variation in r_attributes reward\n purchased['Attributes'] = []\n purchased['Title'] = \"\"\n purchased['BulletPoints'] = \"This shampoo has essential oils and smells like lemons\"\n purchased['Description'] = \"Best shampoo on the market, made with natural ingredients\"\n total_reward = get_reward(purchased, goal, 35, purchased['goal_options'])\n assert isclose(total_reward, 2./3., abs_tol=1e-2)\n\n # Variation in r_option reward\n goal['goal_options'] = {\"color\": \"grey\", \"size\": \"XL\", \"amount\": \"pack of 12\"}\n total_reward = get_reward(purchased, goal, 35, purchased['goal_options'])\n assert isclose(total_reward, 0.5714, abs_tol=1e-2)\n\n # Variation in r_type reward\n goal['name'] = \"Saireed UL Listed 2 Prong Power Cord for JBL Bar 3.1 Bar 2.1 Channel 4K Ultra HD Soundbar\"\n purchased['name'] = \"BRST AC Power Cord Outlet Socket Cable Plug Lead for Panasonic SC-HT830V DVD/VCR Combo Home Theater System\"\n purchased['query'] = \"Query 2\"\n purchased['product_category'] = \"a › d › e\"\n total_reward = get_reward(purchased, goal, 35, purchased['goal_options'])\n assert isclose(total_reward, 0.2857, abs_tol=1e-2)","source_hash":"f10b97ca81eb2f4ffd8a3a0b377f421d3c0ce50ee2d5e80d7e1f39fab228055e","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.tests.web-agent-site.engine.test_normalize","uri":"program://BOLAA/module/webshop.tests.web-agent-site.engine.test_normalize#L1-L53","kind":"module","name":"webshop.tests.web-agent-site.engine.test_normalize","path":"webshop/tests/web-agent-site/engine/test_normalize.py","language":"python","start_line":1,"end_line":53,"context_start_line":1,"context_end_line":53,"code":"import pytest\nfrom web_agent_site.engine.normalize import *\n\ndef test_normalize_color():\n suite = [\n (\"\", \"\"),\n (\"black forest\", \"black\"),\n (\"violet lavender\", \"lavender\"),\n (\"steelivy fuchsia\", \"fuchsia\"),\n (\"123alabaster\", \"alabaster\"),\n (\"webshop\", \"webshop\")\n ]\n for color_string, expected in suite:\n output = normalize_color(color_string)\n assert type(output) is str\n assert output == expected\n\ndef test_normalize_color_size():\n product_prices = {\n (1, \"black forest\", \"3 meter\"): 10.29,\n (2, \"violet lavender\", \"xx-large\"): 23.42,\n (3, \"steelivy fuchsia\", \"random value\"): 193.87,\n (4, \"123alabaster\", \"40cm plus\"): 67.23,\n (5, \"webshop\", \"142\"): 1.02,\n (6, \"webshopsteel\", \"2 petite\"): 57.99,\n (7, \"leather black\", \"91ft walnut feet\"): 6.20,\n }\n color_mapping_expected = {\n 'N.A.': 'not_matched',\n \"black forest\": \"black\",\n \"violet lavender\": \"lavender\",\n \"steelivy fuchsia\": \"fuchsia\",\n \"123alabaster\": \"alabaster\",\n \"webshop\": \"not_matched\",\n \"webshopsteel\": \"steel\",\n \"leather black\": \"black\"\n }\n size_mapping_expected = {\n 'N.A.': 'not_matched',\n \"3 meter\": '(.*)meter',\n \"xx-large\": 'xx-large',\n \"random value\": \"not_matched\",\n \"40cm plus\": '(.*)plus',\n \"142\": \"numeric_size\",\n \"2 petite\": \"(.*)petite\",\n \"91ft walnut feet\": '(.*)ft',\n }\n\n color_mapping, size_mapping = normalize_color_size(product_prices)\n assert type(color_mapping) == dict\n assert type(size_mapping) == dict\n assert color_mapping == color_mapping_expected\n assert size_mapping == size_mapping_expected","source_hash":"503168a43640681d8a5863a027727c8b4c2b777358b278e3c0bd45d6f2f476a4","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.tests.web-agent-site.engine.test_normalize.test_normalize_color","uri":"program://BOLAA/function/webshop.tests.web-agent-site.engine.test_normalize.test_normalize_color#L4-L16","kind":"function","name":"test_normalize_color","path":"webshop/tests/web-agent-site/engine/test_normalize.py","language":"python","start_line":4,"end_line":16,"context_start_line":1,"context_end_line":36,"code":"import pytest\nfrom web_agent_site.engine.normalize import *\n\ndef test_normalize_color():\n suite = [\n (\"\", \"\"),\n (\"black forest\", \"black\"),\n (\"violet lavender\", \"lavender\"),\n (\"steelivy fuchsia\", \"fuchsia\"),\n (\"123alabaster\", \"alabaster\"),\n (\"webshop\", \"webshop\")\n ]\n for color_string, expected in suite:\n output = normalize_color(color_string)\n assert type(output) is str\n assert output == expected\n\ndef test_normalize_color_size():\n product_prices = {\n (1, \"black forest\", \"3 meter\"): 10.29,\n (2, \"violet lavender\", \"xx-large\"): 23.42,\n (3, \"steelivy fuchsia\", \"random value\"): 193.87,\n (4, \"123alabaster\", \"40cm plus\"): 67.23,\n (5, \"webshop\", \"142\"): 1.02,\n (6, \"webshopsteel\", \"2 petite\"): 57.99,\n (7, \"leather black\", \"91ft walnut feet\"): 6.20,\n }\n color_mapping_expected = {\n 'N.A.': 'not_matched',\n \"black forest\": \"black\",\n \"violet lavender\": \"lavender\",\n \"steelivy fuchsia\": \"fuchsia\",\n \"123alabaster\": \"alabaster\",\n \"webshop\": \"not_matched\",\n \"webshopsteel\": \"steel\",\n \"leather black\": \"black\"","source_hash":"503168a43640681d8a5863a027727c8b4c2b777358b278e3c0bd45d6f2f476a4","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.tests.web-agent-site.engine.test_normalize.test_normalize_color_size","uri":"program://BOLAA/function/webshop.tests.web-agent-site.engine.test_normalize.test_normalize_color_size#L18-L53","kind":"function","name":"test_normalize_color_size","path":"webshop/tests/web-agent-site/engine/test_normalize.py","language":"python","start_line":18,"end_line":53,"context_start_line":1,"context_end_line":53,"code":"import pytest\nfrom web_agent_site.engine.normalize import *\n\ndef test_normalize_color():\n suite = [\n (\"\", \"\"),\n (\"black forest\", \"black\"),\n (\"violet lavender\", \"lavender\"),\n (\"steelivy fuchsia\", \"fuchsia\"),\n (\"123alabaster\", \"alabaster\"),\n (\"webshop\", \"webshop\")\n ]\n for color_string, expected in suite:\n output = normalize_color(color_string)\n assert type(output) is str\n assert output == expected\n\ndef test_normalize_color_size():\n product_prices = {\n (1, \"black forest\", \"3 meter\"): 10.29,\n (2, \"violet lavender\", \"xx-large\"): 23.42,\n (3, \"steelivy fuchsia\", \"random value\"): 193.87,\n (4, \"123alabaster\", \"40cm plus\"): 67.23,\n (5, \"webshop\", \"142\"): 1.02,\n (6, \"webshopsteel\", \"2 petite\"): 57.99,\n (7, \"leather black\", \"91ft walnut feet\"): 6.20,\n }\n color_mapping_expected = {\n 'N.A.': 'not_matched',\n \"black forest\": \"black\",\n \"violet lavender\": \"lavender\",\n \"steelivy fuchsia\": \"fuchsia\",\n \"123alabaster\": \"alabaster\",\n \"webshop\": \"not_matched\",\n \"webshopsteel\": \"steel\",\n \"leather black\": \"black\"\n }\n size_mapping_expected = {\n 'N.A.': 'not_matched',\n \"3 meter\": '(.*)meter',\n \"xx-large\": 'xx-large',\n \"random value\": \"not_matched\",\n \"40cm plus\": '(.*)plus',\n \"142\": \"numeric_size\",\n \"2 petite\": \"(.*)petite\",\n \"91ft walnut feet\": '(.*)ft',\n }\n\n color_mapping, size_mapping = normalize_color_size(product_prices)\n assert type(color_mapping) == dict\n assert type(size_mapping) == dict\n assert color_mapping == color_mapping_expected\n assert size_mapping == size_mapping_expected","source_hash":"503168a43640681d8a5863a027727c8b4c2b777358b278e3c0bd45d6f2f476a4","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.tests.transfer.test_predict_help","uri":"program://BOLAA/module/webshop.tests.transfer.test_predict_help#L1-L468","kind":"module","name":"webshop.tests.transfer.test_predict_help","path":"webshop/tests/transfer/test_predict_help.py","language":"python","start_line":1,"end_line":468,"context_start_line":1,"context_end_line":468,"code":"import json\nimport pytest\nimport requests_mock\n\nfrom transfer.predict_help import (\n convert_dict_to_actions,\n parse_item_page_amz, parse_results_amz,\n parse_item_page_ebay, parse_results_ebay,\n parse_item_page_ws, parse_results_ws,\n Page, WEBSHOP_URL, WEBSHOP_SESSION\n)\n\n@requests_mock.Mocker(kw=\"mock\")\ndef test_parse_item_page_ws(**kwargs):\n # Read mock response data\n mock_file = open(\"tests/transfer/mocks/mock_parse_item_page_ws\", \"rb\")\n mock_body = mock_file.read()\n mock_file.close()\n\n mock_desc_file = open(\"tests/transfer/mocks/mock_parse_item_page_ws_desc\", \"rb\")\n mock_desc_body = mock_desc_file.read()\n mock_desc_file.close()\n\n mock_feat_file = open(\"tests/transfer/mocks/mock_parse_item_page_ws_feat\", \"rb\")\n mock_feat_body = mock_feat_file.read()\n mock_feat_file.close()\n\n mock_asin = \"B09P87V3LZ\"\n mock_query = \"red basketball shoes\"\n mock_options = {}\n\n # Invoke function, check response\n query_str = '+'.join(mock_query.split())\n options_str = json.dumps(mock_options)\n url = (\n f\"{WEBSHOP_URL}/item_page/{WEBSHOP_SESSION}/\"\n f\"{mock_asin}/{query_str}/1/{options_str}\"\n )\n url_desc = (\n f\"{WEBSHOP_URL}/item_sub_page/{WEBSHOP_SESSION}/\"\n f\"{mock_asin}/{query_str}/1/Description/{options_str}\"\n )\n url_feat = (\n f\"{WEBSHOP_URL}/item_sub_page/{WEBSHOP_SESSION}/\"\n f\"{mock_asin}/{query_str}/1/Features/{options_str}\"\n )\n print(f\"Item Page URL: {url}\")\n print(f\"Item Description URL: {url_desc}\")\n print(f\"Item Features URL: {url_feat}\")\n\n kwargs[\"mock\"].get(url, content=mock_body)\n kwargs[\"mock\"].get(url_desc, content=mock_desc_body)\n kwargs[\"mock\"].get(url_feat, content=mock_feat_body)\n\n output = parse_item_page_ws(mock_asin, mock_query, 1, mock_options)\n expected = {\n 'MainImage': 'https://m.media-amazon.com/images/I/51ltvkzGhGL.jpg',\n 'Price': '100.0',\n 'Rating': 'N.A.',\n 'Title': 'PMUYBHF Womens Fashion Flat Shoes Comfortable Running Shoes ' \n 'Sneakers Tennis Athletic Shoe Casual Walking Shoes',\n 'asin': mock_asin,\n 'option_to_image': {\n '6.5': 'http://3.83.245.205:3000/item_page/abc/B09P87V3LZ/%5B%27red%27%2C%20%27basketball%27%2C%20%27shoes%27%5D/1/%7B%27size%27:%20%276.5%27%7D',\n '7.5': 'http://3.83.245.205:3000/item_page/abc/B09P87V3LZ/%5B%27red%27%2C%20%27basketball%27%2C%20%27shoes%27%5D/1/%7B%27size%27:%20%277.5%27%7D',\n '8': 'http://3.83.245.205:3000/item_page/abc/B09P87V3LZ/%5B%27red%27%2C%20%27basketball%27%2C%20%27shoes%27%5D/1/%7B%27size%27:%20%278%27%7D',\n '8.5': 'http://3.83.245.205:3000/item_page/abc/B09P87V3LZ/%5B%27red%27%2C%20%27basketball%27%2C%20%27shoes%27%5D/1/%7B%27size%27:%20%278.5%27%7D',\n '9': 'http://3.83.245.205:3000/item_page/abc/B09P87V3LZ/%5B%27red%27%2C%20%27basketball%27%2C%20%27shoes%27%5D/1/%7B%27size%27:%20%279%27%7D',\n 'black': 'http://3.83.245.205:3000/item_page/abc/B09P87V3LZ/%5B%27red%27%2C%20%27basketball%27%2C%20%27shoes%27%5D/1/%7B%27color%27:%20%27black%27%7D',\n 'purple': 'http://3.83.245.205:3000/item_page/abc/B09P87V3LZ/%5B%27red%27%2C%20%27basketball%27%2C%20%27shoes%27%5D/1/%7B%27color%27:%20%27purple%27%7D',\n 'red': 'http://3.83.245.205:3000/item_page/abc/B09P87V3LZ/%5B%27red%27%2C%20%27basketball%27%2C%20%27shoes%27%5D/1/%7B%27color%27:%20%27red%27%7D'\n },\n 'options': {\n 'color': ['black', 'purple', 'red'],\n 'size': ['6.5', '7.5', '8', '8.5', '9']\n },\n 'BulletPoints': 'Pure Running Shoe\\nComfort Flat Sneakers\\n[FEATURES]: Soles with unique non-slip pattern, it has great ' \n 'abrasion resistant and provide protection when you walking or running. (Pure Running Shoe Mesh Walking Shoes Fashion ' \n 'Sneakers Slip On Sneakers Wedge Platform Loafers Modern Walking Shoes Sock Sneakers Platform Loafers Shoes Non Slip ' \n 'Running Shoes Athletic Tennis Shoes Blade Type Sneakers Lace-up Sneaker) sole\\n[WIDE ANKLE DESIGN]: Perfect accord with human body ' \n 'engineering, green, healthy concept design make the walking shoes wear more comfortable, wide width wlking shoes. (Low ' \n 'Top Walking Shoes Fashion Canvas Sneakers Slip On Shoes Casual Walking Shoes Hidden Wedge Sneaker Low Top Canvas ' \n 'Sneakers Lace-up Classic Casual Shoes Walking Tennis Shoes Lightweight Casual Sneakers Slip on Sock Sneakers Air ' \n 'Cushion Platform Loafers Slip-On Mule Sneaker )\\n[CUSHION WITH ARCH SUPPORT]: Gives you a comfort for all day ' \n 'long. Wear these lightweight walking shoes, let every step of moving on a comfortable feeling. (Fashion Casual Shoes ' \n 'Athletic Workout Shoes Fitness Sneaker Athletic Running Shoes Air Cushion Sneakers Stylish Athletic Shoes Lace Up ' \n 'Canvas Shoes Slip on Walking Shoe Fashion Sneakers Low Top Classic Sneakers Comfort Fall Shoes Memory Foam Slip On ' \n 'Sneakers Air Cushion Sneakers Running Walking Shoes)\\n[NON-SLIP SOLE]: Made from ultra soft and lightweight RUBBER ' \n 'material,with the function of shock absorbing and cushioning,offering the best durability and traction. (Wedge ' \n 'Sneakers Walking Tennis Shoes Slip On Running Shoes Lightweight Fashion Sneakers Fashion Travel Shoes Walking ' \n 'Running Shoes Non Slip Running Shoes Athletic Tennis Sneakers Sports Walking Shoes Platform Fashion Sneaker ' \n 'Memory Foam Tennis Sneakers Running Jogging Shoes Sock Sneakers Canvas Fashion Sneakers)\\n[OCCASIONS]: Ultra lightweight design provides actual ' \n 'feelings of being barefooted and like walking on the feather, perfect for walking, hiking, bike riding, working, ' \n 'shopping, indoor, outdoor, casual, sports, travel, exercise, vacation, and etc. (Flat Fashion Sneakers Lightweight ' \n 'Walking Sneakers Platform Loafers Sport Running Shoes Casual Flat Loafers Slip-On Sneaker Casual Walking Shoes High Top ' \n 'Canvas Sneakers Lace up Sneakers Workout Walking Shoes Tennis Fitness Sneaker)\\n' \n '[Customers Are Our Priority]: We follow the principle of customer first, so if you encounter any problems after ' \n 'buying shoes, we will try our best to solve them for you. (Breathable Air Cushion Sneakers Walking Tennis Shoes Air ' \n 'Athletic Running Shoes Air Cushion Shoes Mesh Sneakers Fashion Tennis Shoes Jogging Walking Sneakers Breathable ' \n 'Casual Sneakers Fashion Walking Shoes Athletic Running Sneakers Walking Work Shoes Air Running Shoes Slip on ' \n 'Sneakers Mesh Walking Shoes)',\n 'Description': 'Here Are The Things You Want To Knowa─=≡Σ(((つ̀ώ)つSTORE INTRODUCTION:>>>>Our store helps our customers improve their ' \n 'quality of life~As a distributor, we value quality and service.Focus on the high quality and durability of the ' \n 'product.Committed to creating a store that satisfies and reassures our customers.TIPS:>>>>1. Please allow minor errors ' \n 'in the data due to manual measurements.2. Due to the color settings of the display, the actual color may be slightly ' \n 'different from the online image.QUALITY PROMISE:>>>>Our goal is to continuously provide a range of quality products.We ' \n 'place a huge emphasis on the values of quality and reliability.We have always insisted on fulfilling this ' \n 'commitment.In short, we want our customers to have the same great product experience every time and be trusted to deliver ' \n 'on this commitment.Please give us a chance to serve you.OTHER:>>>>athletic sneaker laces athletic sneakers white ' \n 'athletic sneakers for women clearance leather Sneaker leather sneakers women leather sneakers for menleather sneaker laces ' \n 'leather sneaker platform basketball shoes basketball shoes for men basketball shoe laces basketball shoe grip basketball ' \n 'shoes for women fitness shoes for men fitness shoes women workout fitness shoes women fitness shoes women size 5 ' \n 'fitness shoes men workout fitness shoes for men high top sneakers for women walking shoes sneakers with arch support for women'\n }\n assert output == expected\n\n@requests_mock.Mocker(kw=\"mock\")\ndef test_parse_item_page_ebay(**kwargs):\n # Read mock response data\n mock_file = open(\"tests/transfer/mocks/mock_parse_item_page_ebay\", \"rb\")\n mock_body = mock_file.read()\n mock_file.close()\n mock_asin = \"403760625150\"\n\n # Invoke function, check response\n kwargs[\"mock\"].get(f\"https://www.ebay.com/itm/{mock_asin}\", content=mock_body)\n output = parse_item_page_ebay(mock_asin)\n expected = {\n 'BulletPoints': 'Item specifics Condition:New without box: A brand-new, ' \n 'unused, and unworn item (including handmade items) that is ' \n 'not in ... Read moreabout the conditionNew without box: A ' \n 'brand-new, unused, and unworn item (including handmade ' \n 'items) that is not in original packaging or may be missing ' \n 'original packaging materials (such as the original box or ' \n 'bag). The original tags may not be attached. For example, ' \n 'new shoes (with absolutely no signs of wear) that are no ' \n 'longer in their original box fall into this category. See ' \n 'all condition definitionsopens in a new window or tab ' \n 'Closure:Lace Up US Shoe Size:10 Occasion:Activewear, Casual ' \n 'Silhouette:Puma Fabric Type:Mesh Vintage:No Cushioning ' \n 'Level:Moderate Department:Men Style:Sneaker Outsole ' \n 'Material:Rubber Features:Breathable, Comfort, Cushioned, ' \n 'Performance Season:Fall, Spring, Summer, Winter ' \n 'Idset_Mpn:193990-21 Shoe Shaft Style:Low Top Style ' \n 'Code:193990-16 Pattern:Solid Character:J. Cole Lining ' \n 'Material:Synthetic Color:Red Brand:PUMA Type:Athletic ' \n 'Customized:No Model:RS-Dreamer Theme:Sports Shoe ' \n 'Width:Standard Upper Material:Textile Insole ' \n 'Material:Synthetic Performance/Activity:Basketball Product ' \n 'Line:Puma Dreamer',\n 'Description': 'N/A',\n 'MainImage': 'https://i.ebayimg.com/images/g/4ggAAOSwpk1ioTWz/s-l500.jpg',\n 'Price': 'N/A',\n 'Rating': None,\n 'Title': \"Puma RS-Dreamer J. Cole Basketball Shoes Red 193990-16 Men's Size 10.0\",\n 'asin': '403760625150',\n 'option_to_image': {},\n 'options': {},\n }\n assert output == expected\n\n@requests_mock.Mocker(kw=\"mock\")\ndef test_parse_item_page_amz(**kwargs):\n # Read mock response data\n mock_file = open(\"tests/transfer/mocks/mock_parse_item_page_amz\", \"rb\")\n mock_body = mock_file.read()\n mock_file.close()\n mock_asin = \"B073WRF565\"\n\n # Invoke function, check response\n kwargs[\"mock\"].get(f\"https://www.amazon.com/dp/{mock_asin}\", content=mock_body)\n output = parse_item_page_amz(mock_asin)\n expected = {\n 'asin': 'B073WRF565',\n 'Title': 'Amazon Basics Foldable 14\" Black Metal Platform Bed Frame with Tool-Free Assembly No Box Spring Needed - Full',\n 'Price': 'N/A',\n 'Rating': '4.8 out of 5 stars',\n 'BulletPoints': ' \\n About this item ' \n 'Product dimensions: 75\" L x 54\" W x 14\" H | Weight: 41.4 pounds ' \n 'Designed for sleepers up to 250 pounds Full size platform bed frame offers a quiet, noise-free, ' \n 'supportive foundation for a mattress. No box spring needed Folding mechanism makes the frame easy ' \n 'to store and move in tight spaces Provides extra under-the-bed storage space with a vertical clea' \n 'rance of about 13 inches \\n › See more product details ',\n 'Description': 'Amazon Basics Foldable, 14\" Black Metal Platform Bed Frame with Tool-Free Assembly, No Box Spring Needed - Full Amazon Basics',\n 'MainImage': 'https://images-na.ssl-images-amazon.com/images/I/41WIGwt-asL.__AC_SY300_SX300_QL70_FMwebp_.jpg',\n 'options': {'size': ['Twin', 'Full', 'Queen', 'King'],\n 'style': ['14-Inch', '18-Inch']},\n 'option_to_image': {}\n }\n assert output == expected\n\n@requests_mock.Mocker(kw=\"mock\")\ndef test_parse_results_ebay(**kwargs):\n # Read mock response data\n mock_file = open(\"tests/transfer/mocks/mock_parse_results_ebay\", \"rb\")\n mock_body = mock_file.read()\n mock_file.close()\n mock_query = \"red basketball shoes\"\n \n # Invoke function, check response\n query = mock_query.replace(\" \", \"+\")\n kwargs[\"mock\"].get(f'https://www.ebay.com/sch/i.html?_nkw={query}&_pgn=1', content=mock_body)\n output = parse_results_ebay(mock_query, 1)\n expected = [{\n\t\t'Price': ['100.00', '150.00'],\n\t\t'Title': \"Reebok Answer IV Men's Basketball Shoes\",\n\t\t'asin': '175065123030'\n\t}, {\n\t\t'Price': '$119.90',\n\t\t'Title': \"Air Jordan Stay Loyal Shoes Black Red White DB2884-001 Men's Multi \"\n\t\t'Size NEW',\n\t\t'asin': '265672133690'\n\t}, {\n\t\t'Price': '$100.00',\n\t\t'Title': \"Fila Men's Stackhouse Spaghetti Basketball Shoes Black Red White \"\n\t\t'1BM01788-113',\n\t\t'asin': '175282509234'\n\t}, {\n\t\t'Price': ['61.99',\n\t\t\t'85.99'\n\t\t],\n\t\t'Title': 'Puma Disc Rebirth 19481203 Mens Black Red Synthetic Athletic '\n\t\t'Basketball Shoes',\n\t\t'asin': '313944854658'\n\t}, {\n\t\t'Price': '$0.01',\n\t\t'Title': \"Puma RS-Dreamer J. Cole Basketball Shoes Red 193990-16 Men's Size \"\n\t\t'10.0',\n\t\t'asin': '403760625150'\n\t}, {\n\t\t'Price': '$45.00',\n\t\t'Title': 'Nike Mens 9.5 PG 5 Maroon Red White Basketball Shoes Sneaker DM '\n\t\t'5045–601 Flaw',\n\t\t'asin': '115456853186'\n\t}, {\n\t\t'Price': ['114.90',\n\t\t\t'119.90'\n\t\t],\n\t\t'Title': \"Air Jordan Stay Loyal Shoes White Black Red DB2884-106 Men's Multi \"\n\t\t'Size NEW',\n\t\t'asin': '155046831159'\n\t}, {\n\t\t'Price': '$8.99',\n\t\t'Title': \"Harden Volume 3 Men's Basketball Shoes Size 9.5\",\n\t\t'asin': '175342407862'\n\t}, {\n\t\t'Price': '$59.97',\n\t\t'Title': \"Men's Nike Precision 5 Basketball Shoes Gym Red Black Grey Bred \"\n\t\t'Multi Size NEW',\n\t\t'asin': '134149634710'\n\t}]\n assert output == expected\n\n@requests_mock.Mocker(kw=\"mock\")\ndef test_parse_results_amz(**kwargs):\n # Read mock response data\n mock_file = open(\"tests/transfer/mocks/mock_parse_results_amz\", \"rb\")\n mock_body = mock_file.read()\n mock_file.close()\n mock_query = \"red basketball shoes\"\n \n # Invoke function, check response\n query = mock_query.replace(\" \", \"+\")\n kwargs[\"mock\"].get(f\"https://www.amazon.com/s?k={query}&page=1\", content=mock_body)\n output = parse_results_amz(mock_query, 1)\n expected = [{\n\t\t'Price': '59.49',\n\t\t'Title': 'High Top Mens Basketball Shoes Lou Williams Streetball Master ' \n\t\t\t'Breathable Non Slip Outdoor Sneakers Cushioning Workout Shoes for ' \n\t\t\t'Fitness',\n\t\t'asin': 'B083QCWF61'\n\t}, {\n\t\t'Price': '45.99',\n\t\t'Title': 'Kids Basketball Shoes High-top Sports Shoes Sneakers Durable '\n\t\t'Lace-up Non-Slip Running Shoes Secure for Little Kids Big Kids and '\n\t\t'Boys Girls',\n\t\t'asin': 'B08FWWWQ11'\n\t}, {\n\t\t'Price': '64.99',\n\t\t'Title': 'Unisex-Adult Lockdown 5 Basketball Shoe',\n\t\t'asin': 'B0817BFNC4'\n\t}, {\n\t\t'Price': '63.75',\n\t\t'Title': 'Unisex-Child Team Hustle D 9 (Gs) Sneaker',\n\t\t'asin': 'B07HHTS79M'\n\t}, {\n\t\t'Price': '74.64',\n\t\t'Title': 'Unisex-Adult D.O.N. Issue 3 Basketball Shoe',\n\t\t'asin': 'B08N8DQLS2'\n\t}, {\n\t\t'Price': '104.90',\n\t\t'Title': \"Men's Lebron Witness IV Basketball Shoes\",\n\t\t'asin': 'B07TKMMHVB'\n\t}, {\n\t\t'Price': '36.68',\n\t\t'Title': \"Unisex-Child Pre-School Jet '21 Basketball Shoe\",\n\t\t'asin': 'B08N6VRHV4'\n\t}, {\n\t\t'Price': '59.98',\n\t\t'Title': \"Men's Triple Basketball Shoe\",\n\t\t'asin': 'B08QCL8VKM'\n\t}, {\n\t\t'Price': '45.98',\n\t\t'Title': 'Unisex-Child Pre School Lockdown 4 Basketball Shoe',\n\t\t'asin': 'B07HKP12DH'\n\t}, {\n\t\t'Price': '143.72',\n\t\t'Title': \"Men's Basketball Shoes\",\n\t\t'asin': 'B07SNR7HRF'\n\t}]\n assert output == expected\n\n@requests_mock.Mocker(kw=\"mock\")\ndef test_parse_results_ws(**kwargs):\n # Read mock response data\n mock_file = open(\"tests/transfer/mocks/mock_parse_results_ws\", \"rb\")\n mock_body = mock_file.read()\n mock_file.close()\n mock_query = \"red basketball shoes\"\n \n # Invoke function, check response\n query_str = mock_query.replace(\" \", \"+\")\n url = (\n f'{WEBSHOP_URL}/search_results/{WEBSHOP_SESSION}/'\n f'{query_str}/1'\n )\n kwargs[\"mock\"].get(url, content=mock_body)\n output = parse_results_ws(mock_query, 1)\n expected = [{\n 'Price': [24.49, 39.99],\n 'Title': \"BinGoDug Men's Basketball Shoes, Men's Fashion Sneakers, Air \"\n 'Basketball Shoes for Men, Womens Basketball Shoes, Mens Basketball '\n 'Shoes, Boys Basketball Shoes, Youth Basketball Shoes Men Women',\n 'asin': 'B09GKFNQWT'\n }, {\n 'Price': [1.89, 7.58],\n 'Title': \"RQWEIN Comfortable Mesh Sneakers Men's Roading Running Shoes \"\n 'Tennis Shoes Casual Fashion Sneakers Outdoor Non Slip Gym Athletic '\n 'Sport Shoes',\n 'asin': 'B09BFY2R3R'\n }, {\n 'Price': 100.0,\n 'Title': 'PMUYBHF Womens Fashion Flat Shoes Comfortable Running Shoes '\n 'Sneakers Tennis Athletic Shoe Casual Walking Shoes',\n 'asin': 'B09P87V3LZ'\n }, {\n 'Price': 100.0,\n 'Title': 'PMUYBHF Fashion Travel Shoes Jogging Walking Sneakers Air Cushion '\n 'Platform Loafers Air Cushion Mesh Shoes Walking Dance Shoes',\n 'asin': 'B09N6SNKC1'\n }, {\n 'Price': 100.0,\n 'Title': \"PMUYBHF Women's Ballet Flats Walking Flats Shoes Dressy Work Low \"\n 'Wedge Arch Suport Flats Shoes Slip On Dress Shoes',\n 'asin': 'B09N6X5S74'\n }, {\n 'Price': 100.0,\n 'Title': \"PWKSELW High-top Men's Basketball Shoes Outdoor Sports Shoes \"\n 'Cushioning Training Shoes Casual Running Shoes',\n 'asin': 'B09MDB9V5W'\n }, {\n 'Price': 100.0,\n 'Title': \"Women's Flat Shoes Classic Round Toe Slip Office Black Ballet \"\n 'Flats Walking Flats Shoes Casual Ballet Flats',\n 'asin': 'B09N6PDFRF'\n }, {\n 'Price': 100.0,\n 'Title': \"Women's Mid-Calf Boots Wide Calf Boots for Women Fashion Zipper \"\n 'Womens Shoes Pu Leather Casual Boots Womens Slip-On Womens Flat '\n \"Shoes Med Heel Womens' Boots Winter Snow Boot Comfy Boots(,5.5)\",\n 'asin': 'B09N8ZHFNM'\n }, {\n 'Price': 100.0,\n 'Title': 'PMUYBHF Womens Leisure Fitness Running Sport Warm Sneakers Shoes '\n 'Slip-On Mule Sneakers Womens Mules',\n 'asin': 'B09P87DWGR'\n }, {\n 'Price': 100.0,\n 'Title': 'Men Dress Shoes Leather Modern Classic Business Shoes Lace Up '\n 'Classic Office Shoes Business Formal Shoes for Men',\n 'asin': 'B09R9MMTKR'\n }]\n assert output == expected\n\ndef test_convert_dict_to_actions():\n # Test RESULTS page type\n asin = \"334490012932\"\n page_num = 2\n products = [{\n 'asin': '125331076844',\n 'Title': 'Modern Tall Torchiere Floor Lamp Brushed Nickel Chrome Metal Decor Living Room',\n 'Price': '$129.95'\n }, {\n 'asin': '125109985453',\n 'Title': 'Floor Lamps Set of 2 Polished Steel Crystal Glass for Living Room Bedroom',\n 'Price': '$179.99'\n }, {\n 'asin': '125265434055',\n 'Title': 'Floor Lamp Nickel/Polished Concrete Finish with Off-White Linen Fabric Shade',\n 'Price': '$130.68'\n }, {\n 'asin': '195197281169',\n 'Title': 'New ListingVintage Mid Century Modern Glass Amber Globe Tension Pole Floor Lamp Light',\n 'Price': '$165.00'\n }, {\n 'asin': '195197512929',\n 'Title': 'New ListingVTG Brass Floor Lamp Glass Shade 63.5\" Tall 12\" Diameter Gla\n# ... truncated ...","source_hash":"2f1ed677907f992ff0bf377061e7a82ff04886c655a7dff164bfed0dcddc7d59","truncated":true} {"repo_id":"BOLAA","entity_id":"py:webshop.tests.transfer.test_predict_help.test_parse_item_page_ws","uri":"program://BOLAA/function/webshop.tests.transfer.test_predict_help.test_parse_item_page_ws#L14-L115","kind":"function","name":"test_parse_item_page_ws","path":"webshop/tests/transfer/test_predict_help.py","language":"python","start_line":14,"end_line":115,"context_start_line":1,"context_end_line":135,"code":"import json\nimport pytest\nimport requests_mock\n\nfrom transfer.predict_help import (\n convert_dict_to_actions,\n parse_item_page_amz, parse_results_amz,\n parse_item_page_ebay, parse_results_ebay,\n parse_item_page_ws, parse_results_ws,\n Page, WEBSHOP_URL, WEBSHOP_SESSION\n)\n\n@requests_mock.Mocker(kw=\"mock\")\ndef test_parse_item_page_ws(**kwargs):\n # Read mock response data\n mock_file = open(\"tests/transfer/mocks/mock_parse_item_page_ws\", \"rb\")\n mock_body = mock_file.read()\n mock_file.close()\n\n mock_desc_file = open(\"tests/transfer/mocks/mock_parse_item_page_ws_desc\", \"rb\")\n mock_desc_body = mock_desc_file.read()\n mock_desc_file.close()\n\n mock_feat_file = open(\"tests/transfer/mocks/mock_parse_item_page_ws_feat\", \"rb\")\n mock_feat_body = mock_feat_file.read()\n mock_feat_file.close()\n\n mock_asin = \"B09P87V3LZ\"\n mock_query = \"red basketball shoes\"\n mock_options = {}\n\n # Invoke function, check response\n query_str = '+'.join(mock_query.split())\n options_str = json.dumps(mock_options)\n url = (\n f\"{WEBSHOP_URL}/item_page/{WEBSHOP_SESSION}/\"\n f\"{mock_asin}/{query_str}/1/{options_str}\"\n )\n url_desc = (\n f\"{WEBSHOP_URL}/item_sub_page/{WEBSHOP_SESSION}/\"\n f\"{mock_asin}/{query_str}/1/Description/{options_str}\"\n )\n url_feat = (\n f\"{WEBSHOP_URL}/item_sub_page/{WEBSHOP_SESSION}/\"\n f\"{mock_asin}/{query_str}/1/Features/{options_str}\"\n )\n print(f\"Item Page URL: {url}\")\n print(f\"Item Description URL: {url_desc}\")\n print(f\"Item Features URL: {url_feat}\")\n\n kwargs[\"mock\"].get(url, content=mock_body)\n kwargs[\"mock\"].get(url_desc, content=mock_desc_body)\n kwargs[\"mock\"].get(url_feat, content=mock_feat_body)\n\n output = parse_item_page_ws(mock_asin, mock_query, 1, mock_options)\n expected = {\n 'MainImage': 'https://m.media-amazon.com/images/I/51ltvkzGhGL.jpg',\n 'Price': '100.0',\n 'Rating': 'N.A.',\n 'Title': 'PMUYBHF Womens Fashion Flat Shoes Comfortable Running Shoes ' \n 'Sneakers Tennis Athletic Shoe Casual Walking Shoes',\n 'asin': mock_asin,\n 'option_to_image': {\n '6.5': 'http://3.83.245.205:3000/item_page/abc/B09P87V3LZ/%5B%27red%27%2C%20%27basketball%27%2C%20%27shoes%27%5D/1/%7B%27size%27:%20%276.5%27%7D',\n '7.5': 'http://3.83.245.205:3000/item_page/abc/B09P87V3LZ/%5B%27red%27%2C%20%27basketball%27%2C%20%27shoes%27%5D/1/%7B%27size%27:%20%277.5%27%7D',\n '8': 'http://3.83.245.205:3000/item_page/abc/B09P87V3LZ/%5B%27red%27%2C%20%27basketball%27%2C%20%27shoes%27%5D/1/%7B%27size%27:%20%278%27%7D',\n '8.5': 'http://3.83.245.205:3000/item_page/abc/B09P87V3LZ/%5B%27red%27%2C%20%27basketball%27%2C%20%27shoes%27%5D/1/%7B%27size%27:%20%278.5%27%7D',\n '9': 'http://3.83.245.205:3000/item_page/abc/B09P87V3LZ/%5B%27red%27%2C%20%27basketball%27%2C%20%27shoes%27%5D/1/%7B%27size%27:%20%279%27%7D',\n 'black': 'http://3.83.245.205:3000/item_page/abc/B09P87V3LZ/%5B%27red%27%2C%20%27basketball%27%2C%20%27shoes%27%5D/1/%7B%27color%27:%20%27black%27%7D',\n 'purple': 'http://3.83.245.205:3000/item_page/abc/B09P87V3LZ/%5B%27red%27%2C%20%27basketball%27%2C%20%27shoes%27%5D/1/%7B%27color%27:%20%27purple%27%7D',\n 'red': 'http://3.83.245.205:3000/item_page/abc/B09P87V3LZ/%5B%27red%27%2C%20%27basketball%27%2C%20%27shoes%27%5D/1/%7B%27color%27:%20%27red%27%7D'\n },\n 'options': {\n 'color': ['black', 'purple', 'red'],\n 'size': ['6.5', '7.5', '8', '8.5', '9']\n },\n 'BulletPoints': 'Pure Running Shoe\\nComfort Flat Sneakers\\n[FEATURES]: Soles with unique non-slip pattern, it has great ' \n 'abrasion resistant and provide protection when you walking or running. (Pure Running Shoe Mesh Walking Shoes Fashion ' \n 'Sneakers Slip On Sneakers Wedge Platform Loafers Modern Walking Shoes Sock Sneakers Platform Loafers Shoes Non Slip ' \n 'Running Shoes Athletic Tennis Shoes Blade Type Sneakers Lace-up Sneaker) sole\\n[WIDE ANKLE DESIGN]: Perfect accord with human body ' \n 'engineering, green, healthy concept design make the walking shoes wear more comfortable, wide width wlking shoes. (Low ' \n 'Top Walking Shoes Fashion Canvas Sneakers Slip On Shoes Casual Walking Shoes Hidden Wedge Sneaker Low Top Canvas ' \n 'Sneakers Lace-up Classic Casual Shoes Walking Tennis Shoes Lightweight Casual Sneakers Slip on Sock Sneakers Air ' \n 'Cushion Platform Loafers Slip-On Mule Sneaker )\\n[CUSHION WITH ARCH SUPPORT]: Gives you a comfort for all day ' \n 'long. Wear these lightweight walking shoes, let every step of moving on a comfortable feeling. (Fashion Casual Shoes ' \n 'Athletic Workout Shoes Fitness Sneaker Athletic Running Shoes Air Cushion Sneakers Stylish Athletic Shoes Lace Up ' \n 'Canvas Shoes Slip on Walking Shoe Fashion Sneakers Low Top Classic Sneakers Comfort Fall Shoes Memory Foam Slip On ' \n 'Sneakers Air Cushion Sneakers Running Walking Shoes)\\n[NON-SLIP SOLE]: Made from ultra soft and lightweight RUBBER ' \n 'material,with the function of shock absorbing and cushioning,offering the best durability and traction. (Wedge ' \n 'Sneakers Walking Tennis Shoes Slip On Running Shoes Lightweight Fashion Sneakers Fashion Travel Shoes Walking ' \n 'Running Shoes Non Slip Running Shoes Athletic Tennis Sneakers Sports Walking Shoes Platform Fashion Sneaker ' \n 'Memory Foam Tennis Sneakers Running Jogging Shoes Sock Sneakers Canvas Fashion Sneakers)\\n[OCCASIONS]: Ultra lightweight design provides actual ' \n 'feelings of being barefooted and like walking on the feather, perfect for walking, hiking, bike riding, working, ' \n 'shopping, indoor, outdoor, casual, sports, travel, exercise, vacation, and etc. (Flat Fashion Sneakers Lightweight ' \n 'Walking Sneakers Platform Loafers Sport Running Shoes Casual Flat Loafers Slip-On Sneaker Casual Walking Shoes High Top ' \n 'Canvas Sneakers Lace up Sneakers Workout Walking Shoes Tennis Fitness Sneaker)\\n' \n '[Customers Are Our Priority]: We follow the principle of customer first, so if you encounter any problems after ' \n 'buying shoes, we will try our best to solve them for you. (Breathable Air Cushion Sneakers Walking Tennis Shoes Air ' \n 'Athletic Running Shoes Air Cushion Shoes Mesh Sneakers Fashion Tennis Shoes Jogging Walking Sneakers Breathable ' \n 'Casual Sneakers Fashion Walking Shoes Athletic Running Sneakers Walking Work Shoes Air Running Shoes Slip on ' \n 'Sneakers Mesh Walking Shoes)',\n 'Description': 'Here Are The Things You Want To Knowa─=≡Σ(((つ̀ώ)つSTORE INTRODUCTION:>>>>Our store helps our customers improve their ' \n 'quality of life~As a distributor, we value quality and service.Focus on the high quality and durability of the ' \n 'product.Committed to creating a store that satisfies and reassures our customers.TIPS:>>>>1. Please allow minor errors ' \n 'in the data due to manual measurements.2. Due to the color settings of the display, the actual color may be slightly ' \n 'different from the online image.QUALITY PROMISE:>>>>Our goal is to continuously provide a range of quality products.We ' \n 'place a huge emphasis on the values of quality and reliability.We have always insisted on fulfilling this ' \n 'commitment.In short, we want our customers to have the same great product experience every time and be trusted to deliver ' \n 'on this commitment.Please give us a chance to serve you.OTHER:>>>>athletic sneaker laces athletic sneakers white ' \n 'athletic sneakers for women clearance leather Sneaker leather sneakers women leather sneakers for menleather sneaker laces ' \n 'leather sneaker platform basketball shoes basketball shoes for men basketball shoe laces basketball shoe grip basketball ' \n 'shoes for women fitness shoes for men fitness shoes women workout fitness shoes women fitness shoes women size 5 ' \n 'fitness shoes men workout fitness shoes for men high top sneakers for women walking shoes sneakers with arch support for women'\n }\n assert output == expected\n\n@requests_mock.Mocker(kw=\"mock\")\ndef test_parse_item_page_ebay(**kwargs):\n # Read mock response data\n mock_file = open(\"tests/transfer/mocks/mock_parse_item_page_ebay\", \"rb\")\n mock_body = mock_file.read()\n mock_file.close()\n mock_asin = \"403760625150\"\n\n # Invoke function, check response\n kwargs[\"mock\"].get(f\"https://www.ebay.com/itm/{mock_asin}\", content=mock_body)\n output = parse_item_page_ebay(mock_asin)\n expected = {\n 'BulletPoints': 'Item specifics Condition:New without box: A brand-new, ' \n 'unused, and unworn item (including handmade items) that is ' \n 'not in ... Read moreabout the conditionNew without box: A ' \n 'brand-new, unused, and unworn item (including handmade ' \n 'items) that is not in original packaging or may be missing ' \n 'original packaging materials (such as the original box or ' \n 'bag). The original tags may not be attached. For example, ' ","source_hash":"2f1ed677907f992ff0bf377061e7a82ff04886c655a7dff164bfed0dcddc7d59","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.tests.transfer.test_predict_help.test_parse_item_page_ebay","uri":"program://BOLAA/function/webshop.tests.transfer.test_predict_help.test_parse_item_page_ebay#L118-L160","kind":"function","name":"test_parse_item_page_ebay","path":"webshop/tests/transfer/test_predict_help.py","language":"python","start_line":118,"end_line":160,"context_start_line":98,"context_end_line":180,"code":" 'buying shoes, we will try our best to solve them for you. (Breathable Air Cushion Sneakers Walking Tennis Shoes Air ' \n 'Athletic Running Shoes Air Cushion Shoes Mesh Sneakers Fashion Tennis Shoes Jogging Walking Sneakers Breathable ' \n 'Casual Sneakers Fashion Walking Shoes Athletic Running Sneakers Walking Work Shoes Air Running Shoes Slip on ' \n 'Sneakers Mesh Walking Shoes)',\n 'Description': 'Here Are The Things You Want To Knowa─=≡Σ(((つ̀ώ)つSTORE INTRODUCTION:>>>>Our store helps our customers improve their ' \n 'quality of life~As a distributor, we value quality and service.Focus on the high quality and durability of the ' \n 'product.Committed to creating a store that satisfies and reassures our customers.TIPS:>>>>1. Please allow minor errors ' \n 'in the data due to manual measurements.2. Due to the color settings of the display, the actual color may be slightly ' \n 'different from the online image.QUALITY PROMISE:>>>>Our goal is to continuously provide a range of quality products.We ' \n 'place a huge emphasis on the values of quality and reliability.We have always insisted on fulfilling this ' \n 'commitment.In short, we want our customers to have the same great product experience every time and be trusted to deliver ' \n 'on this commitment.Please give us a chance to serve you.OTHER:>>>>athletic sneaker laces athletic sneakers white ' \n 'athletic sneakers for women clearance leather Sneaker leather sneakers women leather sneakers for menleather sneaker laces ' \n 'leather sneaker platform basketball shoes basketball shoes for men basketball shoe laces basketball shoe grip basketball ' \n 'shoes for women fitness shoes for men fitness shoes women workout fitness shoes women fitness shoes women size 5 ' \n 'fitness shoes men workout fitness shoes for men high top sneakers for women walking shoes sneakers with arch support for women'\n }\n assert output == expected\n\n@requests_mock.Mocker(kw=\"mock\")\ndef test_parse_item_page_ebay(**kwargs):\n # Read mock response data\n mock_file = open(\"tests/transfer/mocks/mock_parse_item_page_ebay\", \"rb\")\n mock_body = mock_file.read()\n mock_file.close()\n mock_asin = \"403760625150\"\n\n # Invoke function, check response\n kwargs[\"mock\"].get(f\"https://www.ebay.com/itm/{mock_asin}\", content=mock_body)\n output = parse_item_page_ebay(mock_asin)\n expected = {\n 'BulletPoints': 'Item specifics Condition:New without box: A brand-new, ' \n 'unused, and unworn item (including handmade items) that is ' \n 'not in ... Read moreabout the conditionNew without box: A ' \n 'brand-new, unused, and unworn item (including handmade ' \n 'items) that is not in original packaging or may be missing ' \n 'original packaging materials (such as the original box or ' \n 'bag). The original tags may not be attached. For example, ' \n 'new shoes (with absolutely no signs of wear) that are no ' \n 'longer in their original box fall into this category. See ' \n 'all condition definitionsopens in a new window or tab ' \n 'Closure:Lace Up US Shoe Size:10 Occasion:Activewear, Casual ' \n 'Silhouette:Puma Fabric Type:Mesh Vintage:No Cushioning ' \n 'Level:Moderate Department:Men Style:Sneaker Outsole ' \n 'Material:Rubber Features:Breathable, Comfort, Cushioned, ' \n 'Performance Season:Fall, Spring, Summer, Winter ' \n 'Idset_Mpn:193990-21 Shoe Shaft Style:Low Top Style ' \n 'Code:193990-16 Pattern:Solid Character:J. Cole Lining ' \n 'Material:Synthetic Color:Red Brand:PUMA Type:Athletic ' \n 'Customized:No Model:RS-Dreamer Theme:Sports Shoe ' \n 'Width:Standard Upper Material:Textile Insole ' \n 'Material:Synthetic Performance/Activity:Basketball Product ' \n 'Line:Puma Dreamer',\n 'Description': 'N/A',\n 'MainImage': 'https://i.ebayimg.com/images/g/4ggAAOSwpk1ioTWz/s-l500.jpg',\n 'Price': 'N/A',\n 'Rating': None,\n 'Title': \"Puma RS-Dreamer J. Cole Basketball Shoes Red 193990-16 Men's Size 10.0\",\n 'asin': '403760625150',\n 'option_to_image': {},\n 'options': {},\n }\n assert output == expected\n\n@requests_mock.Mocker(kw=\"mock\")\ndef test_parse_item_page_amz(**kwargs):\n # Read mock response data\n mock_file = open(\"tests/transfer/mocks/mock_parse_item_page_amz\", \"rb\")\n mock_body = mock_file.read()\n mock_file.close()\n mock_asin = \"B073WRF565\"\n\n # Invoke function, check response\n kwargs[\"mock\"].get(f\"https://www.amazon.com/dp/{mock_asin}\", content=mock_body)\n output = parse_item_page_amz(mock_asin)\n expected = {\n 'asin': 'B073WRF565',\n 'Title': 'Amazon Basics Foldable 14\" Black Metal Platform Bed Frame with Tool-Free Assembly No Box Spring Needed - Full',\n 'Price': 'N/A',\n 'Rating': '4.8 out of 5 stars',\n 'BulletPoints': ' \\n About this item ' \n 'Product dimensions: 75\" L x 54\" W x 14\" H | Weight: 41.4 pounds ' \n 'Designed for sleepers up to 250 pounds Full size platform bed frame offers a quiet, noise-free, ' ","source_hash":"2f1ed677907f992ff0bf377061e7a82ff04886c655a7dff164bfed0dcddc7d59","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.tests.transfer.test_predict_help.test_parse_item_page_amz","uri":"program://BOLAA/function/webshop.tests.transfer.test_predict_help.test_parse_item_page_amz#L163-L190","kind":"function","name":"test_parse_item_page_amz","path":"webshop/tests/transfer/test_predict_help.py","language":"python","start_line":163,"end_line":190,"context_start_line":143,"context_end_line":210,"code":" 'Performance Season:Fall, Spring, Summer, Winter ' \n 'Idset_Mpn:193990-21 Shoe Shaft Style:Low Top Style ' \n 'Code:193990-16 Pattern:Solid Character:J. Cole Lining ' \n 'Material:Synthetic Color:Red Brand:PUMA Type:Athletic ' \n 'Customized:No Model:RS-Dreamer Theme:Sports Shoe ' \n 'Width:Standard Upper Material:Textile Insole ' \n 'Material:Synthetic Performance/Activity:Basketball Product ' \n 'Line:Puma Dreamer',\n 'Description': 'N/A',\n 'MainImage': 'https://i.ebayimg.com/images/g/4ggAAOSwpk1ioTWz/s-l500.jpg',\n 'Price': 'N/A',\n 'Rating': None,\n 'Title': \"Puma RS-Dreamer J. Cole Basketball Shoes Red 193990-16 Men's Size 10.0\",\n 'asin': '403760625150',\n 'option_to_image': {},\n 'options': {},\n }\n assert output == expected\n\n@requests_mock.Mocker(kw=\"mock\")\ndef test_parse_item_page_amz(**kwargs):\n # Read mock response data\n mock_file = open(\"tests/transfer/mocks/mock_parse_item_page_amz\", \"rb\")\n mock_body = mock_file.read()\n mock_file.close()\n mock_asin = \"B073WRF565\"\n\n # Invoke function, check response\n kwargs[\"mock\"].get(f\"https://www.amazon.com/dp/{mock_asin}\", content=mock_body)\n output = parse_item_page_amz(mock_asin)\n expected = {\n 'asin': 'B073WRF565',\n 'Title': 'Amazon Basics Foldable 14\" Black Metal Platform Bed Frame with Tool-Free Assembly No Box Spring Needed - Full',\n 'Price': 'N/A',\n 'Rating': '4.8 out of 5 stars',\n 'BulletPoints': ' \\n About this item ' \n 'Product dimensions: 75\" L x 54\" W x 14\" H | Weight: 41.4 pounds ' \n 'Designed for sleepers up to 250 pounds Full size platform bed frame offers a quiet, noise-free, ' \n 'supportive foundation for a mattress. No box spring needed Folding mechanism makes the frame easy ' \n 'to store and move in tight spaces Provides extra under-the-bed storage space with a vertical clea' \n 'rance of about 13 inches \\n › See more product details ',\n 'Description': 'Amazon Basics Foldable, 14\" Black Metal Platform Bed Frame with Tool-Free Assembly, No Box Spring Needed - Full Amazon Basics',\n 'MainImage': 'https://images-na.ssl-images-amazon.com/images/I/41WIGwt-asL.__AC_SY300_SX300_QL70_FMwebp_.jpg',\n 'options': {'size': ['Twin', 'Full', 'Queen', 'King'],\n 'style': ['14-Inch', '18-Inch']},\n 'option_to_image': {}\n }\n assert output == expected\n\n@requests_mock.Mocker(kw=\"mock\")\ndef test_parse_results_ebay(**kwargs):\n # Read mock response data\n mock_file = open(\"tests/transfer/mocks/mock_parse_results_ebay\", \"rb\")\n mock_body = mock_file.read()\n mock_file.close()\n mock_query = \"red basketball shoes\"\n \n # Invoke function, check response\n query = mock_query.replace(\" \", \"+\")\n kwargs[\"mock\"].get(f'https://www.ebay.com/sch/i.html?_nkw={query}&_pgn=1', content=mock_body)\n output = parse_results_ebay(mock_query, 1)\n expected = [{\n\t\t'Price': ['100.00', '150.00'],\n\t\t'Title': \"Reebok Answer IV Men's Basketball Shoes\",\n\t\t'asin': '175065123030'\n\t}, {\n\t\t'Price': '$119.90',\n\t\t'Title': \"Air Jordan Stay Loyal Shoes Black Red White DB2884-001 Men's Multi \"","source_hash":"2f1ed677907f992ff0bf377061e7a82ff04886c655a7dff164bfed0dcddc7d59","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.tests.transfer.test_predict_help.test_parse_results_ebay","uri":"program://BOLAA/function/webshop.tests.transfer.test_predict_help.test_parse_results_ebay#L193-L252","kind":"function","name":"test_parse_results_ebay","path":"webshop/tests/transfer/test_predict_help.py","language":"python","start_line":193,"end_line":252,"context_start_line":173,"context_end_line":272,"code":" expected = {\n 'asin': 'B073WRF565',\n 'Title': 'Amazon Basics Foldable 14\" Black Metal Platform Bed Frame with Tool-Free Assembly No Box Spring Needed - Full',\n 'Price': 'N/A',\n 'Rating': '4.8 out of 5 stars',\n 'BulletPoints': ' \\n About this item ' \n 'Product dimensions: 75\" L x 54\" W x 14\" H | Weight: 41.4 pounds ' \n 'Designed for sleepers up to 250 pounds Full size platform bed frame offers a quiet, noise-free, ' \n 'supportive foundation for a mattress. No box spring needed Folding mechanism makes the frame easy ' \n 'to store and move in tight spaces Provides extra under-the-bed storage space with a vertical clea' \n 'rance of about 13 inches \\n › See more product details ',\n 'Description': 'Amazon Basics Foldable, 14\" Black Metal Platform Bed Frame with Tool-Free Assembly, No Box Spring Needed - Full Amazon Basics',\n 'MainImage': 'https://images-na.ssl-images-amazon.com/images/I/41WIGwt-asL.__AC_SY300_SX300_QL70_FMwebp_.jpg',\n 'options': {'size': ['Twin', 'Full', 'Queen', 'King'],\n 'style': ['14-Inch', '18-Inch']},\n 'option_to_image': {}\n }\n assert output == expected\n\n@requests_mock.Mocker(kw=\"mock\")\ndef test_parse_results_ebay(**kwargs):\n # Read mock response data\n mock_file = open(\"tests/transfer/mocks/mock_parse_results_ebay\", \"rb\")\n mock_body = mock_file.read()\n mock_file.close()\n mock_query = \"red basketball shoes\"\n \n # Invoke function, check response\n query = mock_query.replace(\" \", \"+\")\n kwargs[\"mock\"].get(f'https://www.ebay.com/sch/i.html?_nkw={query}&_pgn=1', content=mock_body)\n output = parse_results_ebay(mock_query, 1)\n expected = [{\n\t\t'Price': ['100.00', '150.00'],\n\t\t'Title': \"Reebok Answer IV Men's Basketball Shoes\",\n\t\t'asin': '175065123030'\n\t}, {\n\t\t'Price': '$119.90',\n\t\t'Title': \"Air Jordan Stay Loyal Shoes Black Red White DB2884-001 Men's Multi \"\n\t\t'Size NEW',\n\t\t'asin': '265672133690'\n\t}, {\n\t\t'Price': '$100.00',\n\t\t'Title': \"Fila Men's Stackhouse Spaghetti Basketball Shoes Black Red White \"\n\t\t'1BM01788-113',\n\t\t'asin': '175282509234'\n\t}, {\n\t\t'Price': ['61.99',\n\t\t\t'85.99'\n\t\t],\n\t\t'Title': 'Puma Disc Rebirth 19481203 Mens Black Red Synthetic Athletic '\n\t\t'Basketball Shoes',\n\t\t'asin': '313944854658'\n\t}, {\n\t\t'Price': '$0.01',\n\t\t'Title': \"Puma RS-Dreamer J. Cole Basketball Shoes Red 193990-16 Men's Size \"\n\t\t'10.0',\n\t\t'asin': '403760625150'\n\t}, {\n\t\t'Price': '$45.00',\n\t\t'Title': 'Nike Mens 9.5 PG 5 Maroon Red White Basketball Shoes Sneaker DM '\n\t\t'5045–601 Flaw',\n\t\t'asin': '115456853186'\n\t}, {\n\t\t'Price': ['114.90',\n\t\t\t'119.90'\n\t\t],\n\t\t'Title': \"Air Jordan Stay Loyal Shoes White Black Red DB2884-106 Men's Multi \"\n\t\t'Size NEW',\n\t\t'asin': '155046831159'\n\t}, {\n\t\t'Price': '$8.99',\n\t\t'Title': \"Harden Volume 3 Men's Basketball Shoes Size 9.5\",\n\t\t'asin': '175342407862'\n\t}, {\n\t\t'Price': '$59.97',\n\t\t'Title': \"Men's Nike Precision 5 Basketball Shoes Gym Red Black Grey Bred \"\n\t\t'Multi Size NEW',\n\t\t'asin': '134149634710'\n\t}]\n assert output == expected\n\n@requests_mock.Mocker(kw=\"mock\")\ndef test_parse_results_amz(**kwargs):\n # Read mock response data\n mock_file = open(\"tests/transfer/mocks/mock_parse_results_amz\", \"rb\")\n mock_body = mock_file.read()\n mock_file.close()\n mock_query = \"red basketball shoes\"\n \n # Invoke function, check response\n query = mock_query.replace(\" \", \"+\")\n kwargs[\"mock\"].get(f\"https://www.amazon.com/s?k={query}&page=1\", content=mock_body)\n output = parse_results_amz(mock_query, 1)\n expected = [{\n\t\t'Price': '59.49',\n\t\t'Title': 'High Top Mens Basketball Shoes Lou Williams Streetball Master ' \n\t\t\t'Breathable Non Slip Outdoor Sneakers Cushioning Workout Shoes for ' \n\t\t\t'Fitness',\n\t\t'asin': 'B083QCWF61'\n\t}, {","source_hash":"2f1ed677907f992ff0bf377061e7a82ff04886c655a7dff164bfed0dcddc7d59","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.tests.transfer.test_predict_help.test_parse_results_amz","uri":"program://BOLAA/function/webshop.tests.transfer.test_predict_help.test_parse_results_amz#L255-L311","kind":"function","name":"test_parse_results_amz","path":"webshop/tests/transfer/test_predict_help.py","language":"python","start_line":255,"end_line":311,"context_start_line":235,"context_end_line":331,"code":"\t}, {\n\t\t'Price': ['114.90',\n\t\t\t'119.90'\n\t\t],\n\t\t'Title': \"Air Jordan Stay Loyal Shoes White Black Red DB2884-106 Men's Multi \"\n\t\t'Size NEW',\n\t\t'asin': '155046831159'\n\t}, {\n\t\t'Price': '$8.99',\n\t\t'Title': \"Harden Volume 3 Men's Basketball Shoes Size 9.5\",\n\t\t'asin': '175342407862'\n\t}, {\n\t\t'Price': '$59.97',\n\t\t'Title': \"Men's Nike Precision 5 Basketball Shoes Gym Red Black Grey Bred \"\n\t\t'Multi Size NEW',\n\t\t'asin': '134149634710'\n\t}]\n assert output == expected\n\n@requests_mock.Mocker(kw=\"mock\")\ndef test_parse_results_amz(**kwargs):\n # Read mock response data\n mock_file = open(\"tests/transfer/mocks/mock_parse_results_amz\", \"rb\")\n mock_body = mock_file.read()\n mock_file.close()\n mock_query = \"red basketball shoes\"\n \n # Invoke function, check response\n query = mock_query.replace(\" \", \"+\")\n kwargs[\"mock\"].get(f\"https://www.amazon.com/s?k={query}&page=1\", content=mock_body)\n output = parse_results_amz(mock_query, 1)\n expected = [{\n\t\t'Price': '59.49',\n\t\t'Title': 'High Top Mens Basketball Shoes Lou Williams Streetball Master ' \n\t\t\t'Breathable Non Slip Outdoor Sneakers Cushioning Workout Shoes for ' \n\t\t\t'Fitness',\n\t\t'asin': 'B083QCWF61'\n\t}, {\n\t\t'Price': '45.99',\n\t\t'Title': 'Kids Basketball Shoes High-top Sports Shoes Sneakers Durable '\n\t\t'Lace-up Non-Slip Running Shoes Secure for Little Kids Big Kids and '\n\t\t'Boys Girls',\n\t\t'asin': 'B08FWWWQ11'\n\t}, {\n\t\t'Price': '64.99',\n\t\t'Title': 'Unisex-Adult Lockdown 5 Basketball Shoe',\n\t\t'asin': 'B0817BFNC4'\n\t}, {\n\t\t'Price': '63.75',\n\t\t'Title': 'Unisex-Child Team Hustle D 9 (Gs) Sneaker',\n\t\t'asin': 'B07HHTS79M'\n\t}, {\n\t\t'Price': '74.64',\n\t\t'Title': 'Unisex-Adult D.O.N. Issue 3 Basketball Shoe',\n\t\t'asin': 'B08N8DQLS2'\n\t}, {\n\t\t'Price': '104.90',\n\t\t'Title': \"Men's Lebron Witness IV Basketball Shoes\",\n\t\t'asin': 'B07TKMMHVB'\n\t}, {\n\t\t'Price': '36.68',\n\t\t'Title': \"Unisex-Child Pre-School Jet '21 Basketball Shoe\",\n\t\t'asin': 'B08N6VRHV4'\n\t}, {\n\t\t'Price': '59.98',\n\t\t'Title': \"Men's Triple Basketball Shoe\",\n\t\t'asin': 'B08QCL8VKM'\n\t}, {\n\t\t'Price': '45.98',\n\t\t'Title': 'Unisex-Child Pre School Lockdown 4 Basketball Shoe',\n\t\t'asin': 'B07HKP12DH'\n\t}, {\n\t\t'Price': '143.72',\n\t\t'Title': \"Men's Basketball Shoes\",\n\t\t'asin': 'B07SNR7HRF'\n\t}]\n assert output == expected\n\n@requests_mock.Mocker(kw=\"mock\")\ndef test_parse_results_ws(**kwargs):\n # Read mock response data\n mock_file = open(\"tests/transfer/mocks/mock_parse_results_ws\", \"rb\")\n mock_body = mock_file.read()\n mock_file.close()\n mock_query = \"red basketball shoes\"\n \n # Invoke function, check response\n query_str = mock_query.replace(\" \", \"+\")\n url = (\n f'{WEBSHOP_URL}/search_results/{WEBSHOP_SESSION}/'\n f'{query_str}/1'\n )\n kwargs[\"mock\"].get(url, content=mock_body)\n output = parse_results_ws(mock_query, 1)\n expected = [{\n 'Price': [24.49, 39.99],\n 'Title': \"BinGoDug Men's Basketball Shoes, Men's Fashion Sneakers, Air \"","source_hash":"2f1ed677907f992ff0bf377061e7a82ff04886c655a7dff164bfed0dcddc7d59","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.tests.transfer.test_predict_help.test_parse_results_ws","uri":"program://BOLAA/function/webshop.tests.transfer.test_predict_help.test_parse_results_ws#L314-L383","kind":"function","name":"test_parse_results_ws","path":"webshop/tests/transfer/test_predict_help.py","language":"python","start_line":314,"end_line":383,"context_start_line":294,"context_end_line":403,"code":"\t}, {\n\t\t'Price': '36.68',\n\t\t'Title': \"Unisex-Child Pre-School Jet '21 Basketball Shoe\",\n\t\t'asin': 'B08N6VRHV4'\n\t}, {\n\t\t'Price': '59.98',\n\t\t'Title': \"Men's Triple Basketball Shoe\",\n\t\t'asin': 'B08QCL8VKM'\n\t}, {\n\t\t'Price': '45.98',\n\t\t'Title': 'Unisex-Child Pre School Lockdown 4 Basketball Shoe',\n\t\t'asin': 'B07HKP12DH'\n\t}, {\n\t\t'Price': '143.72',\n\t\t'Title': \"Men's Basketball Shoes\",\n\t\t'asin': 'B07SNR7HRF'\n\t}]\n assert output == expected\n\n@requests_mock.Mocker(kw=\"mock\")\ndef test_parse_results_ws(**kwargs):\n # Read mock response data\n mock_file = open(\"tests/transfer/mocks/mock_parse_results_ws\", \"rb\")\n mock_body = mock_file.read()\n mock_file.close()\n mock_query = \"red basketball shoes\"\n \n # Invoke function, check response\n query_str = mock_query.replace(\" \", \"+\")\n url = (\n f'{WEBSHOP_URL}/search_results/{WEBSHOP_SESSION}/'\n f'{query_str}/1'\n )\n kwargs[\"mock\"].get(url, content=mock_body)\n output = parse_results_ws(mock_query, 1)\n expected = [{\n 'Price': [24.49, 39.99],\n 'Title': \"BinGoDug Men's Basketball Shoes, Men's Fashion Sneakers, Air \"\n 'Basketball Shoes for Men, Womens Basketball Shoes, Mens Basketball '\n 'Shoes, Boys Basketball Shoes, Youth Basketball Shoes Men Women',\n 'asin': 'B09GKFNQWT'\n }, {\n 'Price': [1.89, 7.58],\n 'Title': \"RQWEIN Comfortable Mesh Sneakers Men's Roading Running Shoes \"\n 'Tennis Shoes Casual Fashion Sneakers Outdoor Non Slip Gym Athletic '\n 'Sport Shoes',\n 'asin': 'B09BFY2R3R'\n }, {\n 'Price': 100.0,\n 'Title': 'PMUYBHF Womens Fashion Flat Shoes Comfortable Running Shoes '\n 'Sneakers Tennis Athletic Shoe Casual Walking Shoes',\n 'asin': 'B09P87V3LZ'\n }, {\n 'Price': 100.0,\n 'Title': 'PMUYBHF Fashion Travel Shoes Jogging Walking Sneakers Air Cushion '\n 'Platform Loafers Air Cushion Mesh Shoes Walking Dance Shoes',\n 'asin': 'B09N6SNKC1'\n }, {\n 'Price': 100.0,\n 'Title': \"PMUYBHF Women's Ballet Flats Walking Flats Shoes Dressy Work Low \"\n 'Wedge Arch Suport Flats Shoes Slip On Dress Shoes',\n 'asin': 'B09N6X5S74'\n }, {\n 'Price': 100.0,\n 'Title': \"PWKSELW High-top Men's Basketball Shoes Outdoor Sports Shoes \"\n 'Cushioning Training Shoes Casual Running Shoes',\n 'asin': 'B09MDB9V5W'\n }, {\n 'Price': 100.0,\n 'Title': \"Women's Flat Shoes Classic Round Toe Slip Office Black Ballet \"\n 'Flats Walking Flats Shoes Casual Ballet Flats',\n 'asin': 'B09N6PDFRF'\n }, {\n 'Price': 100.0,\n 'Title': \"Women's Mid-Calf Boots Wide Calf Boots for Women Fashion Zipper \"\n 'Womens Shoes Pu Leather Casual Boots Womens Slip-On Womens Flat '\n \"Shoes Med Heel Womens' Boots Winter Snow Boot Comfy Boots(,5.5)\",\n 'asin': 'B09N8ZHFNM'\n }, {\n 'Price': 100.0,\n 'Title': 'PMUYBHF Womens Leisure Fitness Running Sport Warm Sneakers Shoes '\n 'Slip-On Mule Sneakers Womens Mules',\n 'asin': 'B09P87DWGR'\n }, {\n 'Price': 100.0,\n 'Title': 'Men Dress Shoes Leather Modern Classic Business Shoes Lace Up '\n 'Classic Office Shoes Business Formal Shoes for Men',\n 'asin': 'B09R9MMTKR'\n }]\n assert output == expected\n\ndef test_convert_dict_to_actions():\n # Test RESULTS page type\n asin = \"334490012932\"\n page_num = 2\n products = [{\n 'asin': '125331076844',\n 'Title': 'Modern Tall Torchiere Floor Lamp Brushed Nickel Chrome Metal Decor Living Room',\n 'Price': '$129.95'\n }, {\n 'asin': '125109985453',\n 'Title': 'Floor Lamps Set of 2 Polished Steel Crystal Glass for Living Room Bedroom',\n 'Price': '$179.99'\n }, {\n 'asin': '125265434055',\n 'Title': 'Floor Lamp Nickel/Polished Concrete Finish with Off-White Linen Fabric Shade',\n 'Price': '$130.68'\n }, {\n 'asin': '195197281169',\n 'Title': 'New ListingVintage Mid Century Modern Glass Amber Globe Tension Pole Floor Lamp Light',","source_hash":"2f1ed677907f992ff0bf377061e7a82ff04886c655a7dff164bfed0dcddc7d59","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.tests.transfer.test_predict_help.test_convert_dict_to_actions","uri":"program://BOLAA/function/webshop.tests.transfer.test_predict_help.test_convert_dict_to_actions#L385-L468","kind":"function","name":"test_convert_dict_to_actions","path":"webshop/tests/transfer/test_predict_help.py","language":"python","start_line":385,"end_line":468,"context_start_line":365,"context_end_line":468,"code":" 'asin': 'B09N6PDFRF'\n }, {\n 'Price': 100.0,\n 'Title': \"Women's Mid-Calf Boots Wide Calf Boots for Women Fashion Zipper \"\n 'Womens Shoes Pu Leather Casual Boots Womens Slip-On Womens Flat '\n \"Shoes Med Heel Womens' Boots Winter Snow Boot Comfy Boots(,5.5)\",\n 'asin': 'B09N8ZHFNM'\n }, {\n 'Price': 100.0,\n 'Title': 'PMUYBHF Womens Leisure Fitness Running Sport Warm Sneakers Shoes '\n 'Slip-On Mule Sneakers Womens Mules',\n 'asin': 'B09P87DWGR'\n }, {\n 'Price': 100.0,\n 'Title': 'Men Dress Shoes Leather Modern Classic Business Shoes Lace Up '\n 'Classic Office Shoes Business Formal Shoes for Men',\n 'asin': 'B09R9MMTKR'\n }]\n assert output == expected\n\ndef test_convert_dict_to_actions():\n # Test RESULTS page type\n asin = \"334490012932\"\n page_num = 2\n products = [{\n 'asin': '125331076844',\n 'Title': 'Modern Tall Torchiere Floor Lamp Brushed Nickel Chrome Metal Decor Living Room',\n 'Price': '$129.95'\n }, {\n 'asin': '125109985453',\n 'Title': 'Floor Lamps Set of 2 Polished Steel Crystal Glass for Living Room Bedroom',\n 'Price': '$179.99'\n }, {\n 'asin': '125265434055',\n 'Title': 'Floor Lamp Nickel/Polished Concrete Finish with Off-White Linen Fabric Shade',\n 'Price': '$130.68'\n }, {\n 'asin': '195197281169',\n 'Title': 'New ListingVintage Mid Century Modern Glass Amber Globe Tension Pole Floor Lamp Light',\n 'Price': '$165.00'\n }, {\n 'asin': '195197512929',\n 'Title': 'New ListingVTG Brass Floor Lamp Glass Shade 63.5\" Tall 12\" Diameter Glass Shade Original',\n 'Price': '$279.45'\n }, {\n 'asin': '304550250934',\n 'Title': 'Vintage Mid Century Modern 3 Light Tension Pole Floor Lamp glass shades atomic a',\n 'Price': '$149.99'\n }, {\n 'asin': '175338033811',\n 'Title': 'Antique FOSTORIA Ornate Brass Piano Adjustable Floor Oil Lamp up to 76\" Tall !!',\n 'Price': '$1,995.00'\n }, {\n 'asin': '334490012932',\n 'Title': 'Vintage Mid Century Glass Shade Amber Globe 3 Tension Pole Floor Lamp Light MCM',\n 'Price': '$128.00'\n }, {\n 'asin': '185433933521',\n 'Title': 'Brass & Pink Glass Lotus 6 Petal Lamp Shades Set Of Two Replacement Parts As Is',\n 'Price': '$90.00'\n }]\n\n actions = convert_dict_to_actions(Page.RESULTS, products, asin, page_num)\n\n assert actions['valid'] == [\n 'click[back to search]',\n 'click[< prev]',\n 'click[item - Modern Tall Torchiere Floor Lamp Brushed Nickel Chrome Metal Decor Living Room]',\n 'click[item - Floor Lamps Set of 2 Polished Steel Crystal Glass for Living Room Bedroom]',\n 'click[item - Floor Lamp Nickel/Polished Concrete Finish with Off-White Linen Fabric Shade]',\n 'click[item - New ListingVintage Mid Century Modern Glass Amber Globe Tension Pole Floor Lamp Light]',\n 'click[item - New ListingVTG Brass Floor Lamp Glass Shade 63.5\" Tall 12\" Diameter Glass Shade Original]',\n 'click[item - Vintage Mid Century Modern 3 Light Tension Pole Floor Lamp glass shades atomic a]',\n 'click[item - Antique FOSTORIA Ornate Brass Piano Adjustable Floor Oil Lamp up to 76\" Tall !!]',\n 'click[item - Vintage Mid Century Glass Shade Amber Globe 3 Tension Pole Floor Lamp Light MCM]',\n 'click[item - Brass & Pink Glass Lotus 6 Petal Lamp Shades Set Of Two Replacement Parts As Is]'\n ]\n\n # Test ITEM_PAGE page type\n asin = \"224636269803\"\n products = {\n '224636269803': {\n 'asin': '224636269803',\n 'Title': 'Sony SRS-XB01 EXTRA BASS Portable Water-Resistant Wireless Bluetooth Speaker',\n 'Price': '24.99',\n 'MainImage': 'https://i.ebayimg.com/images/g/jVEAAOSwCLBhXLuD/s-l500.jpg',\n 'Rating': None,\n 'options': {\n 'Color': ['Black', 'White', 'Red', 'Blue']\n },\n 'option_to_image': {},\n 'Description': \"eBay Sony EXTRA BASS Portable Water-Resistant Wireless Bluetooth SpeakerBRAND NEW ITEMFREE SHIPPING WITHIN USA30 DAY RETURN POLICYKey FeaturesEXTRA BASS for deep, punchy soundCompact portable designUp to 6 hours of battery lifeWater resistant for worry-free useSupplied with color-coordinated strap What's in the Box?Sony EXTRA BASS Portable Bluetooth SpeakerPower supplyUser manual HIGHLIGHTSMUSIC THAT TRAVELSSmall size but mighty in volume to deliver powerful beats wherever you travelHANDS FREE CALLINGWith the built-in microphone, taking calls from your smartphone is easy. SPLASHPROOF CASINGTake to the pool or beach without worrying about water damaging the speaker unit UPGRADE THE AUDIOWirelessly connects 2 speakers and achieve stereo sound with speaker add function LONGER BATTERY LIFELonger Virtual Happy Hours with this rechargeable speaker's 6 hour battery life Technical SpecsFeatureValueBrandSonyTypePortable speakerModel NumberSRSXB01BluetoothYesFrequency range2.4 GHzMax. Communication Range32 ftBattery LifeApprox. 6 hrsWater ProtectionIPX5Input and Output TerminalsStereo Mini Jack (IN)Dimensions (W x H x D)Approx. 3 1/4 × 2 3/8 × 2 1/4 inWeightApprox. 5.65 oz\",\n 'BulletPoints': \"Item specifics Condition:New: A brand-new, unused, unopened, undamaged item in its original packaging (where packaging is ... Read moreabout the conditionNew: A brand-new, unused, unopened, undamaged item in its original packaging (where packaging is applicable). Packaging should be the same as what is found in a retail store, unless the item is handmade or was packaged by the manufacturer in non-retail packaging, such as an unprinted box or plastic bag. See the seller's listing for full details. See all condition definitionsopens in a new window or tab Model:EXTRA BASS Connectivity:Bluetooth, Wireless Type:Portable Speaker System Compatible Model:EXTRA BASS, Portable Water-Resistant Features:Bluetooth, Water-Resistant MPN:SRS-XB01/B, SRS-XB01/L, SRS-XB01/R, SRS-XB01/W Brand:Sony\"\n }\n }\n\n actions = convert_dict_to_actions(Page.ITEM_PAGE, products, asin, 1)\n\n assert actions['valid'] == ['click[back to search]', 'click[< prev]', 'click[description]', 'click[features]', 'click[buy now]', 'click[Black]', 'click[White]', 'click[Red]', 'click[Blue]']\n\n # Test SUB_PAGE page type\n actions = convert_dict_to_actions(Page.SUB_PAGE, {}, \"12345\", 1)\n \n assert actions['valid'] == ['click[back to search]', 'click[< prev]']","source_hash":"2f1ed677907f992ff0bf377061e7a82ff04886c655a7dff164bfed0dcddc7d59","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.run_envs.run_web_agent_text_env","uri":"program://BOLAA/module/webshop.run_envs.run_web_agent_text_env#L1-L35","kind":"module","name":"webshop.run_envs.run_web_agent_text_env","path":"webshop/run_envs/run_web_agent_text_env.py","language":"python","start_line":1,"end_line":35,"context_start_line":1,"context_end_line":35,"code":"\"\"\"\nTest the text gym environment.\n\nTODO: move to testing dir for more rigorous tests\n\"\"\"\nimport gym\nfrom rich import print\nfrom rich.markup import escape\n\nfrom web_agent_site.envs import WebAgentTextEnv\nfrom web_agent_site.models import RandomPolicy\nfrom web_agent_site.utils import DEBUG_PROD_SIZE\n\nif __name__ == '__main__':\n env = gym.make('WebAgentTextEnv-v0', observation_mode='text', num_products=DEBUG_PROD_SIZE)\n env.reset()\n \n try:\n policy = RandomPolicy()\n \n observation = env.observation\n while True:\n print(observation)\n available_actions = env.get_available_actions()\n print('Available actions:', available_actions)\n # action = policy.forward(observation, available_actions)\n action = \"search[ flat screen tv under $500 ]\"\n observation, reward, done, info = env.step(action)\n print(\"observation:\", observation)\n print(\"info:\", info)\n print(f'Taking action \"{escape(action)}\" -> Reward = {reward}')\n if done:\n break\n finally:\n env.close()","source_hash":"530356dadac65db9e767c677b5b166abd1002d6d9dd5b2c81c4e297a00293751","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.run_envs.run_web_agent_site_env","uri":"program://BOLAA/module/webshop.run_envs.run_web_agent_site_env#L1-L41","kind":"module","name":"webshop.run_envs.run_web_agent_site_env","path":"webshop/run_envs/run_web_agent_site_env.py","language":"python","start_line":1,"end_line":41,"context_start_line":1,"context_end_line":41,"code":"\"\"\"\nTest the site gym environment.\n\nTODO: move to testing dir for more rigorous tests\n\"\"\"\nimport gym\nfrom rich import print\nfrom rich.markup import escape\n\nfrom web_agent_site.envs import WebAgentSiteEnv\nfrom web_agent_site.models import (\n HumanPolicy,\n RandomPolicy,\n)\nfrom web_agent_site.utils import DEBUG_PROD_SIZE\n\n\nif __name__ == '__main__':\n #env = gym.make('WebAgentSite-v0')\n #env = WebAgentSiteEnv(render=True, pause=2.0)\n #env = WebAgentSiteEnv(observation_mode='html', render=False)\n env = WebAgentSiteEnv(observation_mode='text', render=False, num_products=DEBUG_PROD_SIZE)\n global_step = 0\n \n try:\n #policy = HumanPolicy()\n policy = RandomPolicy()\n \n observation = env.observation\n while True:\n print(observation)\n available_actions = env.get_available_actions()\n print('Available actions:', available_actions)\n action = policy.forward(observation, available_actions)\n observation, reward, done, info = env.step(action)\n print(f'Taking action \"{escape(action)}\" -> Reward = {reward}')\n if done:\n break\n global_step += 1\n finally:\n env.close()","source_hash":"c40b099b1039acd9bcb2798eb027f25335c82b8b3f4cda56b5d31fe21638d6f8","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.app","uri":"program://BOLAA/module/webshop.web_agent_site.app#L1-L280","kind":"module","name":"webshop.web_agent_site.app","path":"webshop/web_agent_site/app.py","language":"python","start_line":1,"end_line":280,"context_start_line":1,"context_end_line":280,"code":"import argparse, json, logging, random\nfrom pathlib import Path\nfrom ast import literal_eval\n\nfrom flask import (\n Flask,\n request,\n redirect,\n url_for\n)\n\nfrom rich import print\n\nfrom web_agent_site.engine.engine import (\n load_products,\n init_search_engine,\n convert_web_app_string_to_var,\n get_top_n_product_from_keywords,\n get_product_per_page,\n map_action_to_html,\n END_BUTTON\n)\nfrom web_agent_site.engine.goal import get_reward, get_goals\nfrom web_agent_site.utils import (\n generate_mturk_code,\n setup_logger,\n DEFAULT_FILE_PATH,\n DEBUG_PROD_SIZE,\n)\n\napp = Flask(__name__)\n\nsearch_engine = None\nall_products = None\nproduct_item_dict = None\nproduct_prices = None\nattribute_to_asins = None\ngoals = None\nweights = None\n\nuser_sessions = dict()\nuser_log_dir = None\nSHOW_ATTRS_TAB = False\n\n@app.route('/')\ndef home():\n return redirect(url_for('index', session_id=\"abc\"))\n\n@app.route('/', methods=['GET', 'POST'])\ndef index(session_id):\n global user_log_dir\n global all_products, product_item_dict, \\\n product_prices, attribute_to_asins, \\\n search_engine, \\\n goals, weights, user_sessions\n\n if search_engine is None:\n all_products, product_item_dict, product_prices, attribute_to_asins = \\\n load_products(\n filepath=DEFAULT_FILE_PATH,\n num_products=DEBUG_PROD_SIZE\n )\n search_engine = init_search_engine(num_products=DEBUG_PROD_SIZE)\n goals = get_goals(all_products, product_prices)\n # random.seed(233)\n # random.shuffle(goals)\n weights = [goal['weight'] for goal in goals]\n\n if session_id not in user_sessions and 'fixed' in session_id:\n goal_dix = int(session_id.split('_')[-1])\n goal = goals[goal_dix]\n instruction_text = goal['instruction_text']\n user_sessions[session_id] = {'goal': goal, 'done': False}\n if user_log_dir is not None:\n setup_logger(session_id, user_log_dir)\n elif session_id not in user_sessions:\n goal = random.choices(goals, weights)[0]\n instruction_text = goal['instruction_text']\n user_sessions[session_id] = {'goal': goal, 'done': False}\n if user_log_dir is not None:\n setup_logger(session_id, user_log_dir)\n else:\n instruction_text = user_sessions[session_id]['goal']['instruction_text']\n\n if request.method == 'POST' and 'search_query' in request.form:\n keywords = request.form['search_query'].lower().split(' ')\n return redirect(url_for(\n 'search_results',\n session_id=session_id,\n keywords=keywords,\n page=1,\n ))\n if user_log_dir is not None:\n logger = logging.getLogger(session_id)\n logger.info(json.dumps(dict(\n page='index',\n url=request.url,\n goal=user_sessions[session_id]['goal'],\n )))\n return map_action_to_html(\n 'start',\n session_id=session_id,\n instruction_text=instruction_text,\n )\n\n\n@app.route(\n '/search_results///',\n methods=['GET', 'POST']\n)\ndef search_results(session_id, keywords, page):\n instruction_text = user_sessions[session_id]['goal']['instruction_text']\n page = convert_web_app_string_to_var('page', page)\n keywords = convert_web_app_string_to_var('keywords', keywords)\n top_n_products = get_top_n_product_from_keywords(\n keywords,\n search_engine,\n all_products,\n product_item_dict,\n attribute_to_asins,\n )\n products = get_product_per_page(top_n_products, page)\n html = map_action_to_html(\n 'search',\n session_id=session_id,\n products=products,\n keywords=keywords,\n page=page,\n total=len(top_n_products),\n instruction_text=instruction_text,\n )\n logger = logging.getLogger(session_id)\n logger.info(json.dumps(dict(\n page='search_results',\n url=request.url,\n goal=user_sessions[session_id]['goal'],\n content=dict(\n keywords=keywords,\n search_result_asins=[p['asin'] for p in products],\n page=page,\n )\n )))\n return html\n\n\n@app.route(\n '/item_page/////',\n methods=['GET', 'POST']\n)\ndef item_page(session_id, asin, keywords, page, options):\n options = literal_eval(options)\n product_info = product_item_dict[asin]\n\n goal_instruction = user_sessions[session_id]['goal']['instruction_text']\n product_info['goal_instruction'] = goal_instruction\n\n html = map_action_to_html(\n 'click',\n session_id=session_id,\n product_info=product_info,\n keywords=keywords,\n page=page,\n asin=asin,\n options=options,\n instruction_text=goal_instruction,\n show_attrs=SHOW_ATTRS_TAB,\n )\n logger = logging.getLogger(session_id)\n logger.info(json.dumps(dict(\n page='item_page',\n url=request.url,\n goal=user_sessions[session_id]['goal'],\n content=dict(\n keywords=keywords,\n page=page,\n asin=asin,\n options=options,\n )\n )))\n return html\n\n\n@app.route(\n '/item_sub_page//////',\n methods=['GET', 'POST']\n)\ndef item_sub_page(session_id, asin, keywords, page, sub_page, options):\n options = literal_eval(options)\n product_info = product_item_dict[asin]\n\n goal_instruction = user_sessions[session_id]['goal']['instruction_text']\n product_info['goal_instruction'] = goal_instruction\n\n html = map_action_to_html(\n f'click[{sub_page}]',\n session_id=session_id,\n product_info=product_info,\n keywords=keywords,\n page=page,\n asin=asin,\n options=options,\n instruction_text=goal_instruction\n )\n logger = logging.getLogger(session_id)\n logger.info(json.dumps(dict(\n page='item_sub_page',\n url=request.url,\n goal=user_sessions[session_id]['goal'],\n content=dict(\n keywords=keywords,\n page=page,\n asin=asin,\n options=options,\n )\n )))\n return html\n\n\n@app.route('/done///', methods=['GET', 'POST'])\ndef done(session_id, asin, options):\n options = literal_eval(options)\n goal = user_sessions[session_id]['goal']\n purchased_product = product_item_dict[asin]\n price = product_prices[asin]\n\n reward, reward_info = get_reward(\n purchased_product,\n goal,\n price=price,\n options=options,\n verbose=True\n )\n user_sessions[session_id]['done'] = True\n user_sessions[session_id]['reward'] = reward\n print(user_sessions)\n\n logger = logging.getLogger(session_id)\n logger.info(json.dumps(dict(\n page='done',\n url=request.url,\n goal=goal,\n content=dict(\n asin=asin,\n options=options,\n price=price,\n ),\n reward=reward,\n reward_info=reward_info,\n )))\n del logging.root.manager.loggerDict[session_id]\n \n return map_action_to_html(\n f'click[{END_BUTTON}]',\n session_id=session_id,\n reward=reward,\n asin=asin,\n options=options,\n reward_info=reward_info,\n query=purchased_product['query'],\n category=purchased_product['category'],\n product_category=purchased_product['product_category'],\n goal_attrs=user_sessions[session_id]['goal']['attributes'],\n purchased_attrs=purchased_product['Attributes'],\n goal=goal,\n mturk_code=generate_mturk_code(session_id),\n )\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"WebShop flask app backend configuration\")\n parser.add_argument(\"--log\", action='store_true', help=\"Log actions on WebShop in trajectory file\")\n parser.add_argument(\"--attrs\", action='store_true', help=\"Show attributes tab in item page\")\n\n args = parser.parse_args()\n if args.log:\n user_log_dir = Path('user_session_logs/mturk')\n user_log_dir.mkdir(parents=True, exist_ok=True)\n SHOW_ATTRS_TAB = args.attrs\n\n app.run(host='0.0.0.0', port=3000)","source_hash":"b35dc4e8771af298273974a7d1a1dae7986a78009eb671f71981933546ba8586","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.app.home","uri":"program://BOLAA/function/webshop.web_agent_site.app.home#L46-L47","kind":"function","name":"home","path":"webshop/web_agent_site/app.py","language":"python","start_line":46,"end_line":47,"context_start_line":26,"context_end_line":67,"code":" setup_logger,\n DEFAULT_FILE_PATH,\n DEBUG_PROD_SIZE,\n)\n\napp = Flask(__name__)\n\nsearch_engine = None\nall_products = None\nproduct_item_dict = None\nproduct_prices = None\nattribute_to_asins = None\ngoals = None\nweights = None\n\nuser_sessions = dict()\nuser_log_dir = None\nSHOW_ATTRS_TAB = False\n\n@app.route('/')\ndef home():\n return redirect(url_for('index', session_id=\"abc\"))\n\n@app.route('/', methods=['GET', 'POST'])\ndef index(session_id):\n global user_log_dir\n global all_products, product_item_dict, \\\n product_prices, attribute_to_asins, \\\n search_engine, \\\n goals, weights, user_sessions\n\n if search_engine is None:\n all_products, product_item_dict, product_prices, attribute_to_asins = \\\n load_products(\n filepath=DEFAULT_FILE_PATH,\n num_products=DEBUG_PROD_SIZE\n )\n search_engine = init_search_engine(num_products=DEBUG_PROD_SIZE)\n goals = get_goals(all_products, product_prices)\n # random.seed(233)\n # random.shuffle(goals)\n weights = [goal['weight'] for goal in goals]","source_hash":"b35dc4e8771af298273974a7d1a1dae7986a78009eb671f71981933546ba8586","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.app.index","uri":"program://BOLAA/function/webshop.web_agent_site.app.index#L50-L104","kind":"function","name":"index","path":"webshop/web_agent_site/app.py","language":"python","start_line":50,"end_line":104,"context_start_line":30,"context_end_line":124,"code":"\napp = Flask(__name__)\n\nsearch_engine = None\nall_products = None\nproduct_item_dict = None\nproduct_prices = None\nattribute_to_asins = None\ngoals = None\nweights = None\n\nuser_sessions = dict()\nuser_log_dir = None\nSHOW_ATTRS_TAB = False\n\n@app.route('/')\ndef home():\n return redirect(url_for('index', session_id=\"abc\"))\n\n@app.route('/', methods=['GET', 'POST'])\ndef index(session_id):\n global user_log_dir\n global all_products, product_item_dict, \\\n product_prices, attribute_to_asins, \\\n search_engine, \\\n goals, weights, user_sessions\n\n if search_engine is None:\n all_products, product_item_dict, product_prices, attribute_to_asins = \\\n load_products(\n filepath=DEFAULT_FILE_PATH,\n num_products=DEBUG_PROD_SIZE\n )\n search_engine = init_search_engine(num_products=DEBUG_PROD_SIZE)\n goals = get_goals(all_products, product_prices)\n # random.seed(233)\n # random.shuffle(goals)\n weights = [goal['weight'] for goal in goals]\n\n if session_id not in user_sessions and 'fixed' in session_id:\n goal_dix = int(session_id.split('_')[-1])\n goal = goals[goal_dix]\n instruction_text = goal['instruction_text']\n user_sessions[session_id] = {'goal': goal, 'done': False}\n if user_log_dir is not None:\n setup_logger(session_id, user_log_dir)\n elif session_id not in user_sessions:\n goal = random.choices(goals, weights)[0]\n instruction_text = goal['instruction_text']\n user_sessions[session_id] = {'goal': goal, 'done': False}\n if user_log_dir is not None:\n setup_logger(session_id, user_log_dir)\n else:\n instruction_text = user_sessions[session_id]['goal']['instruction_text']\n\n if request.method == 'POST' and 'search_query' in request.form:\n keywords = request.form['search_query'].lower().split(' ')\n return redirect(url_for(\n 'search_results',\n session_id=session_id,\n keywords=keywords,\n page=1,\n ))\n if user_log_dir is not None:\n logger = logging.getLogger(session_id)\n logger.info(json.dumps(dict(\n page='index',\n url=request.url,\n goal=user_sessions[session_id]['goal'],\n )))\n return map_action_to_html(\n 'start',\n session_id=session_id,\n instruction_text=instruction_text,\n )\n\n\n@app.route(\n '/search_results///',\n methods=['GET', 'POST']\n)\ndef search_results(session_id, keywords, page):\n instruction_text = user_sessions[session_id]['goal']['instruction_text']\n page = convert_web_app_string_to_var('page', page)\n keywords = convert_web_app_string_to_var('keywords', keywords)\n top_n_products = get_top_n_product_from_keywords(\n keywords,\n search_engine,\n all_products,\n product_item_dict,\n attribute_to_asins,\n )\n products = get_product_per_page(top_n_products, page)\n html = map_action_to_html(\n 'search',","source_hash":"b35dc4e8771af298273974a7d1a1dae7986a78009eb671f71981933546ba8586","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.app.search_results","uri":"program://BOLAA/function/webshop.web_agent_site.app.search_results#L111-L143","kind":"function","name":"search_results","path":"webshop/web_agent_site/app.py","language":"python","start_line":111,"end_line":143,"context_start_line":91,"context_end_line":163,"code":" page=1,\n ))\n if user_log_dir is not None:\n logger = logging.getLogger(session_id)\n logger.info(json.dumps(dict(\n page='index',\n url=request.url,\n goal=user_sessions[session_id]['goal'],\n )))\n return map_action_to_html(\n 'start',\n session_id=session_id,\n instruction_text=instruction_text,\n )\n\n\n@app.route(\n '/search_results///',\n methods=['GET', 'POST']\n)\ndef search_results(session_id, keywords, page):\n instruction_text = user_sessions[session_id]['goal']['instruction_text']\n page = convert_web_app_string_to_var('page', page)\n keywords = convert_web_app_string_to_var('keywords', keywords)\n top_n_products = get_top_n_product_from_keywords(\n keywords,\n search_engine,\n all_products,\n product_item_dict,\n attribute_to_asins,\n )\n products = get_product_per_page(top_n_products, page)\n html = map_action_to_html(\n 'search',\n session_id=session_id,\n products=products,\n keywords=keywords,\n page=page,\n total=len(top_n_products),\n instruction_text=instruction_text,\n )\n logger = logging.getLogger(session_id)\n logger.info(json.dumps(dict(\n page='search_results',\n url=request.url,\n goal=user_sessions[session_id]['goal'],\n content=dict(\n keywords=keywords,\n search_result_asins=[p['asin'] for p in products],\n page=page,\n )\n )))\n return html\n\n\n@app.route(\n '/item_page/////',\n methods=['GET', 'POST']\n)\ndef item_page(session_id, asin, keywords, page, options):\n options = literal_eval(options)\n product_info = product_item_dict[asin]\n\n goal_instruction = user_sessions[session_id]['goal']['instruction_text']\n product_info['goal_instruction'] = goal_instruction\n\n html = map_action_to_html(\n 'click',\n session_id=session_id,\n product_info=product_info,\n keywords=keywords,\n page=page,\n asin=asin,","source_hash":"b35dc4e8771af298273974a7d1a1dae7986a78009eb671f71981933546ba8586","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.app.item_page","uri":"program://BOLAA/function/webshop.web_agent_site.app.item_page#L150-L180","kind":"function","name":"item_page","path":"webshop/web_agent_site/app.py","language":"python","start_line":150,"end_line":180,"context_start_line":130,"context_end_line":200,"code":" instruction_text=instruction_text,\n )\n logger = logging.getLogger(session_id)\n logger.info(json.dumps(dict(\n page='search_results',\n url=request.url,\n goal=user_sessions[session_id]['goal'],\n content=dict(\n keywords=keywords,\n search_result_asins=[p['asin'] for p in products],\n page=page,\n )\n )))\n return html\n\n\n@app.route(\n '/item_page/////',\n methods=['GET', 'POST']\n)\ndef item_page(session_id, asin, keywords, page, options):\n options = literal_eval(options)\n product_info = product_item_dict[asin]\n\n goal_instruction = user_sessions[session_id]['goal']['instruction_text']\n product_info['goal_instruction'] = goal_instruction\n\n html = map_action_to_html(\n 'click',\n session_id=session_id,\n product_info=product_info,\n keywords=keywords,\n page=page,\n asin=asin,\n options=options,\n instruction_text=goal_instruction,\n show_attrs=SHOW_ATTRS_TAB,\n )\n logger = logging.getLogger(session_id)\n logger.info(json.dumps(dict(\n page='item_page',\n url=request.url,\n goal=user_sessions[session_id]['goal'],\n content=dict(\n keywords=keywords,\n page=page,\n asin=asin,\n options=options,\n )\n )))\n return html\n\n\n@app.route(\n '/item_sub_page//////',\n methods=['GET', 'POST']\n)\ndef item_sub_page(session_id, asin, keywords, page, sub_page, options):\n options = literal_eval(options)\n product_info = product_item_dict[asin]\n\n goal_instruction = user_sessions[session_id]['goal']['instruction_text']\n product_info['goal_instruction'] = goal_instruction\n\n html = map_action_to_html(\n f'click[{sub_page}]',\n session_id=session_id,\n product_info=product_info,\n keywords=keywords,\n page=page,\n asin=asin,","source_hash":"b35dc4e8771af298273974a7d1a1dae7986a78009eb671f71981933546ba8586","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.app.item_sub_page","uri":"program://BOLAA/function/webshop.web_agent_site.app.item_sub_page#L187-L216","kind":"function","name":"item_sub_page","path":"webshop/web_agent_site/app.py","language":"python","start_line":187,"end_line":216,"context_start_line":167,"context_end_line":236,"code":" )\n logger = logging.getLogger(session_id)\n logger.info(json.dumps(dict(\n page='item_page',\n url=request.url,\n goal=user_sessions[session_id]['goal'],\n content=dict(\n keywords=keywords,\n page=page,\n asin=asin,\n options=options,\n )\n )))\n return html\n\n\n@app.route(\n '/item_sub_page//////',\n methods=['GET', 'POST']\n)\ndef item_sub_page(session_id, asin, keywords, page, sub_page, options):\n options = literal_eval(options)\n product_info = product_item_dict[asin]\n\n goal_instruction = user_sessions[session_id]['goal']['instruction_text']\n product_info['goal_instruction'] = goal_instruction\n\n html = map_action_to_html(\n f'click[{sub_page}]',\n session_id=session_id,\n product_info=product_info,\n keywords=keywords,\n page=page,\n asin=asin,\n options=options,\n instruction_text=goal_instruction\n )\n logger = logging.getLogger(session_id)\n logger.info(json.dumps(dict(\n page='item_sub_page',\n url=request.url,\n goal=user_sessions[session_id]['goal'],\n content=dict(\n keywords=keywords,\n page=page,\n asin=asin,\n options=options,\n )\n )))\n return html\n\n\n@app.route('/done///', methods=['GET', 'POST'])\ndef done(session_id, asin, options):\n options = literal_eval(options)\n goal = user_sessions[session_id]['goal']\n purchased_product = product_item_dict[asin]\n price = product_prices[asin]\n\n reward, reward_info = get_reward(\n purchased_product,\n goal,\n price=price,\n options=options,\n verbose=True\n )\n user_sessions[session_id]['done'] = True\n user_sessions[session_id]['reward'] = reward\n print(user_sessions)\n","source_hash":"b35dc4e8771af298273974a7d1a1dae7986a78009eb671f71981933546ba8586","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.app.done","uri":"program://BOLAA/function/webshop.web_agent_site.app.done#L220-L266","kind":"function","name":"done","path":"webshop/web_agent_site/app.py","language":"python","start_line":220,"end_line":266,"context_start_line":200,"context_end_line":280,"code":" asin=asin,\n options=options,\n instruction_text=goal_instruction\n )\n logger = logging.getLogger(session_id)\n logger.info(json.dumps(dict(\n page='item_sub_page',\n url=request.url,\n goal=user_sessions[session_id]['goal'],\n content=dict(\n keywords=keywords,\n page=page,\n asin=asin,\n options=options,\n )\n )))\n return html\n\n\n@app.route('/done///', methods=['GET', 'POST'])\ndef done(session_id, asin, options):\n options = literal_eval(options)\n goal = user_sessions[session_id]['goal']\n purchased_product = product_item_dict[asin]\n price = product_prices[asin]\n\n reward, reward_info = get_reward(\n purchased_product,\n goal,\n price=price,\n options=options,\n verbose=True\n )\n user_sessions[session_id]['done'] = True\n user_sessions[session_id]['reward'] = reward\n print(user_sessions)\n\n logger = logging.getLogger(session_id)\n logger.info(json.dumps(dict(\n page='done',\n url=request.url,\n goal=goal,\n content=dict(\n asin=asin,\n options=options,\n price=price,\n ),\n reward=reward,\n reward_info=reward_info,\n )))\n del logging.root.manager.loggerDict[session_id]\n \n return map_action_to_html(\n f'click[{END_BUTTON}]',\n session_id=session_id,\n reward=reward,\n asin=asin,\n options=options,\n reward_info=reward_info,\n query=purchased_product['query'],\n category=purchased_product['category'],\n product_category=purchased_product['product_category'],\n goal_attrs=user_sessions[session_id]['goal']['attributes'],\n purchased_attrs=purchased_product['Attributes'],\n goal=goal,\n mturk_code=generate_mturk_code(session_id),\n )\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"WebShop flask app backend configuration\")\n parser.add_argument(\"--log\", action='store_true', help=\"Log actions on WebShop in trajectory file\")\n parser.add_argument(\"--attrs\", action='store_true', help=\"Show attributes tab in item page\")\n\n args = parser.parse_args()\n if args.log:\n user_log_dir = Path('user_session_logs/mturk')\n user_log_dir.mkdir(parents=True, exist_ok=True)\n SHOW_ATTRS_TAB = args.attrs\n\n app.run(host='0.0.0.0', port=3000)","source_hash":"b35dc4e8771af298273974a7d1a1dae7986a78009eb671f71981933546ba8586","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.utils","uri":"program://BOLAA/module/webshop.web_agent_site.utils#L1-L51","kind":"module","name":"webshop.web_agent_site.utils","path":"webshop/web_agent_site/utils.py","language":"python","start_line":1,"end_line":51,"context_start_line":1,"context_end_line":51,"code":"import bisect\nimport hashlib\nimport logging\nimport random\nfrom os.path import dirname, abspath, join\n\nBASE_DIR = dirname(abspath(__file__))\nDEBUG_PROD_SIZE = None # set to `None` to disable\n\n# DEFAULT_ATTR_PATH = join(BASE_DIR, '../data/items_ins_v2_1000.json')\n# DEFAULT_FILE_PATH = join(BASE_DIR, '../data/items_shuffle_1000.json')\nDEFAULT_ATTR_PATH = join(BASE_DIR, '../data/items_ins_v2.json')\nDEFAULT_FILE_PATH = join(BASE_DIR, '../data/items_shuffle.json')\nDEFAULT_REVIEW_PATH = join(BASE_DIR, '../data/reviews.json')\n\nFEAT_CONV = join(BASE_DIR, '../data/feat_conv.pt')\nFEAT_IDS = join(BASE_DIR, '../data/feat_ids.pt')\n\nHUMAN_ATTR_PATH = join(BASE_DIR, '../data/new_human_ins_sampled_1.json')\n\n# HUMAN_ATTR_PATH = join(BASE_DIR, '../data/items_human_ins.json')\n\ndef random_idx(cum_weights):\n \"\"\"Generate random index by sampling uniformly from sum of all weights, then\n selecting the `min` between the position to keep the list sorted (via bisect)\n and the value of the second to last index\n \"\"\"\n pos = random.uniform(0, cum_weights[-1])\n idx = bisect.bisect(cum_weights, pos)\n idx = min(idx, len(cum_weights) - 2)\n return idx\n\ndef setup_logger(session_id, user_log_dir):\n \"\"\"Creates a log file and logging object for the corresponding session ID\"\"\"\n logger = logging.getLogger(session_id)\n formatter = logging.Formatter('%(message)s')\n file_handler = logging.FileHandler(\n user_log_dir / f'{session_id}.jsonl',\n mode='w'\n )\n file_handler.setFormatter(formatter)\n logger.setLevel(logging.INFO)\n logger.addHandler(file_handler)\n return logger\n\ndef generate_mturk_code(session_id: str) -> str:\n \"\"\"Generates a redeem code corresponding to the session ID for an MTurk\n worker once the session is completed\n \"\"\"\n sha = hashlib.sha1(session_id.encode())\n return sha.hexdigest()[:10].upper()","source_hash":"0c78ce4209049cd315e164525edac2bef0a2cdfbbdbb818c90cfa9b2d7073ec6","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.utils.random_idx","uri":"program://BOLAA/function/webshop.web_agent_site.utils.random_idx#L23-L31","kind":"function","name":"random_idx","path":"webshop/web_agent_site/utils.py","language":"python","start_line":23,"end_line":31,"context_start_line":3,"context_end_line":51,"code":"import logging\nimport random\nfrom os.path import dirname, abspath, join\n\nBASE_DIR = dirname(abspath(__file__))\nDEBUG_PROD_SIZE = None # set to `None` to disable\n\n# DEFAULT_ATTR_PATH = join(BASE_DIR, '../data/items_ins_v2_1000.json')\n# DEFAULT_FILE_PATH = join(BASE_DIR, '../data/items_shuffle_1000.json')\nDEFAULT_ATTR_PATH = join(BASE_DIR, '../data/items_ins_v2.json')\nDEFAULT_FILE_PATH = join(BASE_DIR, '../data/items_shuffle.json')\nDEFAULT_REVIEW_PATH = join(BASE_DIR, '../data/reviews.json')\n\nFEAT_CONV = join(BASE_DIR, '../data/feat_conv.pt')\nFEAT_IDS = join(BASE_DIR, '../data/feat_ids.pt')\n\nHUMAN_ATTR_PATH = join(BASE_DIR, '../data/new_human_ins_sampled_1.json')\n\n# HUMAN_ATTR_PATH = join(BASE_DIR, '../data/items_human_ins.json')\n\ndef random_idx(cum_weights):\n \"\"\"Generate random index by sampling uniformly from sum of all weights, then\n selecting the `min` between the position to keep the list sorted (via bisect)\n and the value of the second to last index\n \"\"\"\n pos = random.uniform(0, cum_weights[-1])\n idx = bisect.bisect(cum_weights, pos)\n idx = min(idx, len(cum_weights) - 2)\n return idx\n\ndef setup_logger(session_id, user_log_dir):\n \"\"\"Creates a log file and logging object for the corresponding session ID\"\"\"\n logger = logging.getLogger(session_id)\n formatter = logging.Formatter('%(message)s')\n file_handler = logging.FileHandler(\n user_log_dir / f'{session_id}.jsonl',\n mode='w'\n )\n file_handler.setFormatter(formatter)\n logger.setLevel(logging.INFO)\n logger.addHandler(file_handler)\n return logger\n\ndef generate_mturk_code(session_id: str) -> str:\n \"\"\"Generates a redeem code corresponding to the session ID for an MTurk\n worker once the session is completed\n \"\"\"\n sha = hashlib.sha1(session_id.encode())\n return sha.hexdigest()[:10].upper()","source_hash":"0c78ce4209049cd315e164525edac2bef0a2cdfbbdbb818c90cfa9b2d7073ec6","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.utils.setup_logger","uri":"program://BOLAA/function/webshop.web_agent_site.utils.setup_logger#L33-L44","kind":"function","name":"setup_logger","path":"webshop/web_agent_site/utils.py","language":"python","start_line":33,"end_line":44,"context_start_line":13,"context_end_line":51,"code":"DEFAULT_FILE_PATH = join(BASE_DIR, '../data/items_shuffle.json')\nDEFAULT_REVIEW_PATH = join(BASE_DIR, '../data/reviews.json')\n\nFEAT_CONV = join(BASE_DIR, '../data/feat_conv.pt')\nFEAT_IDS = join(BASE_DIR, '../data/feat_ids.pt')\n\nHUMAN_ATTR_PATH = join(BASE_DIR, '../data/new_human_ins_sampled_1.json')\n\n# HUMAN_ATTR_PATH = join(BASE_DIR, '../data/items_human_ins.json')\n\ndef random_idx(cum_weights):\n \"\"\"Generate random index by sampling uniformly from sum of all weights, then\n selecting the `min` between the position to keep the list sorted (via bisect)\n and the value of the second to last index\n \"\"\"\n pos = random.uniform(0, cum_weights[-1])\n idx = bisect.bisect(cum_weights, pos)\n idx = min(idx, len(cum_weights) - 2)\n return idx\n\ndef setup_logger(session_id, user_log_dir):\n \"\"\"Creates a log file and logging object for the corresponding session ID\"\"\"\n logger = logging.getLogger(session_id)\n formatter = logging.Formatter('%(message)s')\n file_handler = logging.FileHandler(\n user_log_dir / f'{session_id}.jsonl',\n mode='w'\n )\n file_handler.setFormatter(formatter)\n logger.setLevel(logging.INFO)\n logger.addHandler(file_handler)\n return logger\n\ndef generate_mturk_code(session_id: str) -> str:\n \"\"\"Generates a redeem code corresponding to the session ID for an MTurk\n worker once the session is completed\n \"\"\"\n sha = hashlib.sha1(session_id.encode())\n return sha.hexdigest()[:10].upper()","source_hash":"0c78ce4209049cd315e164525edac2bef0a2cdfbbdbb818c90cfa9b2d7073ec6","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.utils.generate_mturk_code","uri":"program://BOLAA/function/webshop.web_agent_site.utils.generate_mturk_code#L46-L51","kind":"function","name":"generate_mturk_code","path":"webshop/web_agent_site/utils.py","language":"python","start_line":46,"end_line":51,"context_start_line":26,"context_end_line":51,"code":" and the value of the second to last index\n \"\"\"\n pos = random.uniform(0, cum_weights[-1])\n idx = bisect.bisect(cum_weights, pos)\n idx = min(idx, len(cum_weights) - 2)\n return idx\n\ndef setup_logger(session_id, user_log_dir):\n \"\"\"Creates a log file and logging object for the corresponding session ID\"\"\"\n logger = logging.getLogger(session_id)\n formatter = logging.Formatter('%(message)s')\n file_handler = logging.FileHandler(\n user_log_dir / f'{session_id}.jsonl',\n mode='w'\n )\n file_handler.setFormatter(formatter)\n logger.setLevel(logging.INFO)\n logger.addHandler(file_handler)\n return logger\n\ndef generate_mturk_code(session_id: str) -> str:\n \"\"\"Generates a redeem code corresponding to the session ID for an MTurk\n worker once the session is completed\n \"\"\"\n sha = hashlib.sha1(session_id.encode())\n return sha.hexdigest()[:10].upper()","source_hash":"0c78ce4209049cd315e164525edac2bef0a2cdfbbdbb818c90cfa9b2d7073ec6","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.models.models","uri":"program://BOLAA/module/webshop.web_agent_site.models.models#L1-L52","kind":"module","name":"webshop.web_agent_site.models.models","path":"webshop/web_agent_site/models/models.py","language":"python","start_line":1,"end_line":52,"context_start_line":1,"context_end_line":52,"code":"\"\"\"\nModel implementations. The model interface should be suitable for both\nthe ``site env'' and the ``text env''.\n\"\"\"\nimport random\n\nrandom.seed(4)\n\n\nclass BasePolicy:\n def __init__(self):\n pass\n \n def forward(observation, available_actions):\n \"\"\"\n Args:\n observation (`str`):\n HTML string\n\n available_actions ():\n ...\n Returns:\n action (`str`): \n Return string of the format ``action_name[action_arg]''.\n Examples:\n - search[white shoes]\n - click[button=Reviews]\n - click[button=Buy Now]\n \"\"\"\n raise NotImplementedError\n\n\nclass HumanPolicy(BasePolicy):\n def __init__(self):\n super().__init__()\n\n def forward(self, observation, available_actions):\n action = input('> ')\n return action\n\n\nclass RandomPolicy(BasePolicy):\n def __init__(self):\n super().__init__()\n \n def forward(self, observation, available_actions):\n if available_actions['has_search_bar']:\n action = 'search[shoes]'\n else:\n action_arg = random.choice(available_actions['clickables'])\n action = f'click[{action_arg}]'\n return action","source_hash":"229b2f2fb0feedcac84a8e7ed6484c976e4c0ccb026e22996052215c427445a7","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.models.models.BasePolicy","uri":"program://BOLAA/class/webshop.web_agent_site.models.models.BasePolicy#L10-L30","kind":"class","name":"BasePolicy","path":"webshop/web_agent_site/models/models.py","language":"python","start_line":10,"end_line":30,"context_start_line":1,"context_end_line":50,"code":"\"\"\"\nModel implementations. The model interface should be suitable for both\nthe ``site env'' and the ``text env''.\n\"\"\"\nimport random\n\nrandom.seed(4)\n\n\nclass BasePolicy:\n def __init__(self):\n pass\n \n def forward(observation, available_actions):\n \"\"\"\n Args:\n observation (`str`):\n HTML string\n\n available_actions ():\n ...\n Returns:\n action (`str`): \n Return string of the format ``action_name[action_arg]''.\n Examples:\n - search[white shoes]\n - click[button=Reviews]\n - click[button=Buy Now]\n \"\"\"\n raise NotImplementedError\n\n\nclass HumanPolicy(BasePolicy):\n def __init__(self):\n super().__init__()\n\n def forward(self, observation, available_actions):\n action = input('> ')\n return action\n\n\nclass RandomPolicy(BasePolicy):\n def __init__(self):\n super().__init__()\n \n def forward(self, observation, available_actions):\n if available_actions['has_search_bar']:\n action = 'search[shoes]'\n else:\n action_arg = random.choice(available_actions['clickables'])","source_hash":"229b2f2fb0feedcac84a8e7ed6484c976e4c0ccb026e22996052215c427445a7","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.models.models.HumanPolicy","uri":"program://BOLAA/class/webshop.web_agent_site.models.models.HumanPolicy#L33-L39","kind":"class","name":"HumanPolicy","path":"webshop/web_agent_site/models/models.py","language":"python","start_line":33,"end_line":39,"context_start_line":13,"context_end_line":52,"code":" \n def forward(observation, available_actions):\n \"\"\"\n Args:\n observation (`str`):\n HTML string\n\n available_actions ():\n ...\n Returns:\n action (`str`): \n Return string of the format ``action_name[action_arg]''.\n Examples:\n - search[white shoes]\n - click[button=Reviews]\n - click[button=Buy Now]\n \"\"\"\n raise NotImplementedError\n\n\nclass HumanPolicy(BasePolicy):\n def __init__(self):\n super().__init__()\n\n def forward(self, observation, available_actions):\n action = input('> ')\n return action\n\n\nclass RandomPolicy(BasePolicy):\n def __init__(self):\n super().__init__()\n \n def forward(self, observation, available_actions):\n if available_actions['has_search_bar']:\n action = 'search[shoes]'\n else:\n action_arg = random.choice(available_actions['clickables'])\n action = f'click[{action_arg}]'\n return action","source_hash":"229b2f2fb0feedcac84a8e7ed6484c976e4c0ccb026e22996052215c427445a7","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.models.models.RandomPolicy","uri":"program://BOLAA/class/webshop.web_agent_site.models.models.RandomPolicy#L42-L52","kind":"class","name":"RandomPolicy","path":"webshop/web_agent_site/models/models.py","language":"python","start_line":42,"end_line":52,"context_start_line":22,"context_end_line":52,"code":" Returns:\n action (`str`): \n Return string of the format ``action_name[action_arg]''.\n Examples:\n - search[white shoes]\n - click[button=Reviews]\n - click[button=Buy Now]\n \"\"\"\n raise NotImplementedError\n\n\nclass HumanPolicy(BasePolicy):\n def __init__(self):\n super().__init__()\n\n def forward(self, observation, available_actions):\n action = input('> ')\n return action\n\n\nclass RandomPolicy(BasePolicy):\n def __init__(self):\n super().__init__()\n \n def forward(self, observation, available_actions):\n if available_actions['has_search_bar']:\n action = 'search[shoes]'\n else:\n action_arg = random.choice(available_actions['clickables'])\n action = f'click[{action_arg}]'\n return action","source_hash":"229b2f2fb0feedcac84a8e7ed6484c976e4c0ccb026e22996052215c427445a7","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.models.models.__init__","uri":"program://BOLAA/function/webshop.web_agent_site.models.models.__init__#L43-L44","kind":"function","name":"__init__","path":"webshop/web_agent_site/models/models.py","language":"python","start_line":43,"end_line":44,"context_start_line":23,"context_end_line":52,"code":" action (`str`): \n Return string of the format ``action_name[action_arg]''.\n Examples:\n - search[white shoes]\n - click[button=Reviews]\n - click[button=Buy Now]\n \"\"\"\n raise NotImplementedError\n\n\nclass HumanPolicy(BasePolicy):\n def __init__(self):\n super().__init__()\n\n def forward(self, observation, available_actions):\n action = input('> ')\n return action\n\n\nclass RandomPolicy(BasePolicy):\n def __init__(self):\n super().__init__()\n \n def forward(self, observation, available_actions):\n if available_actions['has_search_bar']:\n action = 'search[shoes]'\n else:\n action_arg = random.choice(available_actions['clickables'])\n action = f'click[{action_arg}]'\n return action","source_hash":"229b2f2fb0feedcac84a8e7ed6484c976e4c0ccb026e22996052215c427445a7","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.models.models.forward","uri":"program://BOLAA/function/webshop.web_agent_site.models.models.forward#L46-L52","kind":"function","name":"forward","path":"webshop/web_agent_site/models/models.py","language":"python","start_line":46,"end_line":52,"context_start_line":26,"context_end_line":52,"code":" - search[white shoes]\n - click[button=Reviews]\n - click[button=Buy Now]\n \"\"\"\n raise NotImplementedError\n\n\nclass HumanPolicy(BasePolicy):\n def __init__(self):\n super().__init__()\n\n def forward(self, observation, available_actions):\n action = input('> ')\n return action\n\n\nclass RandomPolicy(BasePolicy):\n def __init__(self):\n super().__init__()\n \n def forward(self, observation, available_actions):\n if available_actions['has_search_bar']:\n action = 'search[shoes]'\n else:\n action_arg = random.choice(available_actions['clickables'])\n action = f'click[{action_arg}]'\n return action","source_hash":"229b2f2fb0feedcac84a8e7ed6484c976e4c0ccb026e22996052215c427445a7","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.attributes.generate_attrs","uri":"program://BOLAA/module/webshop.web_agent_site.attributes.generate_attrs#L1-L171","kind":"module","name":"webshop.web_agent_site.attributes.generate_attrs","path":"webshop/web_agent_site/attributes/generate_attrs.py","language":"python","start_line":1,"end_line":171,"context_start_line":1,"context_end_line":171,"code":"import json\nimport yaml\nimport random\nfrom pathlib import Path\nfrom collections import defaultdict\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_extraction import text as sk_text\nimport pandas as pd\nfrom tqdm import tqdm\nfrom rich import print\n\nITEMS_PATH = './data/ITEMS_mar1.json'\nREVIEWS_PATH = './data/reviews.json'\nATTR_DIR = './data/attributes'\n\nrandom.seed(0)\n\n\ndef get_stop_words():\n extra_stop_words = set([str(i) for i in range(1000)])\n stop_words = sk_text.ENGLISH_STOP_WORDS.union(extra_stop_words)\n return stop_words\n\n\ndef load_products(num=None):\n \"\"\"\n Loads products from the `items.json` file and combine them with reviews\n through `asin`.\n Return: dict[asin, product]\n \"\"\"\n with open(ITEMS_PATH) as f:\n all_products = json.load(f)\n if num is not None:\n random.shuffle(all_products)\n all_products = all_products[:num]\n products = dict()\n asins = set()\n for p in all_products:\n asin = p['asin']\n if asin in asins:\n continue\n asins.add(asin)\n products[asin] = p\n\n with open(REVIEWS_PATH) as f:\n reviews = json.load(f)\n reviews = {r['asin']: r for r in reviews}\n\n for asin, p in products.items():\n if asin in reviews:\n p['review'] = reviews[asin]\n else:\n p['review'] = None\n return products\n\n\ndef get_top_attrs(attributes, k):\n attr_to_asins = defaultdict(list)\n\n for asin, attr_scores in attributes.items():\n top_attr_scoress = attr_scores[:k]\n for attr, score in top_attr_scoress:\n attr_to_asins[attr].append(asin)\n total = len([asin for asin, _ in attributes.items()])\n \n top_attrs = [\n (attr, len(asins) / total)\n for attr, asins in attr_to_asins.items()\n ]\n top_attrs = sorted(top_attrs, key=lambda x: -x[1])\n top_attrs = [f'{attr} | {score:.4f}' for attr, score in top_attrs]\n return top_attrs\n\n\ndef get_corpus(\n products,\n keys=('name', 'small_description'),\n category_type='category'\n ):\n \"\"\"\n keys: `name`, `small_description`, `review`\n category_type: `category`, `query`\n \"\"\"\n all_products = list(products.values())\n \n asins_by_cat = defaultdict(set)\n corpus_by_cat = defaultdict(list)\n for p in all_products:\n category = p[category_type]\n asin = p['asin']\n if asin in asins_by_cat[category]:\n continue\n asins_by_cat[category].add(asin)\n\n text = []\n for key in keys:\n if key == 'review':\n rs = p['review']['reviews']\n if r is not None:\n text_ = ' '.join([r['review'].lower() for r in rs])\n else:\n text_ = ''\n else:\n text_ = p[key].lower()\n text.append(text_)\n text = ' '.join(text)\n corpus_by_cat[category].append((asin, text))\n return corpus_by_cat\n\n\ndef generate_ngram_attrs(corpus_by_cat, ngram_range, k, attrs):\n vectorizer = TfidfVectorizer(\n stop_words=get_stop_words(),\n ngram_range=ngram_range,\n max_features=1000,\n )\n\n top_attrs_by_cat = dict()\n for category, corpus in tqdm(corpus_by_cat.items(),\n total=len(corpus_by_cat)):\n asins = [_[0] for _ in corpus]\n texts = [_[1] for _ in corpus]\n vec = vectorizer.fit_transform(texts).todense()\n df = pd.DataFrame(vec, columns=vectorizer.get_feature_names_out())\n\n attrs_by_cat = dict()\n for asin, (row_name, row) in zip(asins, df.iterrows()):\n attr_scores = sorted(\n list(zip(row.index, row)),\n key=lambda x: -x[1]\n )\n attrs_by_cat[asin] = attr_scores\n attrs[asin] = attr_scores\n top_attrs_by_cat[category.lower()] = get_top_attrs(attrs_by_cat, k=k)\n print(top_attrs_by_cat.keys())\n return top_attrs_by_cat\n\n\ndef generate_attrs(corpus_by_cat, k, save_name):\n attrs = dict()\n for n in range(1, 3):\n ngram_range = (n, n)\n top_attrs_by_cat = \\\n generate_ngram_attrs(corpus_by_cat, ngram_range, k, attrs)\n\n if save_name is not None:\n save_path = Path(ATTR_DIR) / f'{save_name}_{n}-gram.yaml'\n with open(save_path, 'w') as f:\n yaml.dump(top_attrs_by_cat, f, default_flow_style=False)\n print(f'Saved: {save_path}')\n\n save_path = Path(ATTR_DIR) / f'{save_name}_attrs_unfiltered.json'\n with open(save_path, 'w') as f:\n json.dump(attrs, f)\n print(f'Saved: {save_path}')\n\n\nif __name__ == '__main__':\n \"\"\"\n python -m web_agent_site.attributes.generate_attrs\n\n Inspect in notebooks/attributes.ipynb.\n \"\"\"\n products = load_products(num=40000)\n\n corpus_by_cat_broad = get_corpus(products, category_type='category')\n generate_attrs(corpus_by_cat_broad, k=5, save_name='broad')\n\n corpus_by_cat_narrow = get_corpus(products, category_type='query')\n generate_attrs(corpus_by_cat_narrow, k=5, save_name='narrow')","source_hash":"b6e079d6765966e1c244e7de31d444c17423d912d24f0ef08844c32daa2efe3a","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.attributes.generate_attrs.get_stop_words","uri":"program://BOLAA/function/webshop.web_agent_site.attributes.generate_attrs.get_stop_words#L20-L23","kind":"function","name":"get_stop_words","path":"webshop/web_agent_site/attributes/generate_attrs.py","language":"python","start_line":20,"end_line":23,"context_start_line":1,"context_end_line":43,"code":"import json\nimport yaml\nimport random\nfrom pathlib import Path\nfrom collections import defaultdict\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_extraction import text as sk_text\nimport pandas as pd\nfrom tqdm import tqdm\nfrom rich import print\n\nITEMS_PATH = './data/ITEMS_mar1.json'\nREVIEWS_PATH = './data/reviews.json'\nATTR_DIR = './data/attributes'\n\nrandom.seed(0)\n\n\ndef get_stop_words():\n extra_stop_words = set([str(i) for i in range(1000)])\n stop_words = sk_text.ENGLISH_STOP_WORDS.union(extra_stop_words)\n return stop_words\n\n\ndef load_products(num=None):\n \"\"\"\n Loads products from the `items.json` file and combine them with reviews\n through `asin`.\n Return: dict[asin, product]\n \"\"\"\n with open(ITEMS_PATH) as f:\n all_products = json.load(f)\n if num is not None:\n random.shuffle(all_products)\n all_products = all_products[:num]\n products = dict()\n asins = set()\n for p in all_products:\n asin = p['asin']\n if asin in asins:\n continue\n asins.add(asin)","source_hash":"b6e079d6765966e1c244e7de31d444c17423d912d24f0ef08844c32daa2efe3a","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.attributes.generate_attrs.load_products","uri":"program://BOLAA/function/webshop.web_agent_site.attributes.generate_attrs.load_products#L26-L55","kind":"function","name":"load_products","path":"webshop/web_agent_site/attributes/generate_attrs.py","language":"python","start_line":26,"end_line":55,"context_start_line":6,"context_end_line":75,"code":"\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_extraction import text as sk_text\nimport pandas as pd\nfrom tqdm import tqdm\nfrom rich import print\n\nITEMS_PATH = './data/ITEMS_mar1.json'\nREVIEWS_PATH = './data/reviews.json'\nATTR_DIR = './data/attributes'\n\nrandom.seed(0)\n\n\ndef get_stop_words():\n extra_stop_words = set([str(i) for i in range(1000)])\n stop_words = sk_text.ENGLISH_STOP_WORDS.union(extra_stop_words)\n return stop_words\n\n\ndef load_products(num=None):\n \"\"\"\n Loads products from the `items.json` file and combine them with reviews\n through `asin`.\n Return: dict[asin, product]\n \"\"\"\n with open(ITEMS_PATH) as f:\n all_products = json.load(f)\n if num is not None:\n random.shuffle(all_products)\n all_products = all_products[:num]\n products = dict()\n asins = set()\n for p in all_products:\n asin = p['asin']\n if asin in asins:\n continue\n asins.add(asin)\n products[asin] = p\n\n with open(REVIEWS_PATH) as f:\n reviews = json.load(f)\n reviews = {r['asin']: r for r in reviews}\n\n for asin, p in products.items():\n if asin in reviews:\n p['review'] = reviews[asin]\n else:\n p['review'] = None\n return products\n\n\ndef get_top_attrs(attributes, k):\n attr_to_asins = defaultdict(list)\n\n for asin, attr_scores in attributes.items():\n top_attr_scoress = attr_scores[:k]\n for attr, score in top_attr_scoress:\n attr_to_asins[attr].append(asin)\n total = len([asin for asin, _ in attributes.items()])\n \n top_attrs = [\n (attr, len(asins) / total)\n for attr, asins in attr_to_asins.items()\n ]\n top_attrs = sorted(top_attrs, key=lambda x: -x[1])\n top_attrs = [f'{attr} | {score:.4f}' for attr, score in top_attrs]\n return top_attrs\n\n","source_hash":"b6e079d6765966e1c244e7de31d444c17423d912d24f0ef08844c32daa2efe3a","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.attributes.generate_attrs.get_top_attrs","uri":"program://BOLAA/function/webshop.web_agent_site.attributes.generate_attrs.get_top_attrs#L58-L73","kind":"function","name":"get_top_attrs","path":"webshop/web_agent_site/attributes/generate_attrs.py","language":"python","start_line":58,"end_line":73,"context_start_line":38,"context_end_line":93,"code":" asins = set()\n for p in all_products:\n asin = p['asin']\n if asin in asins:\n continue\n asins.add(asin)\n products[asin] = p\n\n with open(REVIEWS_PATH) as f:\n reviews = json.load(f)\n reviews = {r['asin']: r for r in reviews}\n\n for asin, p in products.items():\n if asin in reviews:\n p['review'] = reviews[asin]\n else:\n p['review'] = None\n return products\n\n\ndef get_top_attrs(attributes, k):\n attr_to_asins = defaultdict(list)\n\n for asin, attr_scores in attributes.items():\n top_attr_scoress = attr_scores[:k]\n for attr, score in top_attr_scoress:\n attr_to_asins[attr].append(asin)\n total = len([asin for asin, _ in attributes.items()])\n \n top_attrs = [\n (attr, len(asins) / total)\n for attr, asins in attr_to_asins.items()\n ]\n top_attrs = sorted(top_attrs, key=lambda x: -x[1])\n top_attrs = [f'{attr} | {score:.4f}' for attr, score in top_attrs]\n return top_attrs\n\n\ndef get_corpus(\n products,\n keys=('name', 'small_description'),\n category_type='category'\n ):\n \"\"\"\n keys: `name`, `small_description`, `review`\n category_type: `category`, `query`\n \"\"\"\n all_products = list(products.values())\n \n asins_by_cat = defaultdict(set)\n corpus_by_cat = defaultdict(list)\n for p in all_products:\n category = p[category_type]\n asin = p['asin']\n if asin in asins_by_cat[category]:\n continue","source_hash":"b6e079d6765966e1c244e7de31d444c17423d912d24f0ef08844c32daa2efe3a","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.attributes.generate_attrs.get_corpus","uri":"program://BOLAA/function/webshop.web_agent_site.attributes.generate_attrs.get_corpus#L76-L109","kind":"function","name":"get_corpus","path":"webshop/web_agent_site/attributes/generate_attrs.py","language":"python","start_line":76,"end_line":109,"context_start_line":56,"context_end_line":129,"code":"\n\ndef get_top_attrs(attributes, k):\n attr_to_asins = defaultdict(list)\n\n for asin, attr_scores in attributes.items():\n top_attr_scoress = attr_scores[:k]\n for attr, score in top_attr_scoress:\n attr_to_asins[attr].append(asin)\n total = len([asin for asin, _ in attributes.items()])\n \n top_attrs = [\n (attr, len(asins) / total)\n for attr, asins in attr_to_asins.items()\n ]\n top_attrs = sorted(top_attrs, key=lambda x: -x[1])\n top_attrs = [f'{attr} | {score:.4f}' for attr, score in top_attrs]\n return top_attrs\n\n\ndef get_corpus(\n products,\n keys=('name', 'small_description'),\n category_type='category'\n ):\n \"\"\"\n keys: `name`, `small_description`, `review`\n category_type: `category`, `query`\n \"\"\"\n all_products = list(products.values())\n \n asins_by_cat = defaultdict(set)\n corpus_by_cat = defaultdict(list)\n for p in all_products:\n category = p[category_type]\n asin = p['asin']\n if asin in asins_by_cat[category]:\n continue\n asins_by_cat[category].add(asin)\n\n text = []\n for key in keys:\n if key == 'review':\n rs = p['review']['reviews']\n if r is not None:\n text_ = ' '.join([r['review'].lower() for r in rs])\n else:\n text_ = ''\n else:\n text_ = p[key].lower()\n text.append(text_)\n text = ' '.join(text)\n corpus_by_cat[category].append((asin, text))\n return corpus_by_cat\n\n\ndef generate_ngram_attrs(corpus_by_cat, ngram_range, k, attrs):\n vectorizer = TfidfVectorizer(\n stop_words=get_stop_words(),\n ngram_range=ngram_range,\n max_features=1000,\n )\n\n top_attrs_by_cat = dict()\n for category, corpus in tqdm(corpus_by_cat.items(),\n total=len(corpus_by_cat)):\n asins = [_[0] for _ in corpus]\n texts = [_[1] for _ in corpus]\n vec = vectorizer.fit_transform(texts).todense()\n df = pd.DataFrame(vec, columns=vectorizer.get_feature_names_out())\n\n attrs_by_cat = dict()\n for asin, (row_name, row) in zip(asins, df.iterrows()):\n attr_scores = sorted(","source_hash":"b6e079d6765966e1c244e7de31d444c17423d912d24f0ef08844c32daa2efe3a","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.attributes.generate_attrs.generate_ngram_attrs","uri":"program://BOLAA/function/webshop.web_agent_site.attributes.generate_attrs.generate_ngram_attrs#L112-L137","kind":"function","name":"generate_ngram_attrs","path":"webshop/web_agent_site/attributes/generate_attrs.py","language":"python","start_line":112,"end_line":137,"context_start_line":92,"context_end_line":157,"code":" if asin in asins_by_cat[category]:\n continue\n asins_by_cat[category].add(asin)\n\n text = []\n for key in keys:\n if key == 'review':\n rs = p['review']['reviews']\n if r is not None:\n text_ = ' '.join([r['review'].lower() for r in rs])\n else:\n text_ = ''\n else:\n text_ = p[key].lower()\n text.append(text_)\n text = ' '.join(text)\n corpus_by_cat[category].append((asin, text))\n return corpus_by_cat\n\n\ndef generate_ngram_attrs(corpus_by_cat, ngram_range, k, attrs):\n vectorizer = TfidfVectorizer(\n stop_words=get_stop_words(),\n ngram_range=ngram_range,\n max_features=1000,\n )\n\n top_attrs_by_cat = dict()\n for category, corpus in tqdm(corpus_by_cat.items(),\n total=len(corpus_by_cat)):\n asins = [_[0] for _ in corpus]\n texts = [_[1] for _ in corpus]\n vec = vectorizer.fit_transform(texts).todense()\n df = pd.DataFrame(vec, columns=vectorizer.get_feature_names_out())\n\n attrs_by_cat = dict()\n for asin, (row_name, row) in zip(asins, df.iterrows()):\n attr_scores = sorted(\n list(zip(row.index, row)),\n key=lambda x: -x[1]\n )\n attrs_by_cat[asin] = attr_scores\n attrs[asin] = attr_scores\n top_attrs_by_cat[category.lower()] = get_top_attrs(attrs_by_cat, k=k)\n print(top_attrs_by_cat.keys())\n return top_attrs_by_cat\n\n\ndef generate_attrs(corpus_by_cat, k, save_name):\n attrs = dict()\n for n in range(1, 3):\n ngram_range = (n, n)\n top_attrs_by_cat = \\\n generate_ngram_attrs(corpus_by_cat, ngram_range, k, attrs)\n\n if save_name is not None:\n save_path = Path(ATTR_DIR) / f'{save_name}_{n}-gram.yaml'\n with open(save_path, 'w') as f:\n yaml.dump(top_attrs_by_cat, f, default_flow_style=False)\n print(f'Saved: {save_path}')\n\n save_path = Path(ATTR_DIR) / f'{save_name}_attrs_unfiltered.json'\n with open(save_path, 'w') as f:\n json.dump(attrs, f)\n print(f'Saved: {save_path}')\n","source_hash":"b6e079d6765966e1c244e7de31d444c17423d912d24f0ef08844c32daa2efe3a","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.attributes.generate_attrs.generate_attrs","uri":"program://BOLAA/function/webshop.web_agent_site.attributes.generate_attrs.generate_attrs#L140-L156","kind":"function","name":"generate_attrs","path":"webshop/web_agent_site/attributes/generate_attrs.py","language":"python","start_line":140,"end_line":156,"context_start_line":120,"context_end_line":171,"code":" for category, corpus in tqdm(corpus_by_cat.items(),\n total=len(corpus_by_cat)):\n asins = [_[0] for _ in corpus]\n texts = [_[1] for _ in corpus]\n vec = vectorizer.fit_transform(texts).todense()\n df = pd.DataFrame(vec, columns=vectorizer.get_feature_names_out())\n\n attrs_by_cat = dict()\n for asin, (row_name, row) in zip(asins, df.iterrows()):\n attr_scores = sorted(\n list(zip(row.index, row)),\n key=lambda x: -x[1]\n )\n attrs_by_cat[asin] = attr_scores\n attrs[asin] = attr_scores\n top_attrs_by_cat[category.lower()] = get_top_attrs(attrs_by_cat, k=k)\n print(top_attrs_by_cat.keys())\n return top_attrs_by_cat\n\n\ndef generate_attrs(corpus_by_cat, k, save_name):\n attrs = dict()\n for n in range(1, 3):\n ngram_range = (n, n)\n top_attrs_by_cat = \\\n generate_ngram_attrs(corpus_by_cat, ngram_range, k, attrs)\n\n if save_name is not None:\n save_path = Path(ATTR_DIR) / f'{save_name}_{n}-gram.yaml'\n with open(save_path, 'w') as f:\n yaml.dump(top_attrs_by_cat, f, default_flow_style=False)\n print(f'Saved: {save_path}')\n\n save_path = Path(ATTR_DIR) / f'{save_name}_attrs_unfiltered.json'\n with open(save_path, 'w') as f:\n json.dump(attrs, f)\n print(f'Saved: {save_path}')\n\n\nif __name__ == '__main__':\n \"\"\"\n python -m web_agent_site.attributes.generate_attrs\n\n Inspect in notebooks/attributes.ipynb.\n \"\"\"\n products = load_products(num=40000)\n\n corpus_by_cat_broad = get_corpus(products, category_type='category')\n generate_attrs(corpus_by_cat_broad, k=5, save_name='broad')\n\n corpus_by_cat_narrow = get_corpus(products, category_type='query')\n generate_attrs(corpus_by_cat_narrow, k=5, save_name='narrow')","source_hash":"b6e079d6765966e1c244e7de31d444c17423d912d24f0ef08844c32daa2efe3a","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.attributes.annotate","uri":"program://BOLAA/module/webshop.web_agent_site.attributes.annotate#L1-L70","kind":"module","name":"webshop.web_agent_site.attributes.annotate","path":"webshop/web_agent_site/attributes/annotate.py","language":"python","start_line":1,"end_line":70,"context_start_line":1,"context_end_line":70,"code":"import yaml\nfrom pathlib import Path\nfrom rich import print\n\nATTR_DIR = './data/attributes'\n\nATTR_PATHS = [\n 'narrow_2-gram.yaml',\n 'narrow_1-gram.yaml',\n 'broad_2-gram.yaml',\n 'broad_1-gram.yaml',\n]\nATTR_PATHS = [Path(ATTR_DIR) / af for af in ATTR_PATHS]\n\n\ndef annotate(attr_path):\n with open(attr_path) as f:\n attrs_by_cat = yaml.safe_load(f)\n\n unique_attrs = set()\n all_attrs = []\n for _, attrs in attrs_by_cat.items():\n attrs = [a.split('|')[0].strip() for a in attrs]\n unique_attrs.update(attrs)\n all_attrs += attrs\n print(f'Total unique attributes: {len(unique_attrs)}')\n total = len(all_attrs)\n num_left = len(all_attrs)\n\n annotated_attrs_by_cat = dict()\n for category, attrs in attrs_by_cat.items():\n print(\n f'Category: [ {category} ] | '\n f'Number of attributes: {len(attrs)}\\n'\n )\n annotated_attrs = []\n for i, attr in enumerate(attrs):\n attr, score = attr.split(' | ')\n print(\n f'{\"[\" + str(i) + \"]\":<5} '\n f'[bold green]{attr:<30}[/bold green] | '\n f'[red]{category}[/red] | '\n f'{score}'\n )\n tags = input(\n 'Annotate [1: ITEM, 2: PROP, 3: USE, '\n '⎵: next example, q: next category] > '\n )\n print('\\n')\n tags = tags.strip()\n annotated_attrs.append(f'{attr} | {score} | {tags}')\n if 'q' in tags:\n break\n \n num_left -= len(attrs)\n print(f'{num_left} / {total} total attributes left.')\n\n ans = input('Starting the next category... [y/n] > ')\n if ans == 'n':\n break\n\ndef main():\n for attr_path in ATTR_PATHS:\n annotate(attr_path)\n\nif __name__ == '__main__':\n \"\"\"\n python -m web_agent_site.attributes.annotate\n \"\"\"\n main()","source_hash":"f64f3f8be3af15794821506014b97c1abc75424973ab9b06d4af4b9c2dec4a45","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.attributes.annotate.annotate","uri":"program://BOLAA/function/webshop.web_agent_site.attributes.annotate.annotate#L16-L60","kind":"function","name":"annotate","path":"webshop/web_agent_site/attributes/annotate.py","language":"python","start_line":16,"end_line":60,"context_start_line":1,"context_end_line":70,"code":"import yaml\nfrom pathlib import Path\nfrom rich import print\n\nATTR_DIR = './data/attributes'\n\nATTR_PATHS = [\n 'narrow_2-gram.yaml',\n 'narrow_1-gram.yaml',\n 'broad_2-gram.yaml',\n 'broad_1-gram.yaml',\n]\nATTR_PATHS = [Path(ATTR_DIR) / af for af in ATTR_PATHS]\n\n\ndef annotate(attr_path):\n with open(attr_path) as f:\n attrs_by_cat = yaml.safe_load(f)\n\n unique_attrs = set()\n all_attrs = []\n for _, attrs in attrs_by_cat.items():\n attrs = [a.split('|')[0].strip() for a in attrs]\n unique_attrs.update(attrs)\n all_attrs += attrs\n print(f'Total unique attributes: {len(unique_attrs)}')\n total = len(all_attrs)\n num_left = len(all_attrs)\n\n annotated_attrs_by_cat = dict()\n for category, attrs in attrs_by_cat.items():\n print(\n f'Category: [ {category} ] | '\n f'Number of attributes: {len(attrs)}\\n'\n )\n annotated_attrs = []\n for i, attr in enumerate(attrs):\n attr, score = attr.split(' | ')\n print(\n f'{\"[\" + str(i) + \"]\":<5} '\n f'[bold green]{attr:<30}[/bold green] | '\n f'[red]{category}[/red] | '\n f'{score}'\n )\n tags = input(\n 'Annotate [1: ITEM, 2: PROP, 3: USE, '\n '⎵: next example, q: next category] > '\n )\n print('\\n')\n tags = tags.strip()\n annotated_attrs.append(f'{attr} | {score} | {tags}')\n if 'q' in tags:\n break\n \n num_left -= len(attrs)\n print(f'{num_left} / {total} total attributes left.')\n\n ans = input('Starting the next category... [y/n] > ')\n if ans == 'n':\n break\n\ndef main():\n for attr_path in ATTR_PATHS:\n annotate(attr_path)\n\nif __name__ == '__main__':\n \"\"\"\n python -m web_agent_site.attributes.annotate\n \"\"\"\n main()","source_hash":"f64f3f8be3af15794821506014b97c1abc75424973ab9b06d4af4b9c2dec4a45","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.attributes.annotate.main","uri":"program://BOLAA/function/webshop.web_agent_site.attributes.annotate.main#L62-L64","kind":"function","name":"main","path":"webshop/web_agent_site/attributes/annotate.py","language":"python","start_line":62,"end_line":64,"context_start_line":42,"context_end_line":70,"code":" f'[red]{category}[/red] | '\n f'{score}'\n )\n tags = input(\n 'Annotate [1: ITEM, 2: PROP, 3: USE, '\n '⎵: next example, q: next category] > '\n )\n print('\\n')\n tags = tags.strip()\n annotated_attrs.append(f'{attr} | {score} | {tags}')\n if 'q' in tags:\n break\n \n num_left -= len(attrs)\n print(f'{num_left} / {total} total attributes left.')\n\n ans = input('Starting the next category... [y/n] > ')\n if ans == 'n':\n break\n\ndef main():\n for attr_path in ATTR_PATHS:\n annotate(attr_path)\n\nif __name__ == '__main__':\n \"\"\"\n python -m web_agent_site.attributes.annotate\n \"\"\"\n main()","source_hash":"f64f3f8be3af15794821506014b97c1abc75424973ab9b06d4af4b9c2dec4a45","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_site_env","uri":"program://BOLAA/module/webshop.web_agent_site.envs.web_agent_site_env#L1-L217","kind":"module","name":"webshop.web_agent_site.envs.web_agent_site_env","path":"webshop/web_agent_site/envs/web_agent_site_env.py","language":"python","start_line":1,"end_line":217,"context_start_line":1,"context_end_line":217,"code":"import gym\nimport random\nimport requests\nimport string\nimport time\n\nfrom bs4 import BeautifulSoup\nfrom bs4.element import Comment\nfrom gym import spaces\nfrom os.path import join, dirname, abspath\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.common.exceptions import ElementNotInteractableException\nfrom web_agent_site.engine.engine import parse_action, END_BUTTON\n\nclass WebAgentSiteEnv(gym.Env):\n \"\"\"Gym environment for HTML mode of WebShop environment\"\"\"\n\n def __init__(self, observation_mode='html', **kwargs):\n \"\"\"\n Constructor for HTML environment\n\n Arguments:\n observation_mode (`str`) -- ['html' | 'text'] (default 'html')\n pause (`float`) -- Pause (in seconds) after taking an action. \n This is mainly for demo purposes.\n Recommended value: 2.0s\n render (`bool`) -- Show browser if set to `True`.\n session ('str') -- Session ID to initialize environment with\n \"\"\"\n super(WebAgentSiteEnv, self).__init__()\n self.observation_mode = observation_mode\n self.kwargs = kwargs\n\n # Create a browser driver to simulate the WebShop site\n service = Service(join(dirname(abspath(__file__)), 'chromedriver'))\n options = Options()\n if 'render' not in kwargs or not kwargs['render']:\n options.add_argument(\"--headless\") # don't show browser\n self.browser = webdriver.Chrome(service=service, options=options)\n\n # Set flags and values for WebShop session\n self.text_to_clickable = None\n self.assigned_session = kwargs.get('session')\n self.session = None\n self.reset()\n\n def step(self, action):\n \"\"\"\n Takes an action, updates WebShop environment, and returns (observation, reward, done, info)\n\n Arguments:\n action (`str`): An action should be of the following structure:\n - search[keywords]\n - click[value]\n If action not valid, perform nothing.\n \"\"\"\n reward = 0.0\n done = False\n info = None\n\n # Map action to executed command on the WebShop environment via the broswer driver\n action_name, action_arg = parse_action(action)\n if action_name == 'search':\n try:\n search_bar = self.browser.find_element_by_id('search_input')\n except Exception:\n pass\n else:\n search_bar.send_keys(action_arg)\n search_bar.submit()\n elif action_name == 'click':\n try:\n self.text_to_clickable[action_arg].click()\n except ElementNotInteractableException:\n # Perform force click with JavaScript\n button = self.text_to_clickable[action_arg]\n self.browser.execute_script(\"arguments[0].click();\", button)\n reward = self.get_reward()\n if action_arg == END_BUTTON:\n done = True\n elif action_name == 'end':\n done = True\n else:\n print('Invalid action. No action performed.')\n\n if 'pause' in self.kwargs:\n time.sleep(self.kwargs['pause'])\n return self.observation, reward, done, info\n \n def get_available_actions(self):\n \"\"\"Returns list of available actions at the current step\"\"\"\n # Determine if a search bar is available\n try:\n search_bar = self.browser.find_element_by_id('search_input')\n except Exception:\n has_search_bar = False\n else:\n has_search_bar = True\n\n # Collect buttons, links, and options as clickables\n buttons = self.browser.find_elements_by_class_name('btn')\n product_links = self.browser.find_elements_by_class_name('product-link')\n buying_options = self.browser.find_elements_by_css_selector(\"input[type='radio']\")\n\n self.text_to_clickable = {\n f'{b.text}': b\n for b in buttons + product_links\n }\n for opt in buying_options:\n opt_value = opt.get_attribute('value')\n self.text_to_clickable[f'{opt_value}'] = opt\n return dict(\n has_search_bar=has_search_bar,\n clickables=list(self.text_to_clickable.keys()),\n )\n\n def _parse_html(self, html=None, url=None):\n \"\"\"\n Returns web request result wrapped in BeautifulSoup object\n\n Arguments:\n url (`str`): If no url or html is provided, use the current\n observation (HTML) for parsing.\n \"\"\"\n if html is None:\n if url is not None:\n html = requests.get(url)\n else:\n html = self.state['html']\n html_obj = BeautifulSoup(html, 'html.parser')\n return html_obj\n\n def get_reward(self):\n \"\"\"Get reward value at current step of the environment\"\"\"\n html_obj = self._parse_html()\n r = html_obj.find(id='reward')\n r = float(r.findChildren(\"pre\")[0].string) if r is not None else 0.0\n return r\n \n def get_instruction_text(self):\n \"\"\"Get corresponding instruction text for environment current step\"\"\"\n html_obj = self._parse_html(self.browser.page_source)\n instruction_text = html_obj.find(id='instruction-text').h4.text\n return instruction_text\n \n def convert_html_to_text(self, html):\n \"\"\"Strip HTML of tags and add separators to convert observation into simple mode\"\"\"\n texts = self._parse_html(html).findAll(text=True)\n visible_texts = filter(tag_visible, texts)\n observation = ' [SEP] '.join(t.strip() for t in visible_texts if t != '\\n')\n return observation\n \n @property\n def state(self):\n \"\"\"\n State that includes all information. The actual observation are\n likely to be a subset or reduced form of the state.\n \"\"\"\n return dict(\n url=self.browser.current_url,\n html=self.browser.page_source,\n instruction_text=self.instruction_text,\n )\n \n @property\n def observation(self):\n \"\"\"Compiles state into either the `html` or `text` observation mode\"\"\"\n html = self.state['html']\n if self.observation_mode == 'html':\n return html\n elif self.observation_mode == 'text':\n return self.convert_html_to_text(html)\n else:\n raise ValueError(\n f'Observation mode {self.observation_mode} not supported.'\n )\n\n @property\n def action_space(self):\n # Recommended to use `get_available_actions` instead\n return NotImplementedError\n\n @property\n def observation_space(self):\n return NotImplementedError\n\n def reset(self):\n \"\"\"Create a new session and reset environment variables\"\"\"\n if self.assigned_session is not None:\n self.session = self.assigned_session\n else:\n self.session = ''.join(random.choices(string.ascii_lowercase, k=5))\n init_url = f'http://127.0.0.1:3000/{self.session}'\n self.browser.get(init_url)\n\n self.instruction_text = self.get_instruction_text()\n\n return self.observation, None\n\n def render(self, mode='human'):\n # TODO: Render observation in terminal or WebShop website\n return NotImplementedError\n\n def close(self):\n # TODO: When DB used instead of JSONs, tear down DB here\n self.browser.close()\n print('Browser closed.')\n\ndef tag_visible(element):\n \"\"\"Helper method to strip HTML block of extraneous tags\"\"\"\n ignore = {'style', 'script', 'head', 'title', 'meta', '[document]'}\n return (\n element.parent.name not in ignore and not isinstance(element, Comment)\n )","source_hash":"7b3a43c0250ef2215e2ac1e613ebafbcfbea053a24fcbb773541dc634f124981","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_site_env.WebAgentSiteEnv","uri":"program://BOLAA/class/webshop.web_agent_site.envs.web_agent_site_env.WebAgentSiteEnv#L18-L210","kind":"class","name":"WebAgentSiteEnv","path":"webshop/web_agent_site/envs/web_agent_site_env.py","language":"python","start_line":18,"end_line":210,"context_start_line":1,"context_end_line":217,"code":"import gym\nimport random\nimport requests\nimport string\nimport time\n\nfrom bs4 import BeautifulSoup\nfrom bs4.element import Comment\nfrom gym import spaces\nfrom os.path import join, dirname, abspath\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.common.exceptions import ElementNotInteractableException\nfrom web_agent_site.engine.engine import parse_action, END_BUTTON\n\nclass WebAgentSiteEnv(gym.Env):\n \"\"\"Gym environment for HTML mode of WebShop environment\"\"\"\n\n def __init__(self, observation_mode='html', **kwargs):\n \"\"\"\n Constructor for HTML environment\n\n Arguments:\n observation_mode (`str`) -- ['html' | 'text'] (default 'html')\n pause (`float`) -- Pause (in seconds) after taking an action. \n This is mainly for demo purposes.\n Recommended value: 2.0s\n render (`bool`) -- Show browser if set to `True`.\n session ('str') -- Session ID to initialize environment with\n \"\"\"\n super(WebAgentSiteEnv, self).__init__()\n self.observation_mode = observation_mode\n self.kwargs = kwargs\n\n # Create a browser driver to simulate the WebShop site\n service = Service(join(dirname(abspath(__file__)), 'chromedriver'))\n options = Options()\n if 'render' not in kwargs or not kwargs['render']:\n options.add_argument(\"--headless\") # don't show browser\n self.browser = webdriver.Chrome(service=service, options=options)\n\n # Set flags and values for WebShop session\n self.text_to_clickable = None\n self.assigned_session = kwargs.get('session')\n self.session = None\n self.reset()\n\n def step(self, action):\n \"\"\"\n Takes an action, updates WebShop environment, and returns (observation, reward, done, info)\n\n Arguments:\n action (`str`): An action should be of the following structure:\n - search[keywords]\n - click[value]\n If action not valid, perform nothing.\n \"\"\"\n reward = 0.0\n done = False\n info = None\n\n # Map action to executed command on the WebShop environment via the broswer driver\n action_name, action_arg = parse_action(action)\n if action_name == 'search':\n try:\n search_bar = self.browser.find_element_by_id('search_input')\n except Exception:\n pass\n else:\n search_bar.send_keys(action_arg)\n search_bar.submit()\n elif action_name == 'click':\n try:\n self.text_to_clickable[action_arg].click()\n except ElementNotInteractableException:\n # Perform force click with JavaScript\n button = self.text_to_clickable[action_arg]\n self.browser.execute_script(\"arguments[0].click();\", button)\n reward = self.get_reward()\n if action_arg == END_BUTTON:\n done = True\n elif action_name == 'end':\n done = True\n else:\n print('Invalid action. No action performed.')\n\n if 'pause' in self.kwargs:\n time.sleep(self.kwargs['pause'])\n return self.observation, reward, done, info\n \n def get_available_actions(self):\n \"\"\"Returns list of available actions at the current step\"\"\"\n # Determine if a search bar is available\n try:\n search_bar = self.browser.find_element_by_id('search_input')\n except Exception:\n has_search_bar = False\n else:\n has_search_bar = True\n\n # Collect buttons, links, and options as clickables\n buttons = self.browser.find_elements_by_class_name('btn')\n product_links = self.browser.find_elements_by_class_name('product-link')\n buying_options = self.browser.find_elements_by_css_selector(\"input[type='radio']\")\n\n self.text_to_clickable = {\n f'{b.text}': b\n for b in buttons + product_links\n }\n for opt in buying_options:\n opt_value = opt.get_attribute('value')\n self.text_to_clickable[f'{opt_value}'] = opt\n return dict(\n has_search_bar=has_search_bar,\n clickables=list(self.text_to_clickable.keys()),\n )\n\n def _parse_html(self, html=None, url=None):\n \"\"\"\n Returns web request result wrapped in BeautifulSoup object\n\n Arguments:\n url (`str`): If no url or html is provided, use the current\n observation (HTML) for parsing.\n \"\"\"\n if html is None:\n if url is not None:\n html = requests.get(url)\n else:\n html = self.state['html']\n html_obj = BeautifulSoup(html, 'html.parser')\n return html_obj\n\n def get_reward(self):\n \"\"\"Get reward value at current step of the environment\"\"\"\n html_obj = self._parse_html()\n r = html_obj.find(id='reward')\n r = float(r.findChildren(\"pre\")[0].string) if r is not None else 0.0\n return r\n \n def get_instruction_text(self):\n \"\"\"Get corresponding instruction text for environment current step\"\"\"\n html_obj = self._parse_html(self.browser.page_source)\n instruction_text = html_obj.find(id='instruction-text').h4.text\n return instruction_text\n \n def convert_html_to_text(self, html):\n \"\"\"Strip HTML of tags and add separators to convert observation into simple mode\"\"\"\n texts = self._parse_html(html).findAll(text=True)\n visible_texts = filter(tag_visible, texts)\n observation = ' [SEP] '.join(t.strip() for t in visible_texts if t != '\\n')\n return observation\n \n @property\n def state(self):\n \"\"\"\n State that includes all information. The actual observation are\n likely to be a subset or reduced form of the state.\n \"\"\"\n return dict(\n url=self.browser.current_url,\n html=self.browser.page_source,\n instruction_text=self.instruction_text,\n )\n \n @property\n def observation(self):\n \"\"\"Compiles state into either the `html` or `text` observation mode\"\"\"\n html = self.state['html']\n if self.observation_mode == 'html':\n return html\n elif self.observation_mode == 'text':\n return self.convert_html_to_text(html)\n else:\n raise ValueError(\n f'Observation mode {self.observation_mode} not supported.'\n )\n\n @property\n def action_space(self):\n # Recommended to use `get_available_actions` instead\n return NotImplementedError\n\n @property\n def observation_space(self):\n return NotImplementedError\n\n def reset(self):\n \"\"\"Create a new session and reset environment variables\"\"\"\n if self.assigned_session is not None:\n self.session = self.assigned_session\n else:\n self.session = ''.join(random.choices(string.ascii_lowercase, k=5))\n init_url = f'http://127.0.0.1:3000/{self.session}'\n self.browser.get(init_url)\n\n self.instruction_text = self.get_instruction_text()\n\n return self.observation, None\n\n def render(self, mode='human'):\n # TODO: Render observation in terminal or WebShop website\n return NotImplementedError\n\n def close(self):\n # TODO: When DB used instead of JSONs, tear down DB here\n self.browser.close()\n print('Browser closed.')\n\ndef tag_visible(element):\n \"\"\"Helper method to strip HTML block of extraneous tags\"\"\"\n ignore = {'style', 'script', 'head', 'title', 'meta', '[document]'}\n return (\n element.parent.name not in ignore and not isinstance(element, Comment)\n )","source_hash":"7b3a43c0250ef2215e2ac1e613ebafbcfbea053a24fcbb773541dc634f124981","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_site_env.tag_visible","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_site_env.tag_visible#L212-L217","kind":"function","name":"tag_visible","path":"webshop/web_agent_site/envs/web_agent_site_env.py","language":"python","start_line":212,"end_line":217,"context_start_line":192,"context_end_line":217,"code":" if self.assigned_session is not None:\n self.session = self.assigned_session\n else:\n self.session = ''.join(random.choices(string.ascii_lowercase, k=5))\n init_url = f'http://127.0.0.1:3000/{self.session}'\n self.browser.get(init_url)\n\n self.instruction_text = self.get_instruction_text()\n\n return self.observation, None\n\n def render(self, mode='human'):\n # TODO: Render observation in terminal or WebShop website\n return NotImplementedError\n\n def close(self):\n # TODO: When DB used instead of JSONs, tear down DB here\n self.browser.close()\n print('Browser closed.')\n\ndef tag_visible(element):\n \"\"\"Helper method to strip HTML block of extraneous tags\"\"\"\n ignore = {'style', 'script', 'head', 'title', 'meta', '[document]'}\n return (\n element.parent.name not in ignore and not isinstance(element, Comment)\n )","source_hash":"7b3a43c0250ef2215e2ac1e613ebafbcfbea053a24fcbb773541dc634f124981","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_site_env.__init__","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_site_env.__init__#L21-L48","kind":"function","name":"__init__","path":"webshop/web_agent_site/envs/web_agent_site_env.py","language":"python","start_line":21,"end_line":48,"context_start_line":1,"context_end_line":68,"code":"import gym\nimport random\nimport requests\nimport string\nimport time\n\nfrom bs4 import BeautifulSoup\nfrom bs4.element import Comment\nfrom gym import spaces\nfrom os.path import join, dirname, abspath\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.common.exceptions import ElementNotInteractableException\nfrom web_agent_site.engine.engine import parse_action, END_BUTTON\n\nclass WebAgentSiteEnv(gym.Env):\n \"\"\"Gym environment for HTML mode of WebShop environment\"\"\"\n\n def __init__(self, observation_mode='html', **kwargs):\n \"\"\"\n Constructor for HTML environment\n\n Arguments:\n observation_mode (`str`) -- ['html' | 'text'] (default 'html')\n pause (`float`) -- Pause (in seconds) after taking an action. \n This is mainly for demo purposes.\n Recommended value: 2.0s\n render (`bool`) -- Show browser if set to `True`.\n session ('str') -- Session ID to initialize environment with\n \"\"\"\n super(WebAgentSiteEnv, self).__init__()\n self.observation_mode = observation_mode\n self.kwargs = kwargs\n\n # Create a browser driver to simulate the WebShop site\n service = Service(join(dirname(abspath(__file__)), 'chromedriver'))\n options = Options()\n if 'render' not in kwargs or not kwargs['render']:\n options.add_argument(\"--headless\") # don't show browser\n self.browser = webdriver.Chrome(service=service, options=options)\n\n # Set flags and values for WebShop session\n self.text_to_clickable = None\n self.assigned_session = kwargs.get('session')\n self.session = None\n self.reset()\n\n def step(self, action):\n \"\"\"\n Takes an action, updates WebShop environment, and returns (observation, reward, done, info)\n\n Arguments:\n action (`str`): An action should be of the following structure:\n - search[keywords]\n - click[value]\n If action not valid, perform nothing.\n \"\"\"\n reward = 0.0\n done = False\n info = None\n\n # Map action to executed command on the WebShop environment via the broswer driver\n action_name, action_arg = parse_action(action)\n if action_name == 'search':\n try:\n search_bar = self.browser.find_element_by_id('search_input')","source_hash":"7b3a43c0250ef2215e2ac1e613ebafbcfbea053a24fcbb773541dc634f124981","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_site_env.step","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_site_env.step#L50-L91","kind":"function","name":"step","path":"webshop/web_agent_site/envs/web_agent_site_env.py","language":"python","start_line":50,"end_line":91,"context_start_line":30,"context_end_line":111,"code":" render (`bool`) -- Show browser if set to `True`.\n session ('str') -- Session ID to initialize environment with\n \"\"\"\n super(WebAgentSiteEnv, self).__init__()\n self.observation_mode = observation_mode\n self.kwargs = kwargs\n\n # Create a browser driver to simulate the WebShop site\n service = Service(join(dirname(abspath(__file__)), 'chromedriver'))\n options = Options()\n if 'render' not in kwargs or not kwargs['render']:\n options.add_argument(\"--headless\") # don't show browser\n self.browser = webdriver.Chrome(service=service, options=options)\n\n # Set flags and values for WebShop session\n self.text_to_clickable = None\n self.assigned_session = kwargs.get('session')\n self.session = None\n self.reset()\n\n def step(self, action):\n \"\"\"\n Takes an action, updates WebShop environment, and returns (observation, reward, done, info)\n\n Arguments:\n action (`str`): An action should be of the following structure:\n - search[keywords]\n - click[value]\n If action not valid, perform nothing.\n \"\"\"\n reward = 0.0\n done = False\n info = None\n\n # Map action to executed command on the WebShop environment via the broswer driver\n action_name, action_arg = parse_action(action)\n if action_name == 'search':\n try:\n search_bar = self.browser.find_element_by_id('search_input')\n except Exception:\n pass\n else:\n search_bar.send_keys(action_arg)\n search_bar.submit()\n elif action_name == 'click':\n try:\n self.text_to_clickable[action_arg].click()\n except ElementNotInteractableException:\n # Perform force click with JavaScript\n button = self.text_to_clickable[action_arg]\n self.browser.execute_script(\"arguments[0].click();\", button)\n reward = self.get_reward()\n if action_arg == END_BUTTON:\n done = True\n elif action_name == 'end':\n done = True\n else:\n print('Invalid action. No action performed.')\n\n if 'pause' in self.kwargs:\n time.sleep(self.kwargs['pause'])\n return self.observation, reward, done, info\n \n def get_available_actions(self):\n \"\"\"Returns list of available actions at the current step\"\"\"\n # Determine if a search bar is available\n try:\n search_bar = self.browser.find_element_by_id('search_input')\n except Exception:\n has_search_bar = False\n else:\n has_search_bar = True\n\n # Collect buttons, links, and options as clickables\n buttons = self.browser.find_elements_by_class_name('btn')\n product_links = self.browser.find_elements_by_class_name('product-link')\n buying_options = self.browser.find_elements_by_css_selector(\"input[type='radio']\")\n\n self.text_to_clickable = {\n f'{b.text}': b\n for b in buttons + product_links\n }","source_hash":"7b3a43c0250ef2215e2ac1e613ebafbcfbea053a24fcbb773541dc634f124981","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_site_env.get_available_actions","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_site_env.get_available_actions#L93-L118","kind":"function","name":"get_available_actions","path":"webshop/web_agent_site/envs/web_agent_site_env.py","language":"python","start_line":93,"end_line":118,"context_start_line":73,"context_end_line":138,"code":" search_bar.submit()\n elif action_name == 'click':\n try:\n self.text_to_clickable[action_arg].click()\n except ElementNotInteractableException:\n # Perform force click with JavaScript\n button = self.text_to_clickable[action_arg]\n self.browser.execute_script(\"arguments[0].click();\", button)\n reward = self.get_reward()\n if action_arg == END_BUTTON:\n done = True\n elif action_name == 'end':\n done = True\n else:\n print('Invalid action. No action performed.')\n\n if 'pause' in self.kwargs:\n time.sleep(self.kwargs['pause'])\n return self.observation, reward, done, info\n \n def get_available_actions(self):\n \"\"\"Returns list of available actions at the current step\"\"\"\n # Determine if a search bar is available\n try:\n search_bar = self.browser.find_element_by_id('search_input')\n except Exception:\n has_search_bar = False\n else:\n has_search_bar = True\n\n # Collect buttons, links, and options as clickables\n buttons = self.browser.find_elements_by_class_name('btn')\n product_links = self.browser.find_elements_by_class_name('product-link')\n buying_options = self.browser.find_elements_by_css_selector(\"input[type='radio']\")\n\n self.text_to_clickable = {\n f'{b.text}': b\n for b in buttons + product_links\n }\n for opt in buying_options:\n opt_value = opt.get_attribute('value')\n self.text_to_clickable[f'{opt_value}'] = opt\n return dict(\n has_search_bar=has_search_bar,\n clickables=list(self.text_to_clickable.keys()),\n )\n\n def _parse_html(self, html=None, url=None):\n \"\"\"\n Returns web request result wrapped in BeautifulSoup object\n\n Arguments:\n url (`str`): If no url or html is provided, use the current\n observation (HTML) for parsing.\n \"\"\"\n if html is None:\n if url is not None:\n html = requests.get(url)\n else:\n html = self.state['html']\n html_obj = BeautifulSoup(html, 'html.parser')\n return html_obj\n\n def get_reward(self):\n \"\"\"Get reward value at current step of the environment\"\"\"\n html_obj = self._parse_html()","source_hash":"7b3a43c0250ef2215e2ac1e613ebafbcfbea053a24fcbb773541dc634f124981","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_site_env._parse_html","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_site_env._parse_html#L120-L134","kind":"function","name":"_parse_html","path":"webshop/web_agent_site/envs/web_agent_site_env.py","language":"python","start_line":120,"end_line":134,"context_start_line":100,"context_end_line":154,"code":" else:\n has_search_bar = True\n\n # Collect buttons, links, and options as clickables\n buttons = self.browser.find_elements_by_class_name('btn')\n product_links = self.browser.find_elements_by_class_name('product-link')\n buying_options = self.browser.find_elements_by_css_selector(\"input[type='radio']\")\n\n self.text_to_clickable = {\n f'{b.text}': b\n for b in buttons + product_links\n }\n for opt in buying_options:\n opt_value = opt.get_attribute('value')\n self.text_to_clickable[f'{opt_value}'] = opt\n return dict(\n has_search_bar=has_search_bar,\n clickables=list(self.text_to_clickable.keys()),\n )\n\n def _parse_html(self, html=None, url=None):\n \"\"\"\n Returns web request result wrapped in BeautifulSoup object\n\n Arguments:\n url (`str`): If no url or html is provided, use the current\n observation (HTML) for parsing.\n \"\"\"\n if html is None:\n if url is not None:\n html = requests.get(url)\n else:\n html = self.state['html']\n html_obj = BeautifulSoup(html, 'html.parser')\n return html_obj\n\n def get_reward(self):\n \"\"\"Get reward value at current step of the environment\"\"\"\n html_obj = self._parse_html()\n r = html_obj.find(id='reward')\n r = float(r.findChildren(\"pre\")[0].string) if r is not None else 0.0\n return r\n \n def get_instruction_text(self):\n \"\"\"Get corresponding instruction text for environment current step\"\"\"\n html_obj = self._parse_html(self.browser.page_source)\n instruction_text = html_obj.find(id='instruction-text').h4.text\n return instruction_text\n \n def convert_html_to_text(self, html):\n \"\"\"Strip HTML of tags and add separators to convert observation into simple mode\"\"\"\n texts = self._parse_html(html).findAll(text=True)\n visible_texts = filter(tag_visible, texts)\n observation = ' [SEP] '.join(t.strip() for t in visible_texts if t != '\\n')\n return observation","source_hash":"7b3a43c0250ef2215e2ac1e613ebafbcfbea053a24fcbb773541dc634f124981","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_site_env.get_reward","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_site_env.get_reward#L136-L141","kind":"function","name":"get_reward","path":"webshop/web_agent_site/envs/web_agent_site_env.py","language":"python","start_line":136,"end_line":141,"context_start_line":116,"context_end_line":161,"code":" has_search_bar=has_search_bar,\n clickables=list(self.text_to_clickable.keys()),\n )\n\n def _parse_html(self, html=None, url=None):\n \"\"\"\n Returns web request result wrapped in BeautifulSoup object\n\n Arguments:\n url (`str`): If no url or html is provided, use the current\n observation (HTML) for parsing.\n \"\"\"\n if html is None:\n if url is not None:\n html = requests.get(url)\n else:\n html = self.state['html']\n html_obj = BeautifulSoup(html, 'html.parser')\n return html_obj\n\n def get_reward(self):\n \"\"\"Get reward value at current step of the environment\"\"\"\n html_obj = self._parse_html()\n r = html_obj.find(id='reward')\n r = float(r.findChildren(\"pre\")[0].string) if r is not None else 0.0\n return r\n \n def get_instruction_text(self):\n \"\"\"Get corresponding instruction text for environment current step\"\"\"\n html_obj = self._parse_html(self.browser.page_source)\n instruction_text = html_obj.find(id='instruction-text').h4.text\n return instruction_text\n \n def convert_html_to_text(self, html):\n \"\"\"Strip HTML of tags and add separators to convert observation into simple mode\"\"\"\n texts = self._parse_html(html).findAll(text=True)\n visible_texts = filter(tag_visible, texts)\n observation = ' [SEP] '.join(t.strip() for t in visible_texts if t != '\\n')\n return observation\n \n @property\n def state(self):\n \"\"\"\n State that includes all information. The actual observation are\n likely to be a subset or reduced form of the state.\n \"\"\"","source_hash":"7b3a43c0250ef2215e2ac1e613ebafbcfbea053a24fcbb773541dc634f124981","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_site_env.get_instruction_text","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_site_env.get_instruction_text#L143-L147","kind":"function","name":"get_instruction_text","path":"webshop/web_agent_site/envs/web_agent_site_env.py","language":"python","start_line":143,"end_line":147,"context_start_line":123,"context_end_line":167,"code":"\n Arguments:\n url (`str`): If no url or html is provided, use the current\n observation (HTML) for parsing.\n \"\"\"\n if html is None:\n if url is not None:\n html = requests.get(url)\n else:\n html = self.state['html']\n html_obj = BeautifulSoup(html, 'html.parser')\n return html_obj\n\n def get_reward(self):\n \"\"\"Get reward value at current step of the environment\"\"\"\n html_obj = self._parse_html()\n r = html_obj.find(id='reward')\n r = float(r.findChildren(\"pre\")[0].string) if r is not None else 0.0\n return r\n \n def get_instruction_text(self):\n \"\"\"Get corresponding instruction text for environment current step\"\"\"\n html_obj = self._parse_html(self.browser.page_source)\n instruction_text = html_obj.find(id='instruction-text').h4.text\n return instruction_text\n \n def convert_html_to_text(self, html):\n \"\"\"Strip HTML of tags and add separators to convert observation into simple mode\"\"\"\n texts = self._parse_html(html).findAll(text=True)\n visible_texts = filter(tag_visible, texts)\n observation = ' [SEP] '.join(t.strip() for t in visible_texts if t != '\\n')\n return observation\n \n @property\n def state(self):\n \"\"\"\n State that includes all information. The actual observation are\n likely to be a subset or reduced form of the state.\n \"\"\"\n return dict(\n url=self.browser.current_url,\n html=self.browser.page_source,\n instruction_text=self.instruction_text,\n )\n ","source_hash":"7b3a43c0250ef2215e2ac1e613ebafbcfbea053a24fcbb773541dc634f124981","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_site_env.convert_html_to_text","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_site_env.convert_html_to_text#L149-L154","kind":"function","name":"convert_html_to_text","path":"webshop/web_agent_site/envs/web_agent_site_env.py","language":"python","start_line":149,"end_line":154,"context_start_line":129,"context_end_line":174,"code":" if url is not None:\n html = requests.get(url)\n else:\n html = self.state['html']\n html_obj = BeautifulSoup(html, 'html.parser')\n return html_obj\n\n def get_reward(self):\n \"\"\"Get reward value at current step of the environment\"\"\"\n html_obj = self._parse_html()\n r = html_obj.find(id='reward')\n r = float(r.findChildren(\"pre\")[0].string) if r is not None else 0.0\n return r\n \n def get_instruction_text(self):\n \"\"\"Get corresponding instruction text for environment current step\"\"\"\n html_obj = self._parse_html(self.browser.page_source)\n instruction_text = html_obj.find(id='instruction-text').h4.text\n return instruction_text\n \n def convert_html_to_text(self, html):\n \"\"\"Strip HTML of tags and add separators to convert observation into simple mode\"\"\"\n texts = self._parse_html(html).findAll(text=True)\n visible_texts = filter(tag_visible, texts)\n observation = ' [SEP] '.join(t.strip() for t in visible_texts if t != '\\n')\n return observation\n \n @property\n def state(self):\n \"\"\"\n State that includes all information. The actual observation are\n likely to be a subset or reduced form of the state.\n \"\"\"\n return dict(\n url=self.browser.current_url,\n html=self.browser.page_source,\n instruction_text=self.instruction_text,\n )\n \n @property\n def observation(self):\n \"\"\"Compiles state into either the `html` or `text` observation mode\"\"\"\n html = self.state['html']\n if self.observation_mode == 'html':\n return html\n elif self.observation_mode == 'text':","source_hash":"7b3a43c0250ef2215e2ac1e613ebafbcfbea053a24fcbb773541dc634f124981","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_site_env.state","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_site_env.state#L157-L166","kind":"function","name":"state","path":"webshop/web_agent_site/envs/web_agent_site_env.py","language":"python","start_line":157,"end_line":166,"context_start_line":137,"context_end_line":186,"code":" \"\"\"Get reward value at current step of the environment\"\"\"\n html_obj = self._parse_html()\n r = html_obj.find(id='reward')\n r = float(r.findChildren(\"pre\")[0].string) if r is not None else 0.0\n return r\n \n def get_instruction_text(self):\n \"\"\"Get corresponding instruction text for environment current step\"\"\"\n html_obj = self._parse_html(self.browser.page_source)\n instruction_text = html_obj.find(id='instruction-text').h4.text\n return instruction_text\n \n def convert_html_to_text(self, html):\n \"\"\"Strip HTML of tags and add separators to convert observation into simple mode\"\"\"\n texts = self._parse_html(html).findAll(text=True)\n visible_texts = filter(tag_visible, texts)\n observation = ' [SEP] '.join(t.strip() for t in visible_texts if t != '\\n')\n return observation\n \n @property\n def state(self):\n \"\"\"\n State that includes all information. The actual observation are\n likely to be a subset or reduced form of the state.\n \"\"\"\n return dict(\n url=self.browser.current_url,\n html=self.browser.page_source,\n instruction_text=self.instruction_text,\n )\n \n @property\n def observation(self):\n \"\"\"Compiles state into either the `html` or `text` observation mode\"\"\"\n html = self.state['html']\n if self.observation_mode == 'html':\n return html\n elif self.observation_mode == 'text':\n return self.convert_html_to_text(html)\n else:\n raise ValueError(\n f'Observation mode {self.observation_mode} not supported.'\n )\n\n @property\n def action_space(self):\n # Recommended to use `get_available_actions` instead\n return NotImplementedError\n\n @property","source_hash":"7b3a43c0250ef2215e2ac1e613ebafbcfbea053a24fcbb773541dc634f124981","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_site_env.observation","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_site_env.observation#L169-L179","kind":"function","name":"observation","path":"webshop/web_agent_site/envs/web_agent_site_env.py","language":"python","start_line":169,"end_line":179,"context_start_line":149,"context_end_line":199,"code":" def convert_html_to_text(self, html):\n \"\"\"Strip HTML of tags and add separators to convert observation into simple mode\"\"\"\n texts = self._parse_html(html).findAll(text=True)\n visible_texts = filter(tag_visible, texts)\n observation = ' [SEP] '.join(t.strip() for t in visible_texts if t != '\\n')\n return observation\n \n @property\n def state(self):\n \"\"\"\n State that includes all information. The actual observation are\n likely to be a subset or reduced form of the state.\n \"\"\"\n return dict(\n url=self.browser.current_url,\n html=self.browser.page_source,\n instruction_text=self.instruction_text,\n )\n \n @property\n def observation(self):\n \"\"\"Compiles state into either the `html` or `text` observation mode\"\"\"\n html = self.state['html']\n if self.observation_mode == 'html':\n return html\n elif self.observation_mode == 'text':\n return self.convert_html_to_text(html)\n else:\n raise ValueError(\n f'Observation mode {self.observation_mode} not supported.'\n )\n\n @property\n def action_space(self):\n # Recommended to use `get_available_actions` instead\n return NotImplementedError\n\n @property\n def observation_space(self):\n return NotImplementedError\n\n def reset(self):\n \"\"\"Create a new session and reset environment variables\"\"\"\n if self.assigned_session is not None:\n self.session = self.assigned_session\n else:\n self.session = ''.join(random.choices(string.ascii_lowercase, k=5))\n init_url = f'http://127.0.0.1:3000/{self.session}'\n self.browser.get(init_url)\n\n self.instruction_text = self.get_instruction_text()","source_hash":"7b3a43c0250ef2215e2ac1e613ebafbcfbea053a24fcbb773541dc634f124981","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_site_env.action_space","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_site_env.action_space#L182-L184","kind":"function","name":"action_space","path":"webshop/web_agent_site/envs/web_agent_site_env.py","language":"python","start_line":182,"end_line":184,"context_start_line":162,"context_end_line":204,"code":" return dict(\n url=self.browser.current_url,\n html=self.browser.page_source,\n instruction_text=self.instruction_text,\n )\n \n @property\n def observation(self):\n \"\"\"Compiles state into either the `html` or `text` observation mode\"\"\"\n html = self.state['html']\n if self.observation_mode == 'html':\n return html\n elif self.observation_mode == 'text':\n return self.convert_html_to_text(html)\n else:\n raise ValueError(\n f'Observation mode {self.observation_mode} not supported.'\n )\n\n @property\n def action_space(self):\n # Recommended to use `get_available_actions` instead\n return NotImplementedError\n\n @property\n def observation_space(self):\n return NotImplementedError\n\n def reset(self):\n \"\"\"Create a new session and reset environment variables\"\"\"\n if self.assigned_session is not None:\n self.session = self.assigned_session\n else:\n self.session = ''.join(random.choices(string.ascii_lowercase, k=5))\n init_url = f'http://127.0.0.1:3000/{self.session}'\n self.browser.get(init_url)\n\n self.instruction_text = self.get_instruction_text()\n\n return self.observation, None\n\n def render(self, mode='human'):\n # TODO: Render observation in terminal or WebShop website","source_hash":"7b3a43c0250ef2215e2ac1e613ebafbcfbea053a24fcbb773541dc634f124981","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_site_env.observation_space","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_site_env.observation_space#L187-L188","kind":"function","name":"observation_space","path":"webshop/web_agent_site/envs/web_agent_site_env.py","language":"python","start_line":187,"end_line":188,"context_start_line":167,"context_end_line":208,"code":" \n @property\n def observation(self):\n \"\"\"Compiles state into either the `html` or `text` observation mode\"\"\"\n html = self.state['html']\n if self.observation_mode == 'html':\n return html\n elif self.observation_mode == 'text':\n return self.convert_html_to_text(html)\n else:\n raise ValueError(\n f'Observation mode {self.observation_mode} not supported.'\n )\n\n @property\n def action_space(self):\n # Recommended to use `get_available_actions` instead\n return NotImplementedError\n\n @property\n def observation_space(self):\n return NotImplementedError\n\n def reset(self):\n \"\"\"Create a new session and reset environment variables\"\"\"\n if self.assigned_session is not None:\n self.session = self.assigned_session\n else:\n self.session = ''.join(random.choices(string.ascii_lowercase, k=5))\n init_url = f'http://127.0.0.1:3000/{self.session}'\n self.browser.get(init_url)\n\n self.instruction_text = self.get_instruction_text()\n\n return self.observation, None\n\n def render(self, mode='human'):\n # TODO: Render observation in terminal or WebShop website\n return NotImplementedError\n\n def close(self):\n # TODO: When DB used instead of JSONs, tear down DB here","source_hash":"7b3a43c0250ef2215e2ac1e613ebafbcfbea053a24fcbb773541dc634f124981","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_site_env.reset","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_site_env.reset#L190-L201","kind":"function","name":"reset","path":"webshop/web_agent_site/envs/web_agent_site_env.py","language":"python","start_line":190,"end_line":201,"context_start_line":170,"context_end_line":217,"code":" \"\"\"Compiles state into either the `html` or `text` observation mode\"\"\"\n html = self.state['html']\n if self.observation_mode == 'html':\n return html\n elif self.observation_mode == 'text':\n return self.convert_html_to_text(html)\n else:\n raise ValueError(\n f'Observation mode {self.observation_mode} not supported.'\n )\n\n @property\n def action_space(self):\n # Recommended to use `get_available_actions` instead\n return NotImplementedError\n\n @property\n def observation_space(self):\n return NotImplementedError\n\n def reset(self):\n \"\"\"Create a new session and reset environment variables\"\"\"\n if self.assigned_session is not None:\n self.session = self.assigned_session\n else:\n self.session = ''.join(random.choices(string.ascii_lowercase, k=5))\n init_url = f'http://127.0.0.1:3000/{self.session}'\n self.browser.get(init_url)\n\n self.instruction_text = self.get_instruction_text()\n\n return self.observation, None\n\n def render(self, mode='human'):\n # TODO: Render observation in terminal or WebShop website\n return NotImplementedError\n\n def close(self):\n # TODO: When DB used instead of JSONs, tear down DB here\n self.browser.close()\n print('Browser closed.')\n\ndef tag_visible(element):\n \"\"\"Helper method to strip HTML block of extraneous tags\"\"\"\n ignore = {'style', 'script', 'head', 'title', 'meta', '[document]'}\n return (\n element.parent.name not in ignore and not isinstance(element, Comment)\n )","source_hash":"7b3a43c0250ef2215e2ac1e613ebafbcfbea053a24fcbb773541dc634f124981","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_site_env.render","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_site_env.render#L203-L205","kind":"function","name":"render","path":"webshop/web_agent_site/envs/web_agent_site_env.py","language":"python","start_line":203,"end_line":205,"context_start_line":183,"context_end_line":217,"code":" # Recommended to use `get_available_actions` instead\n return NotImplementedError\n\n @property\n def observation_space(self):\n return NotImplementedError\n\n def reset(self):\n \"\"\"Create a new session and reset environment variables\"\"\"\n if self.assigned_session is not None:\n self.session = self.assigned_session\n else:\n self.session = ''.join(random.choices(string.ascii_lowercase, k=5))\n init_url = f'http://127.0.0.1:3000/{self.session}'\n self.browser.get(init_url)\n\n self.instruction_text = self.get_instruction_text()\n\n return self.observation, None\n\n def render(self, mode='human'):\n # TODO: Render observation in terminal or WebShop website\n return NotImplementedError\n\n def close(self):\n # TODO: When DB used instead of JSONs, tear down DB here\n self.browser.close()\n print('Browser closed.')\n\ndef tag_visible(element):\n \"\"\"Helper method to strip HTML block of extraneous tags\"\"\"\n ignore = {'style', 'script', 'head', 'title', 'meta', '[document]'}\n return (\n element.parent.name not in ignore and not isinstance(element, Comment)\n )","source_hash":"7b3a43c0250ef2215e2ac1e613ebafbcfbea053a24fcbb773541dc634f124981","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_site_env.close","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_site_env.close#L207-L210","kind":"function","name":"close","path":"webshop/web_agent_site/envs/web_agent_site_env.py","language":"python","start_line":207,"end_line":210,"context_start_line":187,"context_end_line":217,"code":" def observation_space(self):\n return NotImplementedError\n\n def reset(self):\n \"\"\"Create a new session and reset environment variables\"\"\"\n if self.assigned_session is not None:\n self.session = self.assigned_session\n else:\n self.session = ''.join(random.choices(string.ascii_lowercase, k=5))\n init_url = f'http://127.0.0.1:3000/{self.session}'\n self.browser.get(init_url)\n\n self.instruction_text = self.get_instruction_text()\n\n return self.observation, None\n\n def render(self, mode='human'):\n # TODO: Render observation in terminal or WebShop website\n return NotImplementedError\n\n def close(self):\n # TODO: When DB used instead of JSONs, tear down DB here\n self.browser.close()\n print('Browser closed.')\n\ndef tag_visible(element):\n \"\"\"Helper method to strip HTML block of extraneous tags\"\"\"\n ignore = {'style', 'script', 'head', 'title', 'meta', '[document]'}\n return (\n element.parent.name not in ignore and not isinstance(element, Comment)\n )","source_hash":"7b3a43c0250ef2215e2ac1e613ebafbcfbea053a24fcbb773541dc634f124981","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_text_env","uri":"program://BOLAA/module/webshop.web_agent_site.envs.web_agent_text_env#L1-L643","kind":"module","name":"webshop.web_agent_site.envs.web_agent_text_env","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":1,"end_line":643,"context_start_line":1,"context_end_line":643,"code":"import gym\nimport json\nimport random\nimport string\nimport time\nimport torch\n\nfrom bs4 import BeautifulSoup\nfrom bs4.element import Comment\nfrom collections import defaultdict\nfrom flask import Flask\nfrom web_agent_site.engine.engine import (\n load_products,\n init_search_engine,\n get_top_n_product_from_keywords,\n map_action_to_html,\n parse_action,\n get_product_per_page,\n ACTION_TO_TEMPLATE,\n END_BUTTON, NEXT_PAGE, PREV_PAGE, BACK_TO_SEARCH,\n)\nfrom web_agent_site.engine.goal import get_reward, get_goals\nfrom web_agent_site.utils import (\n DEFAULT_FILE_PATH,\n FEAT_CONV,\n FEAT_IDS,\n random_idx\n)\n\napp = Flask(__name__)\nclass WebAgentTextEnv(gym.Env):\n \"\"\"Gym environment for Text mode of WebShop environment\"\"\"\n def __init__(\n self,\n observation_mode='html',\n file_path=DEFAULT_FILE_PATH,\n server=None,\n **kwargs\n ):\n \"\"\"\n Constructor for text environment\n\n Arguments:\n observation_mode (`str`) -- ['html' | 'text'] (default 'html')\n get_image\n filter_goals\n limit_goals\n num_products\n human_goals\n session\n session_prefix\n show_attrs\n \"\"\"\n super(WebAgentTextEnv, self).__init__()\n self.observation_mode = observation_mode\n self.kwargs = kwargs\n\n self.file_path = file_path\n\n self.base_url = 'http://127.0.0.1:3000'\n self.server = SimServer(\n self.base_url,\n self.file_path,\n self.kwargs.get('filter_goals'),\n self.kwargs.get('limit_goals', -1),\n self.kwargs.get('num_products'),\n self.kwargs.get('human_goals'),\n self.kwargs.get('show_attrs', False),\n ) if server is None else server\n self.browser = SimBrowser(self.server)\n\n self.session = self.kwargs.get('session')\n self.session_prefix = self.kwargs.get('session_prefix')\n if self.kwargs.get('get_image', 0):\n self.feats = torch.load(FEAT_CONV)\n self.ids = torch.load(FEAT_IDS)\n self.ids = {url: idx for idx, url in enumerate(self.ids)}\n self.prev_obs = []\n self.prev_actions = []\n self.num_prev_obs = self.kwargs.get('num_prev_obs', 0)\n self.num_prev_actions = self.kwargs.get('num_prev_actions', 0)\n self.reset()\n\n def step(self, action):\n \"\"\"\n Takes an action, updates WebShop environment, and returns (observation, reward, done, info)\n\n Arguments:\n action (`str`): An action should be of the following structure:\n - search[keywords]\n - click[value]\n If action not valid, perform nothing.\n \"\"\"\n info = None\n self.get_available_actions()\n\n # Determine action type (click, search) and argument\n action_name, action_arg = parse_action(action)\n if action_arg is not None:\n action_arg = action_arg.lower()\n if (action_name == 'search' and \n action_arg is not None and \n action_arg != ''):\n status = self.browser.search(action_arg)\n elif (action_name == 'click' and \n action_arg in self.text_to_clickable.keys() and \n action_arg != 'search'):\n status = self.browser.click(action_arg, self.text_to_clickable)\n else:\n status = dict(reward=0, done=False)\n\n # Update observation, state with the new action\n ob = self.observation\n text_list = [ob]\n self.prev_actions.append(action)\n for i in range(1, 1 + max(self.num_prev_obs, self.num_prev_actions)):\n if len(self.prev_actions) >= i and self.num_prev_actions >= i:\n text_list.append(self.prev_actions[-i])\n if len(self.prev_obs) >= i and self.num_prev_obs >= i:\n text_list.append(self.prev_obs[-i])\n state = ' [SEP] '.join(text_list[::-1])\n self.prev_obs.append(ob)\n return state, status['reward'], status['done'], info\n\n def get_available_actions(self):\n \"\"\"Returns list of available actions at the current step\"\"\"\n html_obj = self._parse_html()\n\n # Collect search bar, buttons, links, and options as clickables\n search_bar = html_obj.find(id='search_input')\n has_search_bar = True if search_bar is not None else False\n buttons = html_obj.find_all(class_='btn')\n product_links = html_obj.find_all(class_='product-link')\n buying_options = html_obj.select('input[type=\"radio\"]')\n\n self.text_to_clickable = {\n f'{b.get_text()}'.lower(): b\n for b in buttons + product_links\n }\n for opt in buying_options:\n opt_value = opt.get('value')\n self.text_to_clickable[f'{opt_value}'] = opt\n return dict(\n has_search_bar=has_search_bar,\n clickables=list(self.text_to_clickable.keys()),\n )\n \n def get_image(self):\n \"\"\"Scrape image from page HTML and return as a list of pixel values\"\"\"\n html_obj = self._parse_html(self.browser.page_source)\n image_url = html_obj.find(id='product-image')\n if image_url is not None:\n image_url = image_url['src']\n if image_url in self.ids:\n image_idx = self.ids[image_url]\n image = self.feats[image_idx]\n return image\n return torch.zeros(512)\n\n def get_instruction_text(self):\n \"\"\"Get corresponding instruction text for current environment session\"\"\"\n html_obj = self._parse_html(self.browser.page_source)\n instruction_text = html_obj.find(id='instruction-text').h4.text\n return instruction_text\n\n def _parse_html(self, html=None):\n \"\"\"\n Returns web request result wrapped in BeautifulSoup object\n\n Arguments:\n url (`str`): If no url or html is provided, use the current\n observation (HTML) for parsing.\n \"\"\"\n if html is None:\n html = self.state['html']\n html_obj = BeautifulSoup(html, 'html.parser')\n return html_obj\n \n @property\n def observation(self):\n \"\"\"Compiles state into either the `html` or `text` observation mode\"\"\"\n html = self.state['html']\n if self.observation_mode == 'html':\n return html\n elif self.observation_mode == 'text':\n return self.convert_html_to_text(html, simple=True)\n elif self.observation_mode == 'text_rich':\n return self.convert_html_to_text(html, simple=False)\n elif self.observation_mode == 'url':\n return self.state['url']\n else:\n raise ValueError(\n f'Observation mode {self.observation_mode} not supported.'\n )\n \n @property\n def state(self):\n \"\"\"\n State that includes all information. The actual observation are\n likely to be a subset or reduced form of the state.\n \"\"\"\n return dict(\n url=self.browser.current_url,\n html=self.browser.page_source,\n instruction_text=self.instruction_text,\n )\n \n def convert_html_to_text(self, html, simple=False):\n \"\"\"Strip HTML of tags and add separators to convert observation into simple mode\"\"\"\n texts = self._parse_html(html).findAll(text=True)\n visible_texts = filter(tag_visible, texts)\n if simple:\n # For `simple` mode, return just [SEP] separators\n return ' [SEP] '.join(t.strip() for t in visible_texts if t != '\\n')\n else:\n # Otherwise, return an observation with tags mapped to specific, unique separators\n observation = ''\n for t in visible_texts:\n if t == '\\n': continue\n if t.parent.name == 'button': # button\n processed_t = f'[button] {t} [button_]'\n elif t.parent.name == 'label': # options\n if f'\"{t}\"' in self.state['url']:\n processed_t = f' [clicked button] {t} [clicked button_]'\n observation = f'You have clicked {t}.\\n' + observation\n else:\n processed_t = f' [button] {t} [button_]'\n elif t.parent.get('class') == [\"product-link\"]: # product asins\n if f'{t}' in self.server.user_sessions[self.session]['asins']:\n processed_t = f'\\n[clicked button] {t} [clicked button_]'\n else:\n processed_t = f'\\n[button] {t} [button_]'\n else: # regular, unclickable text\n processed_t = str(t)\n observation += processed_t + '\\n'\n return observation\n \n def reset(self, session=None, instruction_text=None):\n \"\"\"Create a new session and reset environment variables\"\"\"\n session_int = None\n if session is not None:\n self.session = str(session)\n if isinstance(session, int):\n session_int = session\n else:\n self.session = ''.join(random.choices(string.ascii_lowercase, k=10))\n if self.session_prefix is not None:\n self.session = self.session_prefix + self.session\n\n init_url = f'{self.base_url}/{self.session}'\n self.browser.get(init_url, session_id=self.session, session_int=session_int)\n\n self.text_to_clickable = None\n self.instruction_text = self.get_instruction_text() if instruction_text is None else instruction_text\n obs = self.observation\n self.prev_obs = [obs]\n self.prev_actions = []\n return obs, None\n\n def render(self, mode='human'):\n pass\n\n def close(self):\n pass\n \n\ndef tag_visible(element):\n ignore = {'style', 'script', 'head', 'title', 'meta', '[document]'}\n return (\n element.parent.name not in ignore and not isinstance(element, Comment)\n )\n\n\nclass SimServer:\n \"\"\"Lightweight simulator of WebShop Flask application for generating HTML observations\"\"\"\n def __init__(\n self,\n base_url,\n file_path,\n filter_goals=None,\n limit_goals=-1,\n num_products=None,\n human_goals=True,\n show_attrs=False,\n ):\n \"\"\"\n Constructor for simulated server serving WebShop application\n \n Arguments:\n filter_goals (`func`) -- Select specific goal(s) for consideration based on criteria of custom function\n limit_goals (`int`) -- Limit to number of goals available\n num_products (`int`) -- Number of products to search across\n human_goals (`bool`) -- If true, load human goals; otherwise, load synthetic goals\n \"\"\"\n # Load all products, goals, and search engine\n self.base_url = base_url\n self.all_products, self.product_item_dict, self.product_prices, _ = \\\n load_products(filepath=file_path, num_products=num_products, human_goals=human_goals)\n self.search_engine = init_search_engine(num_products=num_products)\n self.goals = get_goals(self.all_products, self.product_prices, human_goals)\n self.show_attrs = show_attrs\n\n # Fix outcome for random shuffling of goals\n # random.seed(233)\n # random.shuffle(self.goals)\n\n # Apply `filter_goals` parameter if exists to select speific goal(s)\n if filter_goals is not None:\n self.goals = [\n goal for (i, goal) in enumerate(self.goals)\n if filter_goals(i, goal)\n ]\n \n # Imposes `limit` on goals via random selection\n if limit_goals != -1 and limit_goals < len(self.goals):\n self.weights = [goal['weight'] for goal in self.goals]\n self.cum_weights = [0]\n for w in self.weights:\n self.cum_weights.append(self.cum_weights[-1] + w)\n idxs = []\n while len(idxs) < limit_goals:\n idx = random_idx(self.cum_weights)\n if idx not in idxs:\n idxs.append(idx)\n self.goals = [self.goals[i] for i in idxs]\n print(f'Loaded {len(self.goals)} goals.')\n\n # Set extraneous housekeeping variables\n self.weights = [goal['weight'] for goal in self.goals]\n self.cum_weights = [0]\n for w in self.weights:\n self.cum_weights.append(self.cum_weights[-1] + w)\n self.user_sessions = dict()\n self.search_time = 0\n self.render_time = 0\n self.sample_time = 0\n self.assigned_instruction_text = None # TODO: very hacky, should remove\n \n @app.route('/', methods=['GET', 'POST'])\n def index(self, session_id, **kwargs):\n \"\"\"Redirect to the search page with the given session ID\"\"\"\n html = map_action_to_html(\n 'start',\n session_id=session_id,\n instruction_text=kwargs['instruction_text'],\n )\n url = f'{self.base_url}/{session_id}'\n return html, url\n \n @app.route('/', methods=['GET', 'POST'])\n def search_results(self, session_id, **kwargs):\n \"\"\"Initialize session and return the search results page\"\"\"\n session = self.user_sessions[session_id]\n keywords = kwargs['keywords'] # TODO: why is this using kwargs? why not session?\n assert isinstance(keywords, list)\n page = 1 if 'page' not in kwargs else kwargs['page']\n session[\"page\"] = page\n session[\"keywords\"] = keywords\n session[\"actions\"][\"search\"] += 1\n session[\"asin\"] = None\n session[\"options\"] = {}\n\n # Perform search on keywords from items and record amount of time it takes\n old_time = time.time()\n top_n_products = get_top_n_product_from_keywords(\n keywords,\n self.search_engine,\n self.all_products,\n self.product_item_dict,\n )\n self.search_time += time.time() - old_time\n \n # Get product list from search result asins and get list of corresponding URLs\n products = get_product_per_page(top_n_products, page)\n\n keywords_url_string = '+'.join(keywords)\n url = (\n f'{self.base_url}/search_results/{session_id}/'\n f'{keywords_url_string}/{page}'\n )\n\n # Render HTML search page and record amount of time taken\n old_time = time.time()\n html = map_action_to_html(\n 'search',\n session_id=session_id,\n products=products,\n keywords=session[\"keywords\"],\n page=page,\n total=len(top_n_products),\n instruction_text=session[\"goal\"][\"instruction_text\"],\n )\n self.render_time += time.time() - old_time\n return html, url\n \n @app.route('/', methods=['GET', 'POST'])\n def item_page(self, session_id, **kwargs):\n \"\"\"Render and return the HTML for a product item page\"\"\"\n session = self.user_sessions[session_id]\n clickable_name = kwargs['clickable_name']\n text_to_clickable = kwargs['text_to_clickable']\n clickable = text_to_clickable[clickable_name]\n\n # Update session logs with information of last product asin selected\n if (clickable.get('class') is not None and\n clickable.get('class')[0] == 'product-link'):\n session[\"asin\"] = clickable_name.upper()\n session[\"actions\"][\"asin\"] += 1\n session[\"asins\"].add(session[\"asin\"])\n elif clickable.get('name') is not None:\n clickable_key = clickable['name'].lower()\n session[\"options\"][clickable_key] = clickable_name\n session[\"actions\"][\"options\"] += 1\n\n # Set fields + url of page, then render page's HTML\n product_info = self.product_item_dict[session[\"asin\"]]\n keywords_url_string = '+'.join(session[\"keywords\"])\n option_string = json.dumps(session['options'])\n\n url = (\n f'{self.base_url}/item_page/{session_id}/'\n f'{session[\"asin\"]}/{keywords_url_string}/'\n f'{session[\"page\"]}/{option_string}'\n )\n\n html = map_action_to_html(\n 'click',\n session_id=session_id,\n product_info=product_info,\n keywords=session[\"keywords\"],\n page=session[\"page\"],\n asin=session[\"asin\"],\n options=session[\"options\"],\n instruction_text=session[\"goal\"][\"instruction_text\"],\n show_attrs=self.show_attrs,\n )\n return html, url\n\n @app.route('/', methods=['GET', 'POST'])\n def item_sub_page(self, session_id, **kwargs):\n \"\"\"Render and return the HTML for a product's sub page (i.e. description, features)\"\"\"\n session = self.user_sessions[session_id]\n clickable_name = kwargs['clickable_name']\n for k in ACTION_TO_TEMPLATE:\n if clickable_name.lower() == k.lower():\n clickable_name = k\n break\n \n # Set fields + url of page, then render page's HTML\n product_info = self.product_item_dict[session[\"asin\"]]\n session[\"actions\"][clickable_name] += 1\n keywords_url_string = '+'.join(session[\"keywords\"])\n url = (\n f'{self.base_url}/item_sub_page/{session_id}/'\n f'{session[\"asin\"]}/{keywords_url_string}/{session[\"page\"]}/'\n f'{clickable_name}/{session[\"options\"]}'\n )\n html = map_action_to_html(\n f'click[{clickable_name}]',\n session_id=session_id,\n product_info=product_info,\n keywords=session[\"keywords\"],\n page=session[\"page\"],\n asin=session[\"asin\"],\n options=session[\"options\"],\n instruction_text=session[\"goal\"][\"instruction_text\"],\n )\n return html, url\n\n @app.route('/', methods=['GET', 'POST'])\n def done(self, session_id, **kwargs):\n \"\"\"Render and return HTML for done page\"\"\"\n session = self.user_sessions[session_id]\n goal = self.user_sessions[session_id]['goal']\n purchased_product = self.product_item_dict[session[\"asin\"]]\n session[\"actions\"][\"purchase\"] += 1\n price = self.product_prices.get(session[\"asin\"])\n\n # Calculate reward for selected product and set variables for page details\n reward, info = get_reward(\n purchased_product,\n goal,\n price=price,\n options=session[\"options\"],\n verbose=True\n )\n\n self.user_sessions[session_id]['verbose_info'] = info\n self.user_sessions[session_id]['done'] = True\n self.user_sessions[session_id]['reward'] = reward\n\n url = (\n f'{self.base_url}/done/{session_id}/'\n f'{session[\"asin\"]}/{session[\"options\"]}'\n )\n html = map_action_to_html(\n f'click[{END_BUTTON}]',\n session_id=session_id,\n reward=reward,\n asin=session[\"asin\"],\n options=session[\"options\"],\n instruction_text=session[\"goal\"][\"instruction_text\"],\n )\n return html, url, reward\n \n def receive(self, session_id, current_url, session_int=None, **kwargs):\n \"\"\"Map action to the corresponding page\"\"\"\n status = dict(reward=0.0, done=False)\n\n with app.app_context(), app.test_request_context():\n # Create/determine goal, instruction_text from current session\n if session_id not in self.user_sessions:\n idx = session_int if (session_int is not None and isinstance(session_int, int)) else random_idx(self.cum_weights) \n goal = self.goals[idx]\n instruction_text = goal['instruction_text']\n self.user_sessions[session_id] = {'goal': goal, 'done': False}\n else:\n instruction_text = \\\n self.user_sessions[session_id]['goal']['instruction_\n# ... truncated ...","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":true} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_text_env.WebAgentTextEnv","uri":"program://BOLAA/class/webshop.web_agent_site.envs.web_agent_text_env.WebAgentTextEnv#L31-L264","kind":"class","name":"WebAgentTextEnv","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":31,"end_line":264,"context_start_line":11,"context_end_line":284,"code":"from flask import Flask\nfrom web_agent_site.engine.engine import (\n load_products,\n init_search_engine,\n get_top_n_product_from_keywords,\n map_action_to_html,\n parse_action,\n get_product_per_page,\n ACTION_TO_TEMPLATE,\n END_BUTTON, NEXT_PAGE, PREV_PAGE, BACK_TO_SEARCH,\n)\nfrom web_agent_site.engine.goal import get_reward, get_goals\nfrom web_agent_site.utils import (\n DEFAULT_FILE_PATH,\n FEAT_CONV,\n FEAT_IDS,\n random_idx\n)\n\napp = Flask(__name__)\nclass WebAgentTextEnv(gym.Env):\n \"\"\"Gym environment for Text mode of WebShop environment\"\"\"\n def __init__(\n self,\n observation_mode='html',\n file_path=DEFAULT_FILE_PATH,\n server=None,\n **kwargs\n ):\n \"\"\"\n Constructor for text environment\n\n Arguments:\n observation_mode (`str`) -- ['html' | 'text'] (default 'html')\n get_image\n filter_goals\n limit_goals\n num_products\n human_goals\n session\n session_prefix\n show_attrs\n \"\"\"\n super(WebAgentTextEnv, self).__init__()\n self.observation_mode = observation_mode\n self.kwargs = kwargs\n\n self.file_path = file_path\n\n self.base_url = 'http://127.0.0.1:3000'\n self.server = SimServer(\n self.base_url,\n self.file_path,\n self.kwargs.get('filter_goals'),\n self.kwargs.get('limit_goals', -1),\n self.kwargs.get('num_products'),\n self.kwargs.get('human_goals'),\n self.kwargs.get('show_attrs', False),\n ) if server is None else server\n self.browser = SimBrowser(self.server)\n\n self.session = self.kwargs.get('session')\n self.session_prefix = self.kwargs.get('session_prefix')\n if self.kwargs.get('get_image', 0):\n self.feats = torch.load(FEAT_CONV)\n self.ids = torch.load(FEAT_IDS)\n self.ids = {url: idx for idx, url in enumerate(self.ids)}\n self.prev_obs = []\n self.prev_actions = []\n self.num_prev_obs = self.kwargs.get('num_prev_obs', 0)\n self.num_prev_actions = self.kwargs.get('num_prev_actions', 0)\n self.reset()\n\n def step(self, action):\n \"\"\"\n Takes an action, updates WebShop environment, and returns (observation, reward, done, info)\n\n Arguments:\n action (`str`): An action should be of the following structure:\n - search[keywords]\n - click[value]\n If action not valid, perform nothing.\n \"\"\"\n info = None\n self.get_available_actions()\n\n # Determine action type (click, search) and argument\n action_name, action_arg = parse_action(action)\n if action_arg is not None:\n action_arg = action_arg.lower()\n if (action_name == 'search' and \n action_arg is not None and \n action_arg != ''):\n status = self.browser.search(action_arg)\n elif (action_name == 'click' and \n action_arg in self.text_to_clickable.keys() and \n action_arg != 'search'):\n status = self.browser.click(action_arg, self.text_to_clickable)\n else:\n status = dict(reward=0, done=False)\n\n # Update observation, state with the new action\n ob = self.observation\n text_list = [ob]\n self.prev_actions.append(action)\n for i in range(1, 1 + max(self.num_prev_obs, self.num_prev_actions)):\n if len(self.prev_actions) >= i and self.num_prev_actions >= i:\n text_list.append(self.prev_actions[-i])\n if len(self.prev_obs) >= i and self.num_prev_obs >= i:\n text_list.append(self.prev_obs[-i])\n state = ' [SEP] '.join(text_list[::-1])\n self.prev_obs.append(ob)\n return state, status['reward'], status['done'], info\n\n def get_available_actions(self):\n \"\"\"Returns list of available actions at the current step\"\"\"\n html_obj = self._parse_html()\n\n # Collect search bar, buttons, links, and options as clickables\n search_bar = html_obj.find(id='search_input')\n has_search_bar = True if search_bar is not None else False\n buttons = html_obj.find_all(class_='btn')\n product_links = html_obj.find_all(class_='product-link')\n buying_options = html_obj.select('input[type=\"radio\"]')\n\n self.text_to_clickable = {\n f'{b.get_text()}'.lower(): b\n for b in buttons + product_links\n }\n for opt in buying_options:\n opt_value = opt.get('value')\n self.text_to_clickable[f'{opt_value}'] = opt\n return dict(\n has_search_bar=has_search_bar,\n clickables=list(self.text_to_clickable.keys()),\n )\n \n def get_image(self):\n \"\"\"Scrape image from page HTML and return as a list of pixel values\"\"\"\n html_obj = self._parse_html(self.browser.page_source)\n image_url = html_obj.find(id='product-image')\n if image_url is not None:\n image_url = image_url['src']\n if image_url in self.ids:\n image_idx = self.ids[image_url]\n image = self.feats[image_idx]\n return image\n return torch.zeros(512)\n\n def get_instruction_text(self):\n \"\"\"Get corresponding instruction text for current environment session\"\"\"\n html_obj = self._parse_html(self.browser.page_source)\n instruction_text = html_obj.find(id='instruction-text').h4.text\n return instruction_text\n\n def _parse_html(self, html=None):\n \"\"\"\n Returns web request result wrapped in BeautifulSoup object\n\n Arguments:\n url (`str`): If no url or html is provided, use the current\n observation (HTML) for parsing.\n \"\"\"\n if html is None:\n html = self.state['html']\n html_obj = BeautifulSoup(html, 'html.parser')\n return html_obj\n \n @property\n def observation(self):\n \"\"\"Compiles state into either the `html` or `text` observation mode\"\"\"\n html = self.state['html']\n if self.observation_mode == 'html':\n return html\n elif self.observation_mode == 'text':\n return self.convert_html_to_text(html, simple=True)\n elif self.observation_mode == 'text_rich':\n return self.convert_html_to_text(html, simple=False)\n elif self.observation_mode == 'url':\n return self.state['url']\n else:\n raise ValueError(\n f'Observation mode {self.observation_mode} not supported.'\n )\n \n @property\n def state(self):\n \"\"\"\n State that includes all information. The actual observation are\n likely to be a subset or reduced form of the state.\n \"\"\"\n return dict(\n url=self.browser.current_url,\n html=self.browser.page_source,\n instruction_text=self.instruction_text,\n )\n \n def convert_html_to_text(self, html, simple=False):\n \"\"\"Strip HTML of tags and add separators to convert observation into simple mode\"\"\"\n texts = self._parse_html(html).findAll(text=True)\n visible_texts = filter(tag_visible, texts)\n if simple:\n # For `simple` mode, return just [SEP] separators\n return ' [SEP] '.join(t.strip() for t in visible_texts if t != '\\n')\n else:\n # Otherwise, return an observation with tags mapped to specific, unique separators\n observation = ''\n for t in visible_texts:\n if t == '\\n': continue\n if t.parent.name == 'button': # button\n processed_t = f'[button] {t} [button_]'\n elif t.parent.name == 'label': # options\n if f'\"{t}\"' in self.state['url']:\n processed_t = f' [clicked button] {t} [clicked button_]'\n observation = f'You have clicked {t}.\\n' + observation\n else:\n processed_t = f' [button] {t} [button_]'\n elif t.parent.get('class') == [\"product-link\"]: # product asins\n if f'{t}' in self.server.user_sessions[self.session]['asins']:\n processed_t = f'\\n[clicked button] {t} [clicked button_]'\n else:\n processed_t = f'\\n[button] {t} [button_]'\n else: # regular, unclickable text\n processed_t = str(t)\n observation += processed_t + '\\n'\n return observation\n \n def reset(self, session=None, instruction_text=None):\n \"\"\"Create a new session and reset environment variables\"\"\"\n session_int = None\n if session is not None:\n self.session = str(session)\n if isinstance(session, int):\n session_int = session\n else:\n self.session = ''.join(random.choices(string.ascii_lowercase, k=10))\n if self.session_prefix is not None:\n self.session = self.session_prefix + self.session\n\n init_url = f'{self.base_url}/{self.session}'\n self.browser.get(init_url, session_id=self.session, session_int=session_int)\n\n self.text_to_clickable = None\n self.instruction_text = self.get_instruction_text() if instruction_text is None else instruction_text\n obs = self.observation\n self.prev_obs = [obs]\n self.prev_actions = []\n return obs, None\n\n def render(self, mode='human'):\n pass\n\n def close(self):\n pass\n \n\ndef tag_visible(element):\n ignore = {'style', 'script', 'head', 'title', 'meta', '[document]'}\n return (\n element.parent.name not in ignore and not isinstance(element, Comment)\n )\n\n\nclass SimServer:\n \"\"\"Lightweight simulator of WebShop Flask application for generating HTML observations\"\"\"\n def __init__(\n self,\n base_url,\n file_path,\n filter_goals=None,\n limit_goals=-1,\n num_products=None,\n human_goals=True,\n show_attrs=False,","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_text_env.tag_visible","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_text_env.tag_visible#L267-L271","kind":"function","name":"tag_visible","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":267,"end_line":271,"context_start_line":247,"context_end_line":291,"code":" if self.session_prefix is not None:\n self.session = self.session_prefix + self.session\n\n init_url = f'{self.base_url}/{self.session}'\n self.browser.get(init_url, session_id=self.session, session_int=session_int)\n\n self.text_to_clickable = None\n self.instruction_text = self.get_instruction_text() if instruction_text is None else instruction_text\n obs = self.observation\n self.prev_obs = [obs]\n self.prev_actions = []\n return obs, None\n\n def render(self, mode='human'):\n pass\n\n def close(self):\n pass\n \n\ndef tag_visible(element):\n ignore = {'style', 'script', 'head', 'title', 'meta', '[document]'}\n return (\n element.parent.name not in ignore and not isinstance(element, Comment)\n )\n\n\nclass SimServer:\n \"\"\"Lightweight simulator of WebShop Flask application for generating HTML observations\"\"\"\n def __init__(\n self,\n base_url,\n file_path,\n filter_goals=None,\n limit_goals=-1,\n num_products=None,\n human_goals=True,\n show_attrs=False,\n ):\n \"\"\"\n Constructor for simulated server serving WebShop application\n \n Arguments:\n filter_goals (`func`) -- Select specific goal(s) for consideration based on criteria of custom function\n limit_goals (`int`) -- Limit to number of goals available","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_text_env.SimServer","uri":"program://BOLAA/class/webshop.web_agent_site.envs.web_agent_text_env.SimServer#L274-L604","kind":"class","name":"SimServer","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":274,"end_line":604,"context_start_line":254,"context_end_line":624,"code":" self.instruction_text = self.get_instruction_text() if instruction_text is None else instruction_text\n obs = self.observation\n self.prev_obs = [obs]\n self.prev_actions = []\n return obs, None\n\n def render(self, mode='human'):\n pass\n\n def close(self):\n pass\n \n\ndef tag_visible(element):\n ignore = {'style', 'script', 'head', 'title', 'meta', '[document]'}\n return (\n element.parent.name not in ignore and not isinstance(element, Comment)\n )\n\n\nclass SimServer:\n \"\"\"Lightweight simulator of WebShop Flask application for generating HTML observations\"\"\"\n def __init__(\n self,\n base_url,\n file_path,\n filter_goals=None,\n limit_goals=-1,\n num_products=None,\n human_goals=True,\n show_attrs=False,\n ):\n \"\"\"\n Constructor for simulated server serving WebShop application\n \n Arguments:\n filter_goals (`func`) -- Select specific goal(s) for consideration based on criteria of custom function\n limit_goals (`int`) -- Limit to number of goals available\n num_products (`int`) -- Number of products to search across\n human_goals (`bool`) -- If true, load human goals; otherwise, load synthetic goals\n \"\"\"\n # Load all products, goals, and search engine\n self.base_url = base_url\n self.all_products, self.product_item_dict, self.product_prices, _ = \\\n load_products(filepath=file_path, num_products=num_products, human_goals=human_goals)\n self.search_engine = init_search_engine(num_products=num_products)\n self.goals = get_goals(self.all_products, self.product_prices, human_goals)\n self.show_attrs = show_attrs\n\n # Fix outcome for random shuffling of goals\n # random.seed(233)\n # random.shuffle(self.goals)\n\n # Apply `filter_goals` parameter if exists to select speific goal(s)\n if filter_goals is not None:\n self.goals = [\n goal for (i, goal) in enumerate(self.goals)\n if filter_goals(i, goal)\n ]\n \n # Imposes `limit` on goals via random selection\n if limit_goals != -1 and limit_goals < len(self.goals):\n self.weights = [goal['weight'] for goal in self.goals]\n self.cum_weights = [0]\n for w in self.weights:\n self.cum_weights.append(self.cum_weights[-1] + w)\n idxs = []\n while len(idxs) < limit_goals:\n idx = random_idx(self.cum_weights)\n if idx not in idxs:\n idxs.append(idx)\n self.goals = [self.goals[i] for i in idxs]\n print(f'Loaded {len(self.goals)} goals.')\n\n # Set extraneous housekeeping variables\n self.weights = [goal['weight'] for goal in self.goals]\n self.cum_weights = [0]\n for w in self.weights:\n self.cum_weights.append(self.cum_weights[-1] + w)\n self.user_sessions = dict()\n self.search_time = 0\n self.render_time = 0\n self.sample_time = 0\n self.assigned_instruction_text = None # TODO: very hacky, should remove\n \n @app.route('/', methods=['GET', 'POST'])\n def index(self, session_id, **kwargs):\n \"\"\"Redirect to the search page with the given session ID\"\"\"\n html = map_action_to_html(\n 'start',\n session_id=session_id,\n instruction_text=kwargs['instruction_text'],\n )\n url = f'{self.base_url}/{session_id}'\n return html, url\n \n @app.route('/', methods=['GET', 'POST'])\n def search_results(self, session_id, **kwargs):\n \"\"\"Initialize session and return the search results page\"\"\"\n session = self.user_sessions[session_id]\n keywords = kwargs['keywords'] # TODO: why is this using kwargs? why not session?\n assert isinstance(keywords, list)\n page = 1 if 'page' not in kwargs else kwargs['page']\n session[\"page\"] = page\n session[\"keywords\"] = keywords\n session[\"actions\"][\"search\"] += 1\n session[\"asin\"] = None\n session[\"options\"] = {}\n\n # Perform search on keywords from items and record amount of time it takes\n old_time = time.time()\n top_n_products = get_top_n_product_from_keywords(\n keywords,\n self.search_engine,\n self.all_products,\n self.product_item_dict,\n )\n self.search_time += time.time() - old_time\n \n # Get product list from search result asins and get list of corresponding URLs\n products = get_product_per_page(top_n_products, page)\n\n keywords_url_string = '+'.join(keywords)\n url = (\n f'{self.base_url}/search_results/{session_id}/'\n f'{keywords_url_string}/{page}'\n )\n\n # Render HTML search page and record amount of time taken\n old_time = time.time()\n html = map_action_to_html(\n 'search',\n session_id=session_id,\n products=products,\n keywords=session[\"keywords\"],\n page=page,\n total=len(top_n_products),\n instruction_text=session[\"goal\"][\"instruction_text\"],\n )\n self.render_time += time.time() - old_time\n return html, url\n \n @app.route('/', methods=['GET', 'POST'])\n def item_page(self, session_id, **kwargs):\n \"\"\"Render and return the HTML for a product item page\"\"\"\n session = self.user_sessions[session_id]\n clickable_name = kwargs['clickable_name']\n text_to_clickable = kwargs['text_to_clickable']\n clickable = text_to_clickable[clickable_name]\n\n # Update session logs with information of last product asin selected\n if (clickable.get('class') is not None and\n clickable.get('class')[0] == 'product-link'):\n session[\"asin\"] = clickable_name.upper()\n session[\"actions\"][\"asin\"] += 1\n session[\"asins\"].add(session[\"asin\"])\n elif clickable.get('name') is not None:\n clickable_key = clickable['name'].lower()\n session[\"options\"][clickable_key] = clickable_name\n session[\"actions\"][\"options\"] += 1\n\n # Set fields + url of page, then render page's HTML\n product_info = self.product_item_dict[session[\"asin\"]]\n keywords_url_string = '+'.join(session[\"keywords\"])\n option_string = json.dumps(session['options'])\n\n url = (\n f'{self.base_url}/item_page/{session_id}/'\n f'{session[\"asin\"]}/{keywords_url_string}/'\n f'{session[\"page\"]}/{option_string}'\n )\n\n html = map_action_to_html(\n 'click',\n session_id=session_id,\n product_info=product_info,\n keywords=session[\"keywords\"],\n page=session[\"page\"],\n asin=session[\"asin\"],\n options=session[\"options\"],\n instruction_text=session[\"goal\"][\"instruction_text\"],\n show_attrs=self.show_attrs,\n )\n return html, url\n\n @app.route('/', methods=['GET', 'POST'])\n def item_sub_page(self, session_id, **kwargs):\n \"\"\"Render and return the HTML for a product's sub page (i.e. description, features)\"\"\"\n session = self.user_sessions[session_id]\n clickable_name = kwargs['clickable_name']\n for k in ACTION_TO_TEMPLATE:\n if clickable_name.lower() == k.lower():\n clickable_name = k\n break\n \n # Set fields + url of page, then render page's HTML\n product_info = self.product_item_dict[session[\"asin\"]]\n session[\"actions\"][clickable_name] += 1\n keywords_url_string = '+'.join(session[\"keywords\"])\n url = (\n f'{self.base_url}/item_sub_page/{session_id}/'\n f'{session[\"asin\"]}/{keywords_url_string}/{session[\"page\"]}/'\n f'{clickable_name}/{session[\"options\"]}'\n )\n html = map_action_to_html(\n f'click[{clickable_name}]',\n session_id=session_id,\n product_info=product_info,\n keywords=session[\"keywords\"],\n page=session[\"page\"],\n asin=session[\"asin\"],\n options=session[\"options\"],\n instruction_text=session[\"goal\"][\"instruction_text\"],\n )\n return html, url\n\n @app.route('/', methods=['GET', 'POST'])\n def done(self, session_id, **kwargs):\n \"\"\"Render and return HTML for done page\"\"\"\n session = self.user_sessions[session_id]\n goal = self.user_sessions[session_id]['goal']\n purchased_product = self.product_item_dict[session[\"asin\"]]\n session[\"actions\"][\"purchase\"] += 1\n price = self.product_prices.get(session[\"asin\"])\n\n # Calculate reward for selected product and set variables for page details\n reward, info = get_reward(\n purchased_product,\n goal,\n price=price,\n options=session[\"options\"],\n verbose=True\n )\n\n self.user_sessions[session_id]['verbose_info'] = info\n self.user_sessions[session_id]['done'] = True\n self.user_sessions[session_id]['reward'] = reward\n\n url = (\n f'{self.base_url}/done/{session_id}/'\n f'{session[\"asin\"]}/{session[\"options\"]}'\n )\n html = map_action_to_html(\n f'click[{END_BUTTON}]',\n session_id=session_id,\n reward=reward,\n asin=session[\"asin\"],\n options=session[\"options\"],\n instruction_text=session[\"goal\"][\"instruction_text\"],\n )\n return html, url, reward\n \n def receive(self, session_id, current_url, session_int=None, **kwargs):\n \"\"\"Map action to the corresponding page\"\"\"\n status = dict(reward=0.0, done=False)\n\n with app.app_context(), app.test_request_context():\n # Create/determine goal, instruction_text from current session\n if session_id not in self.user_sessions:\n idx = session_int if (session_int is not None and isinstance(session_int, int)) else random_idx(self.cum_weights) \n goal = self.goals[idx]\n instruction_text = goal['instruction_text']\n self.user_sessions[session_id] = {'goal': goal, 'done': False}\n else:\n instruction_text = \\\n self.user_sessions[session_id]['goal']['instruction_text']\n if self.assigned_instruction_text is not None:\n instruction_text = self.assigned_instruction_text # TODO: very hacky, should remove\n self.user_sessions[session_id]['goal']['instruction_text'] = instruction_text\n session = self.user_sessions[session_id]\n\n if not kwargs:\n # If no action, reset the session variables\n kwargs['instruction_text'] = instruction_text\n html, url = self.index(session_id, **kwargs)\n self.user_sessions[session_id].update(\n {\n 'keywords': None,\n 'page': None,\n 'asin': None,\n 'asins': set(),\n 'options': dict(),\n 'actions': defaultdict(int)\n }\n )\n elif 'keywords' in kwargs:\n # If search keywords are available, run a search\n html, url = self.search_results(session_id, **kwargs)\n elif 'clickable_name' in kwargs:\n clickable_name = kwargs['clickable_name'].lower()\n if clickable_name == END_BUTTON.lower():\n # If \"buy now\" clicked, calculate reward and flag session as terminated\n html, url, reward = self.done(session_id, **kwargs)\n status['reward'] = reward\n status['done'] = True\n elif clickable_name == BACK_TO_SEARCH.lower():\n # If \"back to search\" clicked, recursively reset the session back to search page\n html, url, status = self.receive(session_id, current_url)\n elif (clickable_name == NEXT_PAGE.lower() and \n self.get_page_name(current_url) == 'search_results'):\n # If \"next page\" clicked from search results, re-render with `page` enumerated\n html, url, status = self.receive(\n session_id,\n current_url,\n keywords=session[\"keywords\"],\n page=session[\"page\"] + 1,\n )\n elif (clickable_name == PREV_PAGE.lower() and \n self.get_page_name(current_url) == 'search_results'):\n # If \"prev page\" clicked from search results, re-render with `page` denumerated\n html, url, status = self.receive(\n session_id,\n current_url,\n keywords=session[\"keywords\"],\n page=session[\"page\"] - 1,\n )\n elif (clickable_name == PREV_PAGE.lower() and \n self.get_page_name(current_url) == 'item_sub_page'):\n # If \"prev page\" clicked from sub page, return to corresponding item page\n html, url = self.item_page(session_id, **kwargs)\n elif (clickable_name == PREV_PAGE.lower() and \n self.get_page_name(current_url) == 'item_page'):\n # If \"prev page\" clicked from item page, return to search results page\n html, url = self.search_results(\n session_id,\n keywords=session[\"keywords\"],\n page=session[\"page\"],\n **kwargs\n )\n elif clickable_name in [k.lower() for k in ACTION_TO_TEMPLATE]:\n # Render item_sub_page if clickable is description, features, or reviews\n html, url = self.item_sub_page(session_id, **kwargs)\n else:\n # Otherwise, render current item page\n html, url = self.item_page(session_id, **kwargs)\n return html, url, status\n \n def get_page_name(self, url):\n \"\"\"Determine which page (i.e. item_page, search_results) the given URL is pointing at\"\"\"\n if url is None:\n return None\n page_names = [\n 'search_results',\n 'item_page',\n 'item_sub_page',\n 'done'\n ]\n for page_name in page_names:\n if page_name in url:\n return page_name\n return '' # index page\n\n\nclass SimBrowser:\n \"\"\"Simulated browser for rendering the HTML source of WebShop environment pages\"\"\"\n def __init__(self, server):\n self.server = server\n self.current_url = None\n self.page_source = None\n self.session_id = None\n\n def get(self, url, session_id=None, session_int=None):\n \"\"\"Set browser variables to corresponding link, page HTML for URL\"\"\"\n self.session_id = url.split('/')[-1] if session_id is None else session_id\n self.page_source, _, _ = \\\n self.server.receive(self.session_id, self.current_url, session_int=session_int)\n self.current_url = url\n \n def click(self, clickable_name, text_to_clickable):\n \"\"\"Wrapper for `receive` handler for performing click action on current page\"\"\"\n self.page_source, self.current_url, status = \\","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_text_env.SimBrowser","uri":"program://BOLAA/class/webshop.web_agent_site.envs.web_agent_text_env.SimBrowser#L607-L643","kind":"class","name":"SimBrowser","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":607,"end_line":643,"context_start_line":587,"context_end_line":643,"code":" # Otherwise, render current item page\n html, url = self.item_page(session_id, **kwargs)\n return html, url, status\n \n def get_page_name(self, url):\n \"\"\"Determine which page (i.e. item_page, search_results) the given URL is pointing at\"\"\"\n if url is None:\n return None\n page_names = [\n 'search_results',\n 'item_page',\n 'item_sub_page',\n 'done'\n ]\n for page_name in page_names:\n if page_name in url:\n return page_name\n return '' # index page\n\n\nclass SimBrowser:\n \"\"\"Simulated browser for rendering the HTML source of WebShop environment pages\"\"\"\n def __init__(self, server):\n self.server = server\n self.current_url = None\n self.page_source = None\n self.session_id = None\n\n def get(self, url, session_id=None, session_int=None):\n \"\"\"Set browser variables to corresponding link, page HTML for URL\"\"\"\n self.session_id = url.split('/')[-1] if session_id is None else session_id\n self.page_source, _, _ = \\\n self.server.receive(self.session_id, self.current_url, session_int=session_int)\n self.current_url = url\n \n def click(self, clickable_name, text_to_clickable):\n \"\"\"Wrapper for `receive` handler for performing click action on current page\"\"\"\n self.page_source, self.current_url, status = \\\n self.server.receive(\n self.session_id,\n current_url=self.current_url,\n clickable_name=clickable_name,\n text_to_clickable=text_to_clickable,\n )\n return status\n \n def search(self, keywords):\n \"\"\"Wrapper for `receive` handler for performing search action on current page\"\"\"\n if isinstance(keywords, str):\n keywords = keywords.split(' ')\n self.page_source, self.current_url, status = \\\n self.server.receive(\n self.session_id,\n current_url=self.current_url,\n keywords=keywords,\n )\n return status","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_text_env.__init__","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_text_env.__init__#L609-L613","kind":"function","name":"__init__","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":609,"end_line":613,"context_start_line":589,"context_end_line":633,"code":" return html, url, status\n \n def get_page_name(self, url):\n \"\"\"Determine which page (i.e. item_page, search_results) the given URL is pointing at\"\"\"\n if url is None:\n return None\n page_names = [\n 'search_results',\n 'item_page',\n 'item_sub_page',\n 'done'\n ]\n for page_name in page_names:\n if page_name in url:\n return page_name\n return '' # index page\n\n\nclass SimBrowser:\n \"\"\"Simulated browser for rendering the HTML source of WebShop environment pages\"\"\"\n def __init__(self, server):\n self.server = server\n self.current_url = None\n self.page_source = None\n self.session_id = None\n\n def get(self, url, session_id=None, session_int=None):\n \"\"\"Set browser variables to corresponding link, page HTML for URL\"\"\"\n self.session_id = url.split('/')[-1] if session_id is None else session_id\n self.page_source, _, _ = \\\n self.server.receive(self.session_id, self.current_url, session_int=session_int)\n self.current_url = url\n \n def click(self, clickable_name, text_to_clickable):\n \"\"\"Wrapper for `receive` handler for performing click action on current page\"\"\"\n self.page_source, self.current_url, status = \\\n self.server.receive(\n self.session_id,\n current_url=self.current_url,\n clickable_name=clickable_name,\n text_to_clickable=text_to_clickable,\n )\n return status\n \n def search(self, keywords):","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_text_env.step","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_text_env.step#L84-L123","kind":"function","name":"step","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":84,"end_line":123,"context_start_line":64,"context_end_line":143,"code":" self.kwargs.get('filter_goals'),\n self.kwargs.get('limit_goals', -1),\n self.kwargs.get('num_products'),\n self.kwargs.get('human_goals'),\n self.kwargs.get('show_attrs', False),\n ) if server is None else server\n self.browser = SimBrowser(self.server)\n\n self.session = self.kwargs.get('session')\n self.session_prefix = self.kwargs.get('session_prefix')\n if self.kwargs.get('get_image', 0):\n self.feats = torch.load(FEAT_CONV)\n self.ids = torch.load(FEAT_IDS)\n self.ids = {url: idx for idx, url in enumerate(self.ids)}\n self.prev_obs = []\n self.prev_actions = []\n self.num_prev_obs = self.kwargs.get('num_prev_obs', 0)\n self.num_prev_actions = self.kwargs.get('num_prev_actions', 0)\n self.reset()\n\n def step(self, action):\n \"\"\"\n Takes an action, updates WebShop environment, and returns (observation, reward, done, info)\n\n Arguments:\n action (`str`): An action should be of the following structure:\n - search[keywords]\n - click[value]\n If action not valid, perform nothing.\n \"\"\"\n info = None\n self.get_available_actions()\n\n # Determine action type (click, search) and argument\n action_name, action_arg = parse_action(action)\n if action_arg is not None:\n action_arg = action_arg.lower()\n if (action_name == 'search' and \n action_arg is not None and \n action_arg != ''):\n status = self.browser.search(action_arg)\n elif (action_name == 'click' and \n action_arg in self.text_to_clickable.keys() and \n action_arg != 'search'):\n status = self.browser.click(action_arg, self.text_to_clickable)\n else:\n status = dict(reward=0, done=False)\n\n # Update observation, state with the new action\n ob = self.observation\n text_list = [ob]\n self.prev_actions.append(action)\n for i in range(1, 1 + max(self.num_prev_obs, self.num_prev_actions)):\n if len(self.prev_actions) >= i and self.num_prev_actions >= i:\n text_list.append(self.prev_actions[-i])\n if len(self.prev_obs) >= i and self.num_prev_obs >= i:\n text_list.append(self.prev_obs[-i])\n state = ' [SEP] '.join(text_list[::-1])\n self.prev_obs.append(ob)\n return state, status['reward'], status['done'], info\n\n def get_available_actions(self):\n \"\"\"Returns list of available actions at the current step\"\"\"\n html_obj = self._parse_html()\n\n # Collect search bar, buttons, links, and options as clickables\n search_bar = html_obj.find(id='search_input')\n has_search_bar = True if search_bar is not None else False\n buttons = html_obj.find_all(class_='btn')\n product_links = html_obj.find_all(class_='product-link')\n buying_options = html_obj.select('input[type=\"radio\"]')\n\n self.text_to_clickable = {\n f'{b.get_text()}'.lower(): b\n for b in buttons + product_links\n }\n for opt in buying_options:\n opt_value = opt.get('value')\n self.text_to_clickable[f'{opt_value}'] = opt\n return dict(","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_text_env.get_available_actions","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_text_env.get_available_actions#L125-L146","kind":"function","name":"get_available_actions","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":125,"end_line":146,"context_start_line":105,"context_end_line":166,"code":" elif (action_name == 'click' and \n action_arg in self.text_to_clickable.keys() and \n action_arg != 'search'):\n status = self.browser.click(action_arg, self.text_to_clickable)\n else:\n status = dict(reward=0, done=False)\n\n # Update observation, state with the new action\n ob = self.observation\n text_list = [ob]\n self.prev_actions.append(action)\n for i in range(1, 1 + max(self.num_prev_obs, self.num_prev_actions)):\n if len(self.prev_actions) >= i and self.num_prev_actions >= i:\n text_list.append(self.prev_actions[-i])\n if len(self.prev_obs) >= i and self.num_prev_obs >= i:\n text_list.append(self.prev_obs[-i])\n state = ' [SEP] '.join(text_list[::-1])\n self.prev_obs.append(ob)\n return state, status['reward'], status['done'], info\n\n def get_available_actions(self):\n \"\"\"Returns list of available actions at the current step\"\"\"\n html_obj = self._parse_html()\n\n # Collect search bar, buttons, links, and options as clickables\n search_bar = html_obj.find(id='search_input')\n has_search_bar = True if search_bar is not None else False\n buttons = html_obj.find_all(class_='btn')\n product_links = html_obj.find_all(class_='product-link')\n buying_options = html_obj.select('input[type=\"radio\"]')\n\n self.text_to_clickable = {\n f'{b.get_text()}'.lower(): b\n for b in buttons + product_links\n }\n for opt in buying_options:\n opt_value = opt.get('value')\n self.text_to_clickable[f'{opt_value}'] = opt\n return dict(\n has_search_bar=has_search_bar,\n clickables=list(self.text_to_clickable.keys()),\n )\n \n def get_image(self):\n \"\"\"Scrape image from page HTML and return as a list of pixel values\"\"\"\n html_obj = self._parse_html(self.browser.page_source)\n image_url = html_obj.find(id='product-image')\n if image_url is not None:\n image_url = image_url['src']\n if image_url in self.ids:\n image_idx = self.ids[image_url]\n image = self.feats[image_idx]\n return image\n return torch.zeros(512)\n\n def get_instruction_text(self):\n \"\"\"Get corresponding instruction text for current environment session\"\"\"\n html_obj = self._parse_html(self.browser.page_source)\n instruction_text = html_obj.find(id='instruction-text').h4.text\n return instruction_text\n\n def _parse_html(self, html=None):","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_text_env.get_image","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_text_env.get_image#L148-L158","kind":"function","name":"get_image","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":148,"end_line":158,"context_start_line":128,"context_end_line":178,"code":"\n # Collect search bar, buttons, links, and options as clickables\n search_bar = html_obj.find(id='search_input')\n has_search_bar = True if search_bar is not None else False\n buttons = html_obj.find_all(class_='btn')\n product_links = html_obj.find_all(class_='product-link')\n buying_options = html_obj.select('input[type=\"radio\"]')\n\n self.text_to_clickable = {\n f'{b.get_text()}'.lower(): b\n for b in buttons + product_links\n }\n for opt in buying_options:\n opt_value = opt.get('value')\n self.text_to_clickable[f'{opt_value}'] = opt\n return dict(\n has_search_bar=has_search_bar,\n clickables=list(self.text_to_clickable.keys()),\n )\n \n def get_image(self):\n \"\"\"Scrape image from page HTML and return as a list of pixel values\"\"\"\n html_obj = self._parse_html(self.browser.page_source)\n image_url = html_obj.find(id='product-image')\n if image_url is not None:\n image_url = image_url['src']\n if image_url in self.ids:\n image_idx = self.ids[image_url]\n image = self.feats[image_idx]\n return image\n return torch.zeros(512)\n\n def get_instruction_text(self):\n \"\"\"Get corresponding instruction text for current environment session\"\"\"\n html_obj = self._parse_html(self.browser.page_source)\n instruction_text = html_obj.find(id='instruction-text').h4.text\n return instruction_text\n\n def _parse_html(self, html=None):\n \"\"\"\n Returns web request result wrapped in BeautifulSoup object\n\n Arguments:\n url (`str`): If no url or html is provided, use the current\n observation (HTML) for parsing.\n \"\"\"\n if html is None:\n html = self.state['html']\n html_obj = BeautifulSoup(html, 'html.parser')\n return html_obj\n ","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_text_env.get_instruction_text","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_text_env.get_instruction_text#L160-L164","kind":"function","name":"get_instruction_text","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":160,"end_line":164,"context_start_line":140,"context_end_line":184,"code":" for opt in buying_options:\n opt_value = opt.get('value')\n self.text_to_clickable[f'{opt_value}'] = opt\n return dict(\n has_search_bar=has_search_bar,\n clickables=list(self.text_to_clickable.keys()),\n )\n \n def get_image(self):\n \"\"\"Scrape image from page HTML and return as a list of pixel values\"\"\"\n html_obj = self._parse_html(self.browser.page_source)\n image_url = html_obj.find(id='product-image')\n if image_url is not None:\n image_url = image_url['src']\n if image_url in self.ids:\n image_idx = self.ids[image_url]\n image = self.feats[image_idx]\n return image\n return torch.zeros(512)\n\n def get_instruction_text(self):\n \"\"\"Get corresponding instruction text for current environment session\"\"\"\n html_obj = self._parse_html(self.browser.page_source)\n instruction_text = html_obj.find(id='instruction-text').h4.text\n return instruction_text\n\n def _parse_html(self, html=None):\n \"\"\"\n Returns web request result wrapped in BeautifulSoup object\n\n Arguments:\n url (`str`): If no url or html is provided, use the current\n observation (HTML) for parsing.\n \"\"\"\n if html is None:\n html = self.state['html']\n html_obj = BeautifulSoup(html, 'html.parser')\n return html_obj\n \n @property\n def observation(self):\n \"\"\"Compiles state into either the `html` or `text` observation mode\"\"\"\n html = self.state['html']\n if self.observation_mode == 'html':\n return html","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_text_env._parse_html","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_text_env._parse_html#L166-L177","kind":"function","name":"_parse_html","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":166,"end_line":177,"context_start_line":146,"context_end_line":197,"code":" )\n \n def get_image(self):\n \"\"\"Scrape image from page HTML and return as a list of pixel values\"\"\"\n html_obj = self._parse_html(self.browser.page_source)\n image_url = html_obj.find(id='product-image')\n if image_url is not None:\n image_url = image_url['src']\n if image_url in self.ids:\n image_idx = self.ids[image_url]\n image = self.feats[image_idx]\n return image\n return torch.zeros(512)\n\n def get_instruction_text(self):\n \"\"\"Get corresponding instruction text for current environment session\"\"\"\n html_obj = self._parse_html(self.browser.page_source)\n instruction_text = html_obj.find(id='instruction-text').h4.text\n return instruction_text\n\n def _parse_html(self, html=None):\n \"\"\"\n Returns web request result wrapped in BeautifulSoup object\n\n Arguments:\n url (`str`): If no url or html is provided, use the current\n observation (HTML) for parsing.\n \"\"\"\n if html is None:\n html = self.state['html']\n html_obj = BeautifulSoup(html, 'html.parser')\n return html_obj\n \n @property\n def observation(self):\n \"\"\"Compiles state into either the `html` or `text` observation mode\"\"\"\n html = self.state['html']\n if self.observation_mode == 'html':\n return html\n elif self.observation_mode == 'text':\n return self.convert_html_to_text(html, simple=True)\n elif self.observation_mode == 'text_rich':\n return self.convert_html_to_text(html, simple=False)\n elif self.observation_mode == 'url':\n return self.state['url']\n else:\n raise ValueError(\n f'Observation mode {self.observation_mode} not supported.'\n )\n \n @property\n def state(self):","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_text_env.observation","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_text_env.observation#L180-L194","kind":"function","name":"observation","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":180,"end_line":194,"context_start_line":160,"context_end_line":214,"code":" def get_instruction_text(self):\n \"\"\"Get corresponding instruction text for current environment session\"\"\"\n html_obj = self._parse_html(self.browser.page_source)\n instruction_text = html_obj.find(id='instruction-text').h4.text\n return instruction_text\n\n def _parse_html(self, html=None):\n \"\"\"\n Returns web request result wrapped in BeautifulSoup object\n\n Arguments:\n url (`str`): If no url or html is provided, use the current\n observation (HTML) for parsing.\n \"\"\"\n if html is None:\n html = self.state['html']\n html_obj = BeautifulSoup(html, 'html.parser')\n return html_obj\n \n @property\n def observation(self):\n \"\"\"Compiles state into either the `html` or `text` observation mode\"\"\"\n html = self.state['html']\n if self.observation_mode == 'html':\n return html\n elif self.observation_mode == 'text':\n return self.convert_html_to_text(html, simple=True)\n elif self.observation_mode == 'text_rich':\n return self.convert_html_to_text(html, simple=False)\n elif self.observation_mode == 'url':\n return self.state['url']\n else:\n raise ValueError(\n f'Observation mode {self.observation_mode} not supported.'\n )\n \n @property\n def state(self):\n \"\"\"\n State that includes all information. The actual observation are\n likely to be a subset or reduced form of the state.\n \"\"\"\n return dict(\n url=self.browser.current_url,\n html=self.browser.page_source,\n instruction_text=self.instruction_text,\n )\n \n def convert_html_to_text(self, html, simple=False):\n \"\"\"Strip HTML of tags and add separators to convert observation into simple mode\"\"\"\n texts = self._parse_html(html).findAll(text=True)\n visible_texts = filter(tag_visible, texts)\n if simple:\n # For `simple` mode, return just [SEP] separators\n return ' [SEP] '.join(t.strip() for t in visible_texts if t != '\\n')","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_text_env.state","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_text_env.state#L197-L206","kind":"function","name":"state","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":197,"end_line":206,"context_start_line":177,"context_end_line":226,"code":" return html_obj\n \n @property\n def observation(self):\n \"\"\"Compiles state into either the `html` or `text` observation mode\"\"\"\n html = self.state['html']\n if self.observation_mode == 'html':\n return html\n elif self.observation_mode == 'text':\n return self.convert_html_to_text(html, simple=True)\n elif self.observation_mode == 'text_rich':\n return self.convert_html_to_text(html, simple=False)\n elif self.observation_mode == 'url':\n return self.state['url']\n else:\n raise ValueError(\n f'Observation mode {self.observation_mode} not supported.'\n )\n \n @property\n def state(self):\n \"\"\"\n State that includes all information. The actual observation are\n likely to be a subset or reduced form of the state.\n \"\"\"\n return dict(\n url=self.browser.current_url,\n html=self.browser.page_source,\n instruction_text=self.instruction_text,\n )\n \n def convert_html_to_text(self, html, simple=False):\n \"\"\"Strip HTML of tags and add separators to convert observation into simple mode\"\"\"\n texts = self._parse_html(html).findAll(text=True)\n visible_texts = filter(tag_visible, texts)\n if simple:\n # For `simple` mode, return just [SEP] separators\n return ' [SEP] '.join(t.strip() for t in visible_texts if t != '\\n')\n else:\n # Otherwise, return an observation with tags mapped to specific, unique separators\n observation = ''\n for t in visible_texts:\n if t == '\\n': continue\n if t.parent.name == 'button': # button\n processed_t = f'[button] {t} [button_]'\n elif t.parent.name == 'label': # options\n if f'\"{t}\"' in self.state['url']:\n processed_t = f' [clicked button] {t} [clicked button_]'\n observation = f'You have clicked {t}.\\n' + observation\n else:","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_text_env.convert_html_to_text","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_text_env.convert_html_to_text#L208-L236","kind":"function","name":"convert_html_to_text","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":208,"end_line":236,"context_start_line":188,"context_end_line":256,"code":" return self.convert_html_to_text(html, simple=False)\n elif self.observation_mode == 'url':\n return self.state['url']\n else:\n raise ValueError(\n f'Observation mode {self.observation_mode} not supported.'\n )\n \n @property\n def state(self):\n \"\"\"\n State that includes all information. The actual observation are\n likely to be a subset or reduced form of the state.\n \"\"\"\n return dict(\n url=self.browser.current_url,\n html=self.browser.page_source,\n instruction_text=self.instruction_text,\n )\n \n def convert_html_to_text(self, html, simple=False):\n \"\"\"Strip HTML of tags and add separators to convert observation into simple mode\"\"\"\n texts = self._parse_html(html).findAll(text=True)\n visible_texts = filter(tag_visible, texts)\n if simple:\n # For `simple` mode, return just [SEP] separators\n return ' [SEP] '.join(t.strip() for t in visible_texts if t != '\\n')\n else:\n # Otherwise, return an observation with tags mapped to specific, unique separators\n observation = ''\n for t in visible_texts:\n if t == '\\n': continue\n if t.parent.name == 'button': # button\n processed_t = f'[button] {t} [button_]'\n elif t.parent.name == 'label': # options\n if f'\"{t}\"' in self.state['url']:\n processed_t = f' [clicked button] {t} [clicked button_]'\n observation = f'You have clicked {t}.\\n' + observation\n else:\n processed_t = f' [button] {t} [button_]'\n elif t.parent.get('class') == [\"product-link\"]: # product asins\n if f'{t}' in self.server.user_sessions[self.session]['asins']:\n processed_t = f'\\n[clicked button] {t} [clicked button_]'\n else:\n processed_t = f'\\n[button] {t} [button_]'\n else: # regular, unclickable text\n processed_t = str(t)\n observation += processed_t + '\\n'\n return observation\n \n def reset(self, session=None, instruction_text=None):\n \"\"\"Create a new session and reset environment variables\"\"\"\n session_int = None\n if session is not None:\n self.session = str(session)\n if isinstance(session, int):\n session_int = session\n else:\n self.session = ''.join(random.choices(string.ascii_lowercase, k=10))\n if self.session_prefix is not None:\n self.session = self.session_prefix + self.session\n\n init_url = f'{self.base_url}/{self.session}'\n self.browser.get(init_url, session_id=self.session, session_int=session_int)\n\n self.text_to_clickable = None\n self.instruction_text = self.get_instruction_text() if instruction_text is None else instruction_text\n obs = self.observation\n self.prev_obs = [obs]","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_text_env.reset","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_text_env.reset#L238-L258","kind":"function","name":"reset","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":238,"end_line":258,"context_start_line":218,"context_end_line":278,"code":" for t in visible_texts:\n if t == '\\n': continue\n if t.parent.name == 'button': # button\n processed_t = f'[button] {t} [button_]'\n elif t.parent.name == 'label': # options\n if f'\"{t}\"' in self.state['url']:\n processed_t = f' [clicked button] {t} [clicked button_]'\n observation = f'You have clicked {t}.\\n' + observation\n else:\n processed_t = f' [button] {t} [button_]'\n elif t.parent.get('class') == [\"product-link\"]: # product asins\n if f'{t}' in self.server.user_sessions[self.session]['asins']:\n processed_t = f'\\n[clicked button] {t} [clicked button_]'\n else:\n processed_t = f'\\n[button] {t} [button_]'\n else: # regular, unclickable text\n processed_t = str(t)\n observation += processed_t + '\\n'\n return observation\n \n def reset(self, session=None, instruction_text=None):\n \"\"\"Create a new session and reset environment variables\"\"\"\n session_int = None\n if session is not None:\n self.session = str(session)\n if isinstance(session, int):\n session_int = session\n else:\n self.session = ''.join(random.choices(string.ascii_lowercase, k=10))\n if self.session_prefix is not None:\n self.session = self.session_prefix + self.session\n\n init_url = f'{self.base_url}/{self.session}'\n self.browser.get(init_url, session_id=self.session, session_int=session_int)\n\n self.text_to_clickable = None\n self.instruction_text = self.get_instruction_text() if instruction_text is None else instruction_text\n obs = self.observation\n self.prev_obs = [obs]\n self.prev_actions = []\n return obs, None\n\n def render(self, mode='human'):\n pass\n\n def close(self):\n pass\n \n\ndef tag_visible(element):\n ignore = {'style', 'script', 'head', 'title', 'meta', '[document]'}\n return (\n element.parent.name not in ignore and not isinstance(element, Comment)\n )\n\n\nclass SimServer:\n \"\"\"Lightweight simulator of WebShop Flask application for generating HTML observations\"\"\"\n def __init__(\n self,\n base_url,","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_text_env.render","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_text_env.render#L260-L261","kind":"function","name":"render","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":260,"end_line":261,"context_start_line":240,"context_end_line":281,"code":" session_int = None\n if session is not None:\n self.session = str(session)\n if isinstance(session, int):\n session_int = session\n else:\n self.session = ''.join(random.choices(string.ascii_lowercase, k=10))\n if self.session_prefix is not None:\n self.session = self.session_prefix + self.session\n\n init_url = f'{self.base_url}/{self.session}'\n self.browser.get(init_url, session_id=self.session, session_int=session_int)\n\n self.text_to_clickable = None\n self.instruction_text = self.get_instruction_text() if instruction_text is None else instruction_text\n obs = self.observation\n self.prev_obs = [obs]\n self.prev_actions = []\n return obs, None\n\n def render(self, mode='human'):\n pass\n\n def close(self):\n pass\n \n\ndef tag_visible(element):\n ignore = {'style', 'script', 'head', 'title', 'meta', '[document]'}\n return (\n element.parent.name not in ignore and not isinstance(element, Comment)\n )\n\n\nclass SimServer:\n \"\"\"Lightweight simulator of WebShop Flask application for generating HTML observations\"\"\"\n def __init__(\n self,\n base_url,\n file_path,\n filter_goals=None,\n limit_goals=-1,","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_text_env.close","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_text_env.close#L263-L264","kind":"function","name":"close","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":263,"end_line":264,"context_start_line":243,"context_end_line":284,"code":" if isinstance(session, int):\n session_int = session\n else:\n self.session = ''.join(random.choices(string.ascii_lowercase, k=10))\n if self.session_prefix is not None:\n self.session = self.session_prefix + self.session\n\n init_url = f'{self.base_url}/{self.session}'\n self.browser.get(init_url, session_id=self.session, session_int=session_int)\n\n self.text_to_clickable = None\n self.instruction_text = self.get_instruction_text() if instruction_text is None else instruction_text\n obs = self.observation\n self.prev_obs = [obs]\n self.prev_actions = []\n return obs, None\n\n def render(self, mode='human'):\n pass\n\n def close(self):\n pass\n \n\ndef tag_visible(element):\n ignore = {'style', 'script', 'head', 'title', 'meta', '[document]'}\n return (\n element.parent.name not in ignore and not isinstance(element, Comment)\n )\n\n\nclass SimServer:\n \"\"\"Lightweight simulator of WebShop Flask application for generating HTML observations\"\"\"\n def __init__(\n self,\n base_url,\n file_path,\n filter_goals=None,\n limit_goals=-1,\n num_products=None,\n human_goals=True,\n show_attrs=False,","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_text_env.index","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_text_env.index#L340-L348","kind":"function","name":"index","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":340,"end_line":348,"context_start_line":320,"context_end_line":368,"code":" idxs = []\n while len(idxs) < limit_goals:\n idx = random_idx(self.cum_weights)\n if idx not in idxs:\n idxs.append(idx)\n self.goals = [self.goals[i] for i in idxs]\n print(f'Loaded {len(self.goals)} goals.')\n\n # Set extraneous housekeeping variables\n self.weights = [goal['weight'] for goal in self.goals]\n self.cum_weights = [0]\n for w in self.weights:\n self.cum_weights.append(self.cum_weights[-1] + w)\n self.user_sessions = dict()\n self.search_time = 0\n self.render_time = 0\n self.sample_time = 0\n self.assigned_instruction_text = None # TODO: very hacky, should remove\n \n @app.route('/', methods=['GET', 'POST'])\n def index(self, session_id, **kwargs):\n \"\"\"Redirect to the search page with the given session ID\"\"\"\n html = map_action_to_html(\n 'start',\n session_id=session_id,\n instruction_text=kwargs['instruction_text'],\n )\n url = f'{self.base_url}/{session_id}'\n return html, url\n \n @app.route('/', methods=['GET', 'POST'])\n def search_results(self, session_id, **kwargs):\n \"\"\"Initialize session and return the search results page\"\"\"\n session = self.user_sessions[session_id]\n keywords = kwargs['keywords'] # TODO: why is this using kwargs? why not session?\n assert isinstance(keywords, list)\n page = 1 if 'page' not in kwargs else kwargs['page']\n session[\"page\"] = page\n session[\"keywords\"] = keywords\n session[\"actions\"][\"search\"] += 1\n session[\"asin\"] = None\n session[\"options\"] = {}\n\n # Perform search on keywords from items and record amount of time it takes\n old_time = time.time()\n top_n_products = get_top_n_product_from_keywords(\n keywords,\n self.search_engine,\n self.all_products,","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_text_env.search_results","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_text_env.search_results#L351-L394","kind":"function","name":"search_results","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":351,"end_line":394,"context_start_line":331,"context_end_line":414,"code":" for w in self.weights:\n self.cum_weights.append(self.cum_weights[-1] + w)\n self.user_sessions = dict()\n self.search_time = 0\n self.render_time = 0\n self.sample_time = 0\n self.assigned_instruction_text = None # TODO: very hacky, should remove\n \n @app.route('/', methods=['GET', 'POST'])\n def index(self, session_id, **kwargs):\n \"\"\"Redirect to the search page with the given session ID\"\"\"\n html = map_action_to_html(\n 'start',\n session_id=session_id,\n instruction_text=kwargs['instruction_text'],\n )\n url = f'{self.base_url}/{session_id}'\n return html, url\n \n @app.route('/', methods=['GET', 'POST'])\n def search_results(self, session_id, **kwargs):\n \"\"\"Initialize session and return the search results page\"\"\"\n session = self.user_sessions[session_id]\n keywords = kwargs['keywords'] # TODO: why is this using kwargs? why not session?\n assert isinstance(keywords, list)\n page = 1 if 'page' not in kwargs else kwargs['page']\n session[\"page\"] = page\n session[\"keywords\"] = keywords\n session[\"actions\"][\"search\"] += 1\n session[\"asin\"] = None\n session[\"options\"] = {}\n\n # Perform search on keywords from items and record amount of time it takes\n old_time = time.time()\n top_n_products = get_top_n_product_from_keywords(\n keywords,\n self.search_engine,\n self.all_products,\n self.product_item_dict,\n )\n self.search_time += time.time() - old_time\n \n # Get product list from search result asins and get list of corresponding URLs\n products = get_product_per_page(top_n_products, page)\n\n keywords_url_string = '+'.join(keywords)\n url = (\n f'{self.base_url}/search_results/{session_id}/'\n f'{keywords_url_string}/{page}'\n )\n\n # Render HTML search page and record amount of time taken\n old_time = time.time()\n html = map_action_to_html(\n 'search',\n session_id=session_id,\n products=products,\n keywords=session[\"keywords\"],\n page=page,\n total=len(top_n_products),\n instruction_text=session[\"goal\"][\"instruction_text\"],\n )\n self.render_time += time.time() - old_time\n return html, url\n \n @app.route('/', methods=['GET', 'POST'])\n def item_page(self, session_id, **kwargs):\n \"\"\"Render and return the HTML for a product item page\"\"\"\n session = self.user_sessions[session_id]\n clickable_name = kwargs['clickable_name']\n text_to_clickable = kwargs['text_to_clickable']\n clickable = text_to_clickable[clickable_name]\n\n # Update session logs with information of last product asin selected\n if (clickable.get('class') is not None and\n clickable.get('class')[0] == 'product-link'):\n session[\"asin\"] = clickable_name.upper()\n session[\"actions\"][\"asin\"] += 1\n session[\"asins\"].add(session[\"asin\"])\n elif clickable.get('name') is not None:\n clickable_key = clickable['name'].lower()\n session[\"options\"][clickable_key] = clickable_name\n session[\"actions\"][\"options\"] += 1\n","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_text_env.item_page","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_text_env.item_page#L397-L437","kind":"function","name":"item_page","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":397,"end_line":437,"context_start_line":377,"context_end_line":457,"code":" url = (\n f'{self.base_url}/search_results/{session_id}/'\n f'{keywords_url_string}/{page}'\n )\n\n # Render HTML search page and record amount of time taken\n old_time = time.time()\n html = map_action_to_html(\n 'search',\n session_id=session_id,\n products=products,\n keywords=session[\"keywords\"],\n page=page,\n total=len(top_n_products),\n instruction_text=session[\"goal\"][\"instruction_text\"],\n )\n self.render_time += time.time() - old_time\n return html, url\n \n @app.route('/', methods=['GET', 'POST'])\n def item_page(self, session_id, **kwargs):\n \"\"\"Render and return the HTML for a product item page\"\"\"\n session = self.user_sessions[session_id]\n clickable_name = kwargs['clickable_name']\n text_to_clickable = kwargs['text_to_clickable']\n clickable = text_to_clickable[clickable_name]\n\n # Update session logs with information of last product asin selected\n if (clickable.get('class') is not None and\n clickable.get('class')[0] == 'product-link'):\n session[\"asin\"] = clickable_name.upper()\n session[\"actions\"][\"asin\"] += 1\n session[\"asins\"].add(session[\"asin\"])\n elif clickable.get('name') is not None:\n clickable_key = clickable['name'].lower()\n session[\"options\"][clickable_key] = clickable_name\n session[\"actions\"][\"options\"] += 1\n\n # Set fields + url of page, then render page's HTML\n product_info = self.product_item_dict[session[\"asin\"]]\n keywords_url_string = '+'.join(session[\"keywords\"])\n option_string = json.dumps(session['options'])\n\n url = (\n f'{self.base_url}/item_page/{session_id}/'\n f'{session[\"asin\"]}/{keywords_url_string}/'\n f'{session[\"page\"]}/{option_string}'\n )\n\n html = map_action_to_html(\n 'click',\n session_id=session_id,\n product_info=product_info,\n keywords=session[\"keywords\"],\n page=session[\"page\"],\n asin=session[\"asin\"],\n options=session[\"options\"],\n instruction_text=session[\"goal\"][\"instruction_text\"],\n show_attrs=self.show_attrs,\n )\n return html, url\n\n @app.route('/', methods=['GET', 'POST'])\n def item_sub_page(self, session_id, **kwargs):\n \"\"\"Render and return the HTML for a product's sub page (i.e. description, features)\"\"\"\n session = self.user_sessions[session_id]\n clickable_name = kwargs['clickable_name']\n for k in ACTION_TO_TEMPLATE:\n if clickable_name.lower() == k.lower():\n clickable_name = k\n break\n \n # Set fields + url of page, then render page's HTML\n product_info = self.product_item_dict[session[\"asin\"]]\n session[\"actions\"][clickable_name] += 1\n keywords_url_string = '+'.join(session[\"keywords\"])\n url = (\n f'{self.base_url}/item_sub_page/{session_id}/'\n f'{session[\"asin\"]}/{keywords_url_string}/{session[\"page\"]}/'\n f'{clickable_name}/{session[\"options\"]}'\n )","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_text_env.item_sub_page","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_text_env.item_sub_page#L440-L468","kind":"function","name":"item_sub_page","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":440,"end_line":468,"context_start_line":420,"context_end_line":488,"code":" url = (\n f'{self.base_url}/item_page/{session_id}/'\n f'{session[\"asin\"]}/{keywords_url_string}/'\n f'{session[\"page\"]}/{option_string}'\n )\n\n html = map_action_to_html(\n 'click',\n session_id=session_id,\n product_info=product_info,\n keywords=session[\"keywords\"],\n page=session[\"page\"],\n asin=session[\"asin\"],\n options=session[\"options\"],\n instruction_text=session[\"goal\"][\"instruction_text\"],\n show_attrs=self.show_attrs,\n )\n return html, url\n\n @app.route('/', methods=['GET', 'POST'])\n def item_sub_page(self, session_id, **kwargs):\n \"\"\"Render and return the HTML for a product's sub page (i.e. description, features)\"\"\"\n session = self.user_sessions[session_id]\n clickable_name = kwargs['clickable_name']\n for k in ACTION_TO_TEMPLATE:\n if clickable_name.lower() == k.lower():\n clickable_name = k\n break\n \n # Set fields + url of page, then render page's HTML\n product_info = self.product_item_dict[session[\"asin\"]]\n session[\"actions\"][clickable_name] += 1\n keywords_url_string = '+'.join(session[\"keywords\"])\n url = (\n f'{self.base_url}/item_sub_page/{session_id}/'\n f'{session[\"asin\"]}/{keywords_url_string}/{session[\"page\"]}/'\n f'{clickable_name}/{session[\"options\"]}'\n )\n html = map_action_to_html(\n f'click[{clickable_name}]',\n session_id=session_id,\n product_info=product_info,\n keywords=session[\"keywords\"],\n page=session[\"page\"],\n asin=session[\"asin\"],\n options=session[\"options\"],\n instruction_text=session[\"goal\"][\"instruction_text\"],\n )\n return html, url\n\n @app.route('/', methods=['GET', 'POST'])\n def done(self, session_id, **kwargs):\n \"\"\"Render and return HTML for done page\"\"\"\n session = self.user_sessions[session_id]\n goal = self.user_sessions[session_id]['goal']\n purchased_product = self.product_item_dict[session[\"asin\"]]\n session[\"actions\"][\"purchase\"] += 1\n price = self.product_prices.get(session[\"asin\"])\n\n # Calculate reward for selected product and set variables for page details\n reward, info = get_reward(\n purchased_product,\n goal,\n price=price,\n options=session[\"options\"],\n verbose=True\n )\n\n self.user_sessions[session_id]['verbose_info'] = info","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_text_env.done","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_text_env.done#L471-L504","kind":"function","name":"done","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":471,"end_line":504,"context_start_line":451,"context_end_line":524,"code":" session[\"actions\"][clickable_name] += 1\n keywords_url_string = '+'.join(session[\"keywords\"])\n url = (\n f'{self.base_url}/item_sub_page/{session_id}/'\n f'{session[\"asin\"]}/{keywords_url_string}/{session[\"page\"]}/'\n f'{clickable_name}/{session[\"options\"]}'\n )\n html = map_action_to_html(\n f'click[{clickable_name}]',\n session_id=session_id,\n product_info=product_info,\n keywords=session[\"keywords\"],\n page=session[\"page\"],\n asin=session[\"asin\"],\n options=session[\"options\"],\n instruction_text=session[\"goal\"][\"instruction_text\"],\n )\n return html, url\n\n @app.route('/', methods=['GET', 'POST'])\n def done(self, session_id, **kwargs):\n \"\"\"Render and return HTML for done page\"\"\"\n session = self.user_sessions[session_id]\n goal = self.user_sessions[session_id]['goal']\n purchased_product = self.product_item_dict[session[\"asin\"]]\n session[\"actions\"][\"purchase\"] += 1\n price = self.product_prices.get(session[\"asin\"])\n\n # Calculate reward for selected product and set variables for page details\n reward, info = get_reward(\n purchased_product,\n goal,\n price=price,\n options=session[\"options\"],\n verbose=True\n )\n\n self.user_sessions[session_id]['verbose_info'] = info\n self.user_sessions[session_id]['done'] = True\n self.user_sessions[session_id]['reward'] = reward\n\n url = (\n f'{self.base_url}/done/{session_id}/'\n f'{session[\"asin\"]}/{session[\"options\"]}'\n )\n html = map_action_to_html(\n f'click[{END_BUTTON}]',\n session_id=session_id,\n reward=reward,\n asin=session[\"asin\"],\n options=session[\"options\"],\n instruction_text=session[\"goal\"][\"instruction_text\"],\n )\n return html, url, reward\n \n def receive(self, session_id, current_url, session_int=None, **kwargs):\n \"\"\"Map action to the corresponding page\"\"\"\n status = dict(reward=0.0, done=False)\n\n with app.app_context(), app.test_request_context():\n # Create/determine goal, instruction_text from current session\n if session_id not in self.user_sessions:\n idx = session_int if (session_int is not None and isinstance(session_int, int)) else random_idx(self.cum_weights) \n goal = self.goals[idx]\n instruction_text = goal['instruction_text']\n self.user_sessions[session_id] = {'goal': goal, 'done': False}\n else:\n instruction_text = \\\n self.user_sessions[session_id]['goal']['instruction_text']\n if self.assigned_instruction_text is not None:\n instruction_text = self.assigned_instruction_text # TODO: very hacky, should remove\n self.user_sessions[session_id]['goal']['instruction_text'] = instruction_text\n session = self.user_sessions[session_id]\n","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_text_env.receive","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_text_env.receive#L506-L589","kind":"function","name":"receive","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":506,"end_line":589,"context_start_line":486,"context_end_line":609,"code":" )\n\n self.user_sessions[session_id]['verbose_info'] = info\n self.user_sessions[session_id]['done'] = True\n self.user_sessions[session_id]['reward'] = reward\n\n url = (\n f'{self.base_url}/done/{session_id}/'\n f'{session[\"asin\"]}/{session[\"options\"]}'\n )\n html = map_action_to_html(\n f'click[{END_BUTTON}]',\n session_id=session_id,\n reward=reward,\n asin=session[\"asin\"],\n options=session[\"options\"],\n instruction_text=session[\"goal\"][\"instruction_text\"],\n )\n return html, url, reward\n \n def receive(self, session_id, current_url, session_int=None, **kwargs):\n \"\"\"Map action to the corresponding page\"\"\"\n status = dict(reward=0.0, done=False)\n\n with app.app_context(), app.test_request_context():\n # Create/determine goal, instruction_text from current session\n if session_id not in self.user_sessions:\n idx = session_int if (session_int is not None and isinstance(session_int, int)) else random_idx(self.cum_weights) \n goal = self.goals[idx]\n instruction_text = goal['instruction_text']\n self.user_sessions[session_id] = {'goal': goal, 'done': False}\n else:\n instruction_text = \\\n self.user_sessions[session_id]['goal']['instruction_text']\n if self.assigned_instruction_text is not None:\n instruction_text = self.assigned_instruction_text # TODO: very hacky, should remove\n self.user_sessions[session_id]['goal']['instruction_text'] = instruction_text\n session = self.user_sessions[session_id]\n\n if not kwargs:\n # If no action, reset the session variables\n kwargs['instruction_text'] = instruction_text\n html, url = self.index(session_id, **kwargs)\n self.user_sessions[session_id].update(\n {\n 'keywords': None,\n 'page': None,\n 'asin': None,\n 'asins': set(),\n 'options': dict(),\n 'actions': defaultdict(int)\n }\n )\n elif 'keywords' in kwargs:\n # If search keywords are available, run a search\n html, url = self.search_results(session_id, **kwargs)\n elif 'clickable_name' in kwargs:\n clickable_name = kwargs['clickable_name'].lower()\n if clickable_name == END_BUTTON.lower():\n # If \"buy now\" clicked, calculate reward and flag session as terminated\n html, url, reward = self.done(session_id, **kwargs)\n status['reward'] = reward\n status['done'] = True\n elif clickable_name == BACK_TO_SEARCH.lower():\n # If \"back to search\" clicked, recursively reset the session back to search page\n html, url, status = self.receive(session_id, current_url)\n elif (clickable_name == NEXT_PAGE.lower() and \n self.get_page_name(current_url) == 'search_results'):\n # If \"next page\" clicked from search results, re-render with `page` enumerated\n html, url, status = self.receive(\n session_id,\n current_url,\n keywords=session[\"keywords\"],\n page=session[\"page\"] + 1,\n )\n elif (clickable_name == PREV_PAGE.lower() and \n self.get_page_name(current_url) == 'search_results'):\n # If \"prev page\" clicked from search results, re-render with `page` denumerated\n html, url, status = self.receive(\n session_id,\n current_url,\n keywords=session[\"keywords\"],\n page=session[\"page\"] - 1,\n )\n elif (clickable_name == PREV_PAGE.lower() and \n self.get_page_name(current_url) == 'item_sub_page'):\n # If \"prev page\" clicked from sub page, return to corresponding item page\n html, url = self.item_page(session_id, **kwargs)\n elif (clickable_name == PREV_PAGE.lower() and \n self.get_page_name(current_url) == 'item_page'):\n # If \"prev page\" clicked from item page, return to search results page\n html, url = self.search_results(\n session_id,\n keywords=session[\"keywords\"],\n page=session[\"page\"],\n **kwargs\n )\n elif clickable_name in [k.lower() for k in ACTION_TO_TEMPLATE]:\n # Render item_sub_page if clickable is description, features, or reviews\n html, url = self.item_sub_page(session_id, **kwargs)\n else:\n # Otherwise, render current item page\n html, url = self.item_page(session_id, **kwargs)\n return html, url, status\n \n def get_page_name(self, url):\n \"\"\"Determine which page (i.e. item_page, search_results) the given URL is pointing at\"\"\"\n if url is None:\n return None\n page_names = [\n 'search_results',\n 'item_page',\n 'item_sub_page',\n 'done'\n ]\n for page_name in page_names:\n if page_name in url:\n return page_name\n return '' # index page\n\n\nclass SimBrowser:\n \"\"\"Simulated browser for rendering the HTML source of WebShop environment pages\"\"\"\n def __init__(self, server):","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_text_env.get_page_name","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_text_env.get_page_name#L591-L604","kind":"function","name":"get_page_name","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":591,"end_line":604,"context_start_line":571,"context_end_line":624,"code":" self.get_page_name(current_url) == 'item_sub_page'):\n # If \"prev page\" clicked from sub page, return to corresponding item page\n html, url = self.item_page(session_id, **kwargs)\n elif (clickable_name == PREV_PAGE.lower() and \n self.get_page_name(current_url) == 'item_page'):\n # If \"prev page\" clicked from item page, return to search results page\n html, url = self.search_results(\n session_id,\n keywords=session[\"keywords\"],\n page=session[\"page\"],\n **kwargs\n )\n elif clickable_name in [k.lower() for k in ACTION_TO_TEMPLATE]:\n # Render item_sub_page if clickable is description, features, or reviews\n html, url = self.item_sub_page(session_id, **kwargs)\n else:\n # Otherwise, render current item page\n html, url = self.item_page(session_id, **kwargs)\n return html, url, status\n \n def get_page_name(self, url):\n \"\"\"Determine which page (i.e. item_page, search_results) the given URL is pointing at\"\"\"\n if url is None:\n return None\n page_names = [\n 'search_results',\n 'item_page',\n 'item_sub_page',\n 'done'\n ]\n for page_name in page_names:\n if page_name in url:\n return page_name\n return '' # index page\n\n\nclass SimBrowser:\n \"\"\"Simulated browser for rendering the HTML source of WebShop environment pages\"\"\"\n def __init__(self, server):\n self.server = server\n self.current_url = None\n self.page_source = None\n self.session_id = None\n\n def get(self, url, session_id=None, session_int=None):\n \"\"\"Set browser variables to corresponding link, page HTML for URL\"\"\"\n self.session_id = url.split('/')[-1] if session_id is None else session_id\n self.page_source, _, _ = \\\n self.server.receive(self.session_id, self.current_url, session_int=session_int)\n self.current_url = url\n \n def click(self, clickable_name, text_to_clickable):\n \"\"\"Wrapper for `receive` handler for performing click action on current page\"\"\"\n self.page_source, self.current_url, status = \\","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_text_env.get","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_text_env.get#L615-L620","kind":"function","name":"get","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":615,"end_line":620,"context_start_line":595,"context_end_line":640,"code":" page_names = [\n 'search_results',\n 'item_page',\n 'item_sub_page',\n 'done'\n ]\n for page_name in page_names:\n if page_name in url:\n return page_name\n return '' # index page\n\n\nclass SimBrowser:\n \"\"\"Simulated browser for rendering the HTML source of WebShop environment pages\"\"\"\n def __init__(self, server):\n self.server = server\n self.current_url = None\n self.page_source = None\n self.session_id = None\n\n def get(self, url, session_id=None, session_int=None):\n \"\"\"Set browser variables to corresponding link, page HTML for URL\"\"\"\n self.session_id = url.split('/')[-1] if session_id is None else session_id\n self.page_source, _, _ = \\\n self.server.receive(self.session_id, self.current_url, session_int=session_int)\n self.current_url = url\n \n def click(self, clickable_name, text_to_clickable):\n \"\"\"Wrapper for `receive` handler for performing click action on current page\"\"\"\n self.page_source, self.current_url, status = \\\n self.server.receive(\n self.session_id,\n current_url=self.current_url,\n clickable_name=clickable_name,\n text_to_clickable=text_to_clickable,\n )\n return status\n \n def search(self, keywords):\n \"\"\"Wrapper for `receive` handler for performing search action on current page\"\"\"\n if isinstance(keywords, str):\n keywords = keywords.split(' ')\n self.page_source, self.current_url, status = \\\n self.server.receive(\n self.session_id,\n current_url=self.current_url,","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_text_env.click","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_text_env.click#L622-L631","kind":"function","name":"click","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":622,"end_line":631,"context_start_line":602,"context_end_line":643,"code":" if page_name in url:\n return page_name\n return '' # index page\n\n\nclass SimBrowser:\n \"\"\"Simulated browser for rendering the HTML source of WebShop environment pages\"\"\"\n def __init__(self, server):\n self.server = server\n self.current_url = None\n self.page_source = None\n self.session_id = None\n\n def get(self, url, session_id=None, session_int=None):\n \"\"\"Set browser variables to corresponding link, page HTML for URL\"\"\"\n self.session_id = url.split('/')[-1] if session_id is None else session_id\n self.page_source, _, _ = \\\n self.server.receive(self.session_id, self.current_url, session_int=session_int)\n self.current_url = url\n \n def click(self, clickable_name, text_to_clickable):\n \"\"\"Wrapper for `receive` handler for performing click action on current page\"\"\"\n self.page_source, self.current_url, status = \\\n self.server.receive(\n self.session_id,\n current_url=self.current_url,\n clickable_name=clickable_name,\n text_to_clickable=text_to_clickable,\n )\n return status\n \n def search(self, keywords):\n \"\"\"Wrapper for `receive` handler for performing search action on current page\"\"\"\n if isinstance(keywords, str):\n keywords = keywords.split(' ')\n self.page_source, self.current_url, status = \\\n self.server.receive(\n self.session_id,\n current_url=self.current_url,\n keywords=keywords,\n )\n return status","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.envs.web_agent_text_env.search","uri":"program://BOLAA/function/webshop.web_agent_site.envs.web_agent_text_env.search#L633-L643","kind":"function","name":"search","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":633,"end_line":643,"context_start_line":613,"context_end_line":643,"code":" self.session_id = None\n\n def get(self, url, session_id=None, session_int=None):\n \"\"\"Set browser variables to corresponding link, page HTML for URL\"\"\"\n self.session_id = url.split('/')[-1] if session_id is None else session_id\n self.page_source, _, _ = \\\n self.server.receive(self.session_id, self.current_url, session_int=session_int)\n self.current_url = url\n \n def click(self, clickable_name, text_to_clickable):\n \"\"\"Wrapper for `receive` handler for performing click action on current page\"\"\"\n self.page_source, self.current_url, status = \\\n self.server.receive(\n self.session_id,\n current_url=self.current_url,\n clickable_name=clickable_name,\n text_to_clickable=text_to_clickable,\n )\n return status\n \n def search(self, keywords):\n \"\"\"Wrapper for `receive` handler for performing search action on current page\"\"\"\n if isinstance(keywords, str):\n keywords = keywords.split(' ')\n self.page_source, self.current_url, status = \\\n self.server.receive(\n self.session_id,\n current_url=self.current_url,\n keywords=keywords,\n )\n return status","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.engine.normalize","uri":"program://BOLAA/module/webshop.web_agent_site.engine.normalize#L1-L103","kind":"module","name":"webshop.web_agent_site.engine.normalize","path":"webshop/web_agent_site/engine/normalize.py","language":"python","start_line":1,"end_line":103,"context_start_line":1,"context_end_line":103,"code":"import re\nfrom typing import Tuple\n\nCOLOR_SET = [\n 'alabaster', 'apricot', 'aqua', 'ash', 'asphalt', 'azure',\n 'banana', 'beige', 'black', 'blue', 'blush', 'bordeaux', 'bronze',\n 'brown', 'burgundy', 'camel', 'camo', 'caramel', 'champagne',\n 'charcoal', 'cheetah', 'chestnut', 'chocolate', 'christmas', 'coffee',\n 'cognac', 'copper', 'coral', 'cranberry', 'cream', 'crystal', 'dark',\n 'denim', 'eggplant', 'elephant', 'espresso', 'fuchsia', 'gold', 'granite',\n 'grape', 'graphite', 'grass', 'gray', 'green', 'grey', 'heather', 'indigo',\n 'ivory', 'ivy', 'khaki', 'lavender', 'lemon', 'leopard', 'light', 'lilac',\n 'lime', 'magenta', 'maroon', 'mauve', 'merlot', 'midnight', 'mint', 'mocha',\n 'multicolor', 'mushroom', 'mustard', 'natural', 'navy', 'nude', 'olive',\n 'orange', 'peach', 'pewter', 'pink', 'plum', 'purple', 'rainbow', 'red',\n 'rose', 'royal', 'rust', 'sand', 'sapphire', 'seashell', 'silver', 'skull',\n 'slate', 'steel', 'stone', 'stonewash', 'sunflower', 'tan', 'taupe', 'teal',\n 'tiger', 'turquoise', 'violet', 'walnut', 'wheat', 'white', 'wine', 'yellow',\n]\n\nSIZE_SET = [\n 'xx-large', '3x-large', '4x-large', '5x-large', 'x-large', 'x-small',\n 'medium', 'large', 'small',\n 'queen', 'twin', 'full', 'king', 'one size',\n 'pack',\n]\n\nSIZE_PATTERNS = [\n re.compile(r'(.*)neck(.*)sleeve'),\n re.compile(r'(.*) women \\| (.*) men'),\n re.compile(r'(.*)w x(.*)l'),\n re.compile(r'(.*)w by (.*)l'),\n re.compile(r'(.*)w x(.*)h'),\n re.compile(r'(.*)wide'),\n re.compile(r'(.*)x-wide'),\n re.compile(r'(.*)narrow'),\n re.compile(r'(.*)petite'),\n re.compile(r'(.*)inch'),\n re.compile(r'(.*)plus'),\n re.compile(r'(.*)mm'),\n re.compile(r'women(.*)'),\n re.compile(r'(.*)x(.*)'),\n re.compile(r'(.*)ft'),\n re.compile(r'(.*)feet'),\n re.compile(r'(.*)meter'),\n re.compile(r'(.*)yards'),\n re.compile(r'(.*)\\*(.*)'),\n re.compile(r'(.*)\\-(.*)'),\n re.compile(r'(\\d+)\"$'),\n re.compile(r'(\\d+)f$'),\n re.compile(r'(\\d+)m$'),\n re.compile(r'(\\d+)cm$'),\n re.compile(r'(\\d+)g$'),\n]\nSIZE_PATTERNS = [re.compile(s) for s in SIZE_SET] + SIZE_PATTERNS\n\ndef normalize_color(color_string: str) -> str:\n \"\"\"Extracts the first color found if exists\"\"\"\n for norm_color in COLOR_SET:\n if norm_color in color_string:\n return norm_color\n return color_string\n\ndef normalize_color_size(product_prices: dict) -> Tuple[dict, dict]:\n \"\"\"Get mappings of all colors, sizes to corresponding values in COLOR_SET, SIZE_PATTERNS\"\"\"\n \n # Get all colors, sizes from list of all products\n all_colors, all_sizes = set(), set()\n for (_, color, size), _ in product_prices.items():\n all_colors.add(color.lower())\n all_sizes.add(size.lower())\n \n # Create mapping of each original color value to corresponding set value\n color_mapping = {'N.A.': 'not_matched'} \n for c in all_colors:\n matched = False\n for base in COLOR_SET:\n if base in c:\n color_mapping[c] = base\n matched = True\n break\n if not matched:\n color_mapping[c] = 'not_matched'\n\n # Create mapping of each original size value to corresponding set value\n size_mapping = {'N.A.': 'not_matched'}\n for s in all_sizes:\n matched = False\n for pattern in SIZE_PATTERNS:\n m = re.search(pattern, s)\n if m is not None:\n matched = True\n size_mapping[s] = pattern.pattern\n break\n if not matched:\n if s.replace('.', '', 1).isdigit():\n size_mapping[s] = 'numeric_size'\n matched= True\n if not matched:\n size_mapping[s] = 'not_matched'\n \n return color_mapping, size_mapping\n ","source_hash":"1962113ac9e209a636d4f181b2c70544bbea59b03adca9847e48287158d794fb","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.engine.normalize.normalize_color","uri":"program://BOLAA/function/webshop.web_agent_site.engine.normalize.normalize_color#L57-L62","kind":"function","name":"normalize_color","path":"webshop/web_agent_site/engine/normalize.py","language":"python","start_line":57,"end_line":62,"context_start_line":37,"context_end_line":82,"code":" re.compile(r'(.*)petite'),\n re.compile(r'(.*)inch'),\n re.compile(r'(.*)plus'),\n re.compile(r'(.*)mm'),\n re.compile(r'women(.*)'),\n re.compile(r'(.*)x(.*)'),\n re.compile(r'(.*)ft'),\n re.compile(r'(.*)feet'),\n re.compile(r'(.*)meter'),\n re.compile(r'(.*)yards'),\n re.compile(r'(.*)\\*(.*)'),\n re.compile(r'(.*)\\-(.*)'),\n re.compile(r'(\\d+)\"$'),\n re.compile(r'(\\d+)f$'),\n re.compile(r'(\\d+)m$'),\n re.compile(r'(\\d+)cm$'),\n re.compile(r'(\\d+)g$'),\n]\nSIZE_PATTERNS = [re.compile(s) for s in SIZE_SET] + SIZE_PATTERNS\n\ndef normalize_color(color_string: str) -> str:\n \"\"\"Extracts the first color found if exists\"\"\"\n for norm_color in COLOR_SET:\n if norm_color in color_string:\n return norm_color\n return color_string\n\ndef normalize_color_size(product_prices: dict) -> Tuple[dict, dict]:\n \"\"\"Get mappings of all colors, sizes to corresponding values in COLOR_SET, SIZE_PATTERNS\"\"\"\n \n # Get all colors, sizes from list of all products\n all_colors, all_sizes = set(), set()\n for (_, color, size), _ in product_prices.items():\n all_colors.add(color.lower())\n all_sizes.add(size.lower())\n \n # Create mapping of each original color value to corresponding set value\n color_mapping = {'N.A.': 'not_matched'} \n for c in all_colors:\n matched = False\n for base in COLOR_SET:\n if base in c:\n color_mapping[c] = base\n matched = True\n break\n if not matched:","source_hash":"1962113ac9e209a636d4f181b2c70544bbea59b03adca9847e48287158d794fb","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.engine.normalize.normalize_color_size","uri":"program://BOLAA/function/webshop.web_agent_site.engine.normalize.normalize_color_size#L64-L102","kind":"function","name":"normalize_color_size","path":"webshop/web_agent_site/engine/normalize.py","language":"python","start_line":64,"end_line":102,"context_start_line":44,"context_end_line":103,"code":" re.compile(r'(.*)feet'),\n re.compile(r'(.*)meter'),\n re.compile(r'(.*)yards'),\n re.compile(r'(.*)\\*(.*)'),\n re.compile(r'(.*)\\-(.*)'),\n re.compile(r'(\\d+)\"$'),\n re.compile(r'(\\d+)f$'),\n re.compile(r'(\\d+)m$'),\n re.compile(r'(\\d+)cm$'),\n re.compile(r'(\\d+)g$'),\n]\nSIZE_PATTERNS = [re.compile(s) for s in SIZE_SET] + SIZE_PATTERNS\n\ndef normalize_color(color_string: str) -> str:\n \"\"\"Extracts the first color found if exists\"\"\"\n for norm_color in COLOR_SET:\n if norm_color in color_string:\n return norm_color\n return color_string\n\ndef normalize_color_size(product_prices: dict) -> Tuple[dict, dict]:\n \"\"\"Get mappings of all colors, sizes to corresponding values in COLOR_SET, SIZE_PATTERNS\"\"\"\n \n # Get all colors, sizes from list of all products\n all_colors, all_sizes = set(), set()\n for (_, color, size), _ in product_prices.items():\n all_colors.add(color.lower())\n all_sizes.add(size.lower())\n \n # Create mapping of each original color value to corresponding set value\n color_mapping = {'N.A.': 'not_matched'} \n for c in all_colors:\n matched = False\n for base in COLOR_SET:\n if base in c:\n color_mapping[c] = base\n matched = True\n break\n if not matched:\n color_mapping[c] = 'not_matched'\n\n # Create mapping of each original size value to corresponding set value\n size_mapping = {'N.A.': 'not_matched'}\n for s in all_sizes:\n matched = False\n for pattern in SIZE_PATTERNS:\n m = re.search(pattern, s)\n if m is not None:\n matched = True\n size_mapping[s] = pattern.pattern\n break\n if not matched:\n if s.replace('.', '', 1).isdigit():\n size_mapping[s] = 'numeric_size'\n matched= True\n if not matched:\n size_mapping[s] = 'not_matched'\n \n return color_mapping, size_mapping\n ","source_hash":"1962113ac9e209a636d4f181b2c70544bbea59b03adca9847e48287158d794fb","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.engine.goal","uri":"program://BOLAA/module/webshop.web_agent_site.engine.goal#L1-L269","kind":"module","name":"webshop.web_agent_site.engine.goal","path":"webshop/web_agent_site/engine/goal.py","language":"python","start_line":1,"end_line":269,"context_start_line":1,"context_end_line":269,"code":"\"\"\"\nFunctions for specifying goals and reward calculations.\n\"\"\"\nimport itertools\nimport random\nimport spacy\nfrom collections import defaultdict\nfrom rich import print\nfrom thefuzz import fuzz\nfrom web_agent_site.engine.normalize import normalize_color\n\nnlp = spacy.load(\"en_core_web_lg\")\n\nPRICE_RANGE = [10.0 * i for i in range(1, 100)]\n\ndef get_goals(all_products, product_prices, human_goals=True):\n if human_goals:\n return get_human_goals(all_products, product_prices)\n else:\n return get_synthetic_goals(all_products, product_prices)\n \ndef get_human_goals(all_products, product_prices):\n goals = []\n cnt_atts = defaultdict(int)\n cnt = 0\n for item in all_products:\n asin = item['asin']\n if 'instructions' not in item: continue\n for product in item['instructions']:\n attributes = product['instruction_attributes']\n if len(attributes) == 0: \n cnt += 1\n continue\n\n if product_prices is not None:\n price = product_prices[asin]\n price_range = [p for p in PRICE_RANGE if p > price][:4]\n if len(price_range) >= 2:\n _, price_upper = sorted(random.sample(price_range, 2))\n price_text = \\\n f', and price lower than {price_upper:.2f} dollars'\n else:\n price_upper = 1000000\n price_text = ''\n else:\n price_upper = 1000000\n\n goals.append({\n 'asin': asin,\n 'category': item['category'],\n 'query': item['query'],\n 'name': item['name'],\n 'product_category': item['product_category'],\n 'instruction_text': product['instruction'].strip('.') + price_text,\n 'attributes': attributes,\n 'price_upper': price_upper,\n 'goal_options': product['instruction_options'],\n })\n for att in attributes:\n cnt_atts[att] += 1\n # goals += product_goals\n for goal in goals:\n goal['weight'] = 1\n print(cnt, 'skipped')\n return goals\n\n\ndef get_synthetic_goals(all_products, product_prices):\n goals = []\n cnt_atts = defaultdict(int)\n for product in all_products:\n if ('instruction_text' not in product or \n product['instruction_text'] is None):\n continue\n product_goals = [] \n asin = product['asin']\n attributes = product['instruction_attributes']\n assert len(attributes) > 0\n\n if product_prices is not None:\n price = product_prices[asin]\n price_range = [p for p in PRICE_RANGE if p > price][:4]\n if len(price_range) >= 2:\n _, price_upper = sorted(random.sample(price_range, 2))\n price_text = \\\n f', and price lower than {price_upper:.2f} dollars'\n else:\n price_upper = 1000000\n price_text = ''\n else:\n price_upper = 1000000\n price_text = ''\n\n instruction_text = product['instruction_text']\n\n options = product['options']\n option_names = sorted(options)\n combinations = list(itertools.product(\n *(options[option_name] for option_name in option_names)\n ))\n for combination in combinations:\n goal_options = dict()\n for i, o in enumerate(combination):\n# option_text.append(f'{option_names[i]}: {o}')\n goal_options[option_names[i]] = o\n option_text = ', and '.join([\n f'{k}: {v}' for k, v in goal_options.items()\n ])\n option_text = ' with ' + option_text if option_text else ''\n product_goals.append({\n 'asin': asin,\n 'category': product['category'],\n 'query': product['query'],\n 'name': product['name'],\n 'product_category': product['product_category'],\n 'instruction_text': f'{instruction_text}{option_text}{price_text}',\n 'attributes': attributes,\n 'price_upper': price_upper,\n 'goal_options': goal_options,\n 'name': product['Title'],\n })\n for att in attributes:\n cnt_atts[att] += 1\n goals += product_goals\n for goal in goals:\n goal['weight'] = sum(1. / cnt_atts[att] for att in goal['attributes']) / len(goal['attributes'])\n return goals\n\n\ndef get_type_reward(purchased_product, goal):\n \"\"\"Determines the type reward - captures whether chosen product is in the same category\"\"\"\n query_match = purchased_product['query'] == goal['query']\n\n # Check number of unique categories that match, ignoring order\n purchased_product_category = [x.strip() for x in purchased_product['product_category'].split('›')]\n goal_product_category = [x.strip() for x in goal['product_category'].split('›')]\n category_match = len(set(purchased_product_category) & set(goal_product_category)) >= 2\n\n # Determine whether types align based on product name similarity\n purchased_type = purchased_product['name']\n desired_type = goal['name']\n\n purchased_type_parse = nlp(purchased_type)\n desired_type_parse = nlp(desired_type)\n\n purchased_type_parse = [t.text.lower() for t in purchased_type_parse if t.pos_ in ('PNOUN', 'NOUN', 'PROPN')]\n desired_type_parse = [t.text.lower() for t in desired_type_parse if t.pos_ in ('PNOUN', 'NOUN', 'PROPN')]\n\n n_intersect_type = len(\n set(purchased_type_parse) & set(desired_type_parse)\n )\n if len(desired_type_parse) == 0:\n title_score = 0.2\n else:\n title_score = n_intersect_type / len(desired_type_parse)\n\n r_type = 1.0\n\n # Adjust r_type score based on query, category title matching/scores\n match = query_match or category_match or title_score > 0.2\n if not match:\n r_type = 0.5\n\n if title_score < 0.1:\n r_type = 0.1\n \n if title_score == 0.0:\n r_type = 0.0\n\n return dict(\n r_type=r_type,\n query_match=query_match,\n category_match=category_match,\n title_score=title_score,\n )\n\n\ndef get_attribute_reward(purchased_product, goal):\n \"\"\"Determines whether purchased products shares same attributes as goal\"\"\"\n purchased_attrs = purchased_product['Attributes']\n goal_attrs = goal['attributes']\n\n num_attr_matches = 0\n for g_attr in goal_attrs:\n matched = False\n # Check whether goal attribute found in purchased product attribute list\n for p_attr in purchased_attrs:\n score = fuzz.token_set_ratio(p_attr, g_attr)\n if score > 85:\n num_attr_matches += 1\n matched = True\n break\n # If not in purchased attrs, check Title, Bullet Points (Features), Desc\n if (\n not matched and\n (\n g_attr in purchased_product['Title'].lower() or\n g_attr in ' '.join(purchased_product['BulletPoints']).lower() or\n g_attr in purchased_product['Description'].lower()\n )\n ):\n num_attr_matches += 1\n matched = True\n \n r_attr = num_attr_matches / len(goal_attrs)\n return r_attr, num_attr_matches\n\n\ndef get_option_reward(purchased_options, goal_options):\n \"\"\"Calculate reward for purchased product's options w.r.t. goal options\"\"\"\n purchased_options = [normalize_color(o) for o in purchased_options]\n goal_options = [normalize_color(o) for o in goal_options]\n\n # Perform fuzzy matching of each purchased option against each goal option\n num_option_matches = 0\n for g_option in goal_options:\n for p_option in purchased_options:\n score = fuzz.token_set_ratio(p_option, g_option)\n if score > 85:\n num_option_matches += 1\n break\n \n # Calculate option reward as fraction of goal options hit\n r_option = num_option_matches / len(goal_options) if len(goal_options) > 0 else None\n return r_option, num_option_matches\n\n\ndef get_reward(purchased_product, goal, price, options, **kwargs):\n \"\"\"Get cumulative reward score for purchased product and goal\"\"\"\n r_type_dict = get_type_reward(purchased_product, goal)\n\n r_price = (\n price <= goal['price_upper']\n ) if goal['price_upper'] > 0 else None\n\n r_att, num_attr_matches = get_attribute_reward(purchased_product, goal)\n\n r_option, num_option_matches = get_option_reward(\n list(options.values()),\n goal['goal_options'].items()\n if isinstance(goal['goal_options'], dict)\n else goal['goal_options']\n )\n\n total_reward = (\n (num_attr_matches + num_option_matches + r_price) \\\n / (len(goal['attributes']) + len(goal['goal_options']) + 1)\n )\n\n total_reward *= r_type_dict['r_type']\n\n # If verbose flag enabled, store score sub-components into dictionary\n if kwargs.get('verbose', False):\n info = {\n 'r_type': r_type_dict['r_type'],\n 'r_att': r_att,\n 'w_att': len(goal['attributes']) / (len(goal['attributes']) + len(goal['goal_options']) + 1),\n 'query_match': r_type_dict['query_match'],\n 'category_match': r_type_dict['category_match'],\n 'title_score': r_type_dict['title_score'],\n }\n if r_option is not None:\n info['r_option'] = r_option\n info['w_option'] = len(goal['goal_options']) / (len(goal['attributes']) + len(goal['goal_options']) + 1)\n if r_price is not None:\n info['r_price'] = r_price\n info['w_price'] = 1 / (len(goal['attributes']) + len(goal['goal_options']) + 1)\n return total_reward, info\n return total_reward","source_hash":"d6083dbff9e8b3957bef50cf56edd1f371bcd076ad8cf16fdd7eda09ee4fb87e","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.engine.goal.get_goals","uri":"program://BOLAA/function/webshop.web_agent_site.engine.goal.get_goals#L16-L20","kind":"function","name":"get_goals","path":"webshop/web_agent_site/engine/goal.py","language":"python","start_line":16,"end_line":20,"context_start_line":1,"context_end_line":40,"code":"\"\"\"\nFunctions for specifying goals and reward calculations.\n\"\"\"\nimport itertools\nimport random\nimport spacy\nfrom collections import defaultdict\nfrom rich import print\nfrom thefuzz import fuzz\nfrom web_agent_site.engine.normalize import normalize_color\n\nnlp = spacy.load(\"en_core_web_lg\")\n\nPRICE_RANGE = [10.0 * i for i in range(1, 100)]\n\ndef get_goals(all_products, product_prices, human_goals=True):\n if human_goals:\n return get_human_goals(all_products, product_prices)\n else:\n return get_synthetic_goals(all_products, product_prices)\n \ndef get_human_goals(all_products, product_prices):\n goals = []\n cnt_atts = defaultdict(int)\n cnt = 0\n for item in all_products:\n asin = item['asin']\n if 'instructions' not in item: continue\n for product in item['instructions']:\n attributes = product['instruction_attributes']\n if len(attributes) == 0: \n cnt += 1\n continue\n\n if product_prices is not None:\n price = product_prices[asin]\n price_range = [p for p in PRICE_RANGE if p > price][:4]\n if len(price_range) >= 2:\n _, price_upper = sorted(random.sample(price_range, 2))\n price_text = \\","source_hash":"d6083dbff9e8b3957bef50cf56edd1f371bcd076ad8cf16fdd7eda09ee4fb87e","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.engine.goal.get_human_goals","uri":"program://BOLAA/function/webshop.web_agent_site.engine.goal.get_human_goals#L22-L65","kind":"function","name":"get_human_goals","path":"webshop/web_agent_site/engine/goal.py","language":"python","start_line":22,"end_line":65,"context_start_line":2,"context_end_line":85,"code":"Functions for specifying goals and reward calculations.\n\"\"\"\nimport itertools\nimport random\nimport spacy\nfrom collections import defaultdict\nfrom rich import print\nfrom thefuzz import fuzz\nfrom web_agent_site.engine.normalize import normalize_color\n\nnlp = spacy.load(\"en_core_web_lg\")\n\nPRICE_RANGE = [10.0 * i for i in range(1, 100)]\n\ndef get_goals(all_products, product_prices, human_goals=True):\n if human_goals:\n return get_human_goals(all_products, product_prices)\n else:\n return get_synthetic_goals(all_products, product_prices)\n \ndef get_human_goals(all_products, product_prices):\n goals = []\n cnt_atts = defaultdict(int)\n cnt = 0\n for item in all_products:\n asin = item['asin']\n if 'instructions' not in item: continue\n for product in item['instructions']:\n attributes = product['instruction_attributes']\n if len(attributes) == 0: \n cnt += 1\n continue\n\n if product_prices is not None:\n price = product_prices[asin]\n price_range = [p for p in PRICE_RANGE if p > price][:4]\n if len(price_range) >= 2:\n _, price_upper = sorted(random.sample(price_range, 2))\n price_text = \\\n f', and price lower than {price_upper:.2f} dollars'\n else:\n price_upper = 1000000\n price_text = ''\n else:\n price_upper = 1000000\n\n goals.append({\n 'asin': asin,\n 'category': item['category'],\n 'query': item['query'],\n 'name': item['name'],\n 'product_category': item['product_category'],\n 'instruction_text': product['instruction'].strip('.') + price_text,\n 'attributes': attributes,\n 'price_upper': price_upper,\n 'goal_options': product['instruction_options'],\n })\n for att in attributes:\n cnt_atts[att] += 1\n # goals += product_goals\n for goal in goals:\n goal['weight'] = 1\n print(cnt, 'skipped')\n return goals\n\n\ndef get_synthetic_goals(all_products, product_prices):\n goals = []\n cnt_atts = defaultdict(int)\n for product in all_products:\n if ('instruction_text' not in product or \n product['instruction_text'] is None):\n continue\n product_goals = [] \n asin = product['asin']\n attributes = product['instruction_attributes']\n assert len(attributes) > 0\n\n if product_prices is not None:\n price = product_prices[asin]\n price_range = [p for p in PRICE_RANGE if p > price][:4]\n if len(price_range) >= 2:\n _, price_upper = sorted(random.sample(price_range, 2))\n price_text = \\","source_hash":"d6083dbff9e8b3957bef50cf56edd1f371bcd076ad8cf16fdd7eda09ee4fb87e","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.engine.goal.get_synthetic_goals","uri":"program://BOLAA/function/webshop.web_agent_site.engine.goal.get_synthetic_goals#L68-L127","kind":"function","name":"get_synthetic_goals","path":"webshop/web_agent_site/engine/goal.py","language":"python","start_line":68,"end_line":127,"context_start_line":48,"context_end_line":147,"code":" goals.append({\n 'asin': asin,\n 'category': item['category'],\n 'query': item['query'],\n 'name': item['name'],\n 'product_category': item['product_category'],\n 'instruction_text': product['instruction'].strip('.') + price_text,\n 'attributes': attributes,\n 'price_upper': price_upper,\n 'goal_options': product['instruction_options'],\n })\n for att in attributes:\n cnt_atts[att] += 1\n # goals += product_goals\n for goal in goals:\n goal['weight'] = 1\n print(cnt, 'skipped')\n return goals\n\n\ndef get_synthetic_goals(all_products, product_prices):\n goals = []\n cnt_atts = defaultdict(int)\n for product in all_products:\n if ('instruction_text' not in product or \n product['instruction_text'] is None):\n continue\n product_goals = [] \n asin = product['asin']\n attributes = product['instruction_attributes']\n assert len(attributes) > 0\n\n if product_prices is not None:\n price = product_prices[asin]\n price_range = [p for p in PRICE_RANGE if p > price][:4]\n if len(price_range) >= 2:\n _, price_upper = sorted(random.sample(price_range, 2))\n price_text = \\\n f', and price lower than {price_upper:.2f} dollars'\n else:\n price_upper = 1000000\n price_text = ''\n else:\n price_upper = 1000000\n price_text = ''\n\n instruction_text = product['instruction_text']\n\n options = product['options']\n option_names = sorted(options)\n combinations = list(itertools.product(\n *(options[option_name] for option_name in option_names)\n ))\n for combination in combinations:\n goal_options = dict()\n for i, o in enumerate(combination):\n# option_text.append(f'{option_names[i]}: {o}')\n goal_options[option_names[i]] = o\n option_text = ', and '.join([\n f'{k}: {v}' for k, v in goal_options.items()\n ])\n option_text = ' with ' + option_text if option_text else ''\n product_goals.append({\n 'asin': asin,\n 'category': product['category'],\n 'query': product['query'],\n 'name': product['name'],\n 'product_category': product['product_category'],\n 'instruction_text': f'{instruction_text}{option_text}{price_text}',\n 'attributes': attributes,\n 'price_upper': price_upper,\n 'goal_options': goal_options,\n 'name': product['Title'],\n })\n for att in attributes:\n cnt_atts[att] += 1\n goals += product_goals\n for goal in goals:\n goal['weight'] = sum(1. / cnt_atts[att] for att in goal['attributes']) / len(goal['attributes'])\n return goals\n\n\ndef get_type_reward(purchased_product, goal):\n \"\"\"Determines the type reward - captures whether chosen product is in the same category\"\"\"\n query_match = purchased_product['query'] == goal['query']\n\n # Check number of unique categories that match, ignoring order\n purchased_product_category = [x.strip() for x in purchased_product['product_category'].split('›')]\n goal_product_category = [x.strip() for x in goal['product_category'].split('›')]\n category_match = len(set(purchased_product_category) & set(goal_product_category)) >= 2\n\n # Determine whether types align based on product name similarity\n purchased_type = purchased_product['name']\n desired_type = goal['name']\n\n purchased_type_parse = nlp(purchased_type)\n desired_type_parse = nlp(desired_type)\n\n purchased_type_parse = [t.text.lower() for t in purchased_type_parse if t.pos_ in ('PNOUN', 'NOUN', 'PROPN')]\n desired_type_parse = [t.text.lower() for t in desired_type_parse if t.pos_ in ('PNOUN', 'NOUN', 'PROPN')]","source_hash":"d6083dbff9e8b3957bef50cf56edd1f371bcd076ad8cf16fdd7eda09ee4fb87e","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.engine.goal.get_type_reward","uri":"program://BOLAA/function/webshop.web_agent_site.engine.goal.get_type_reward#L130-L175","kind":"function","name":"get_type_reward","path":"webshop/web_agent_site/engine/goal.py","language":"python","start_line":130,"end_line":175,"context_start_line":110,"context_end_line":195,"code":" product_goals.append({\n 'asin': asin,\n 'category': product['category'],\n 'query': product['query'],\n 'name': product['name'],\n 'product_category': product['product_category'],\n 'instruction_text': f'{instruction_text}{option_text}{price_text}',\n 'attributes': attributes,\n 'price_upper': price_upper,\n 'goal_options': goal_options,\n 'name': product['Title'],\n })\n for att in attributes:\n cnt_atts[att] += 1\n goals += product_goals\n for goal in goals:\n goal['weight'] = sum(1. / cnt_atts[att] for att in goal['attributes']) / len(goal['attributes'])\n return goals\n\n\ndef get_type_reward(purchased_product, goal):\n \"\"\"Determines the type reward - captures whether chosen product is in the same category\"\"\"\n query_match = purchased_product['query'] == goal['query']\n\n # Check number of unique categories that match, ignoring order\n purchased_product_category = [x.strip() for x in purchased_product['product_category'].split('›')]\n goal_product_category = [x.strip() for x in goal['product_category'].split('›')]\n category_match = len(set(purchased_product_category) & set(goal_product_category)) >= 2\n\n # Determine whether types align based on product name similarity\n purchased_type = purchased_product['name']\n desired_type = goal['name']\n\n purchased_type_parse = nlp(purchased_type)\n desired_type_parse = nlp(desired_type)\n\n purchased_type_parse = [t.text.lower() for t in purchased_type_parse if t.pos_ in ('PNOUN', 'NOUN', 'PROPN')]\n desired_type_parse = [t.text.lower() for t in desired_type_parse if t.pos_ in ('PNOUN', 'NOUN', 'PROPN')]\n\n n_intersect_type = len(\n set(purchased_type_parse) & set(desired_type_parse)\n )\n if len(desired_type_parse) == 0:\n title_score = 0.2\n else:\n title_score = n_intersect_type / len(desired_type_parse)\n\n r_type = 1.0\n\n # Adjust r_type score based on query, category title matching/scores\n match = query_match or category_match or title_score > 0.2\n if not match:\n r_type = 0.5\n\n if title_score < 0.1:\n r_type = 0.1\n \n if title_score == 0.0:\n r_type = 0.0\n\n return dict(\n r_type=r_type,\n query_match=query_match,\n category_match=category_match,\n title_score=title_score,\n )\n\n\ndef get_attribute_reward(purchased_product, goal):\n \"\"\"Determines whether purchased products shares same attributes as goal\"\"\"\n purchased_attrs = purchased_product['Attributes']\n goal_attrs = goal['attributes']\n\n num_attr_matches = 0\n for g_attr in goal_attrs:\n matched = False\n # Check whether goal attribute found in purchased product attribute list\n for p_attr in purchased_attrs:\n score = fuzz.token_set_ratio(p_attr, g_attr)\n if score > 85:\n num_attr_matches += 1\n matched = True\n break\n # If not in purchased attrs, check Title, Bullet Points (Features), Desc\n if (\n not matched and","source_hash":"d6083dbff9e8b3957bef50cf56edd1f371bcd076ad8cf16fdd7eda09ee4fb87e","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.engine.goal.get_attribute_reward","uri":"program://BOLAA/function/webshop.web_agent_site.engine.goal.get_attribute_reward#L178-L206","kind":"function","name":"get_attribute_reward","path":"webshop/web_agent_site/engine/goal.py","language":"python","start_line":178,"end_line":206,"context_start_line":158,"context_end_line":226,"code":"\n # Adjust r_type score based on query, category title matching/scores\n match = query_match or category_match or title_score > 0.2\n if not match:\n r_type = 0.5\n\n if title_score < 0.1:\n r_type = 0.1\n \n if title_score == 0.0:\n r_type = 0.0\n\n return dict(\n r_type=r_type,\n query_match=query_match,\n category_match=category_match,\n title_score=title_score,\n )\n\n\ndef get_attribute_reward(purchased_product, goal):\n \"\"\"Determines whether purchased products shares same attributes as goal\"\"\"\n purchased_attrs = purchased_product['Attributes']\n goal_attrs = goal['attributes']\n\n num_attr_matches = 0\n for g_attr in goal_attrs:\n matched = False\n # Check whether goal attribute found in purchased product attribute list\n for p_attr in purchased_attrs:\n score = fuzz.token_set_ratio(p_attr, g_attr)\n if score > 85:\n num_attr_matches += 1\n matched = True\n break\n # If not in purchased attrs, check Title, Bullet Points (Features), Desc\n if (\n not matched and\n (\n g_attr in purchased_product['Title'].lower() or\n g_attr in ' '.join(purchased_product['BulletPoints']).lower() or\n g_attr in purchased_product['Description'].lower()\n )\n ):\n num_attr_matches += 1\n matched = True\n \n r_attr = num_attr_matches / len(goal_attrs)\n return r_attr, num_attr_matches\n\n\ndef get_option_reward(purchased_options, goal_options):\n \"\"\"Calculate reward for purchased product's options w.r.t. goal options\"\"\"\n purchased_options = [normalize_color(o) for o in purchased_options]\n goal_options = [normalize_color(o) for o in goal_options]\n\n # Perform fuzzy matching of each purchased option against each goal option\n num_option_matches = 0\n for g_option in goal_options:\n for p_option in purchased_options:\n score = fuzz.token_set_ratio(p_option, g_option)\n if score > 85:\n num_option_matches += 1\n break\n \n # Calculate option reward as fraction of goal options hit\n r_option = num_option_matches / len(goal_options) if len(goal_options) > 0 else None\n return r_option, num_option_matches\n","source_hash":"d6083dbff9e8b3957bef50cf56edd1f371bcd076ad8cf16fdd7eda09ee4fb87e","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.engine.goal.get_option_reward","uri":"program://BOLAA/function/webshop.web_agent_site.engine.goal.get_option_reward#L209-L225","kind":"function","name":"get_option_reward","path":"webshop/web_agent_site/engine/goal.py","language":"python","start_line":209,"end_line":225,"context_start_line":189,"context_end_line":245,"code":" if score > 85:\n num_attr_matches += 1\n matched = True\n break\n # If not in purchased attrs, check Title, Bullet Points (Features), Desc\n if (\n not matched and\n (\n g_attr in purchased_product['Title'].lower() or\n g_attr in ' '.join(purchased_product['BulletPoints']).lower() or\n g_attr in purchased_product['Description'].lower()\n )\n ):\n num_attr_matches += 1\n matched = True\n \n r_attr = num_attr_matches / len(goal_attrs)\n return r_attr, num_attr_matches\n\n\ndef get_option_reward(purchased_options, goal_options):\n \"\"\"Calculate reward for purchased product's options w.r.t. goal options\"\"\"\n purchased_options = [normalize_color(o) for o in purchased_options]\n goal_options = [normalize_color(o) for o in goal_options]\n\n # Perform fuzzy matching of each purchased option against each goal option\n num_option_matches = 0\n for g_option in goal_options:\n for p_option in purchased_options:\n score = fuzz.token_set_ratio(p_option, g_option)\n if score > 85:\n num_option_matches += 1\n break\n \n # Calculate option reward as fraction of goal options hit\n r_option = num_option_matches / len(goal_options) if len(goal_options) > 0 else None\n return r_option, num_option_matches\n\n\ndef get_reward(purchased_product, goal, price, options, **kwargs):\n \"\"\"Get cumulative reward score for purchased product and goal\"\"\"\n r_type_dict = get_type_reward(purchased_product, goal)\n\n r_price = (\n price <= goal['price_upper']\n ) if goal['price_upper'] > 0 else None\n\n r_att, num_attr_matches = get_attribute_reward(purchased_product, goal)\n\n r_option, num_option_matches = get_option_reward(\n list(options.values()),\n goal['goal_options'].items()\n if isinstance(goal['goal_options'], dict)\n else goal['goal_options']\n )\n\n total_reward = (","source_hash":"d6083dbff9e8b3957bef50cf56edd1f371bcd076ad8cf16fdd7eda09ee4fb87e","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.engine.goal.get_reward","uri":"program://BOLAA/function/webshop.web_agent_site.engine.goal.get_reward#L228-L269","kind":"function","name":"get_reward","path":"webshop/web_agent_site/engine/goal.py","language":"python","start_line":228,"end_line":269,"context_start_line":208,"context_end_line":269,"code":"\ndef get_option_reward(purchased_options, goal_options):\n \"\"\"Calculate reward for purchased product's options w.r.t. goal options\"\"\"\n purchased_options = [normalize_color(o) for o in purchased_options]\n goal_options = [normalize_color(o) for o in goal_options]\n\n # Perform fuzzy matching of each purchased option against each goal option\n num_option_matches = 0\n for g_option in goal_options:\n for p_option in purchased_options:\n score = fuzz.token_set_ratio(p_option, g_option)\n if score > 85:\n num_option_matches += 1\n break\n \n # Calculate option reward as fraction of goal options hit\n r_option = num_option_matches / len(goal_options) if len(goal_options) > 0 else None\n return r_option, num_option_matches\n\n\ndef get_reward(purchased_product, goal, price, options, **kwargs):\n \"\"\"Get cumulative reward score for purchased product and goal\"\"\"\n r_type_dict = get_type_reward(purchased_product, goal)\n\n r_price = (\n price <= goal['price_upper']\n ) if goal['price_upper'] > 0 else None\n\n r_att, num_attr_matches = get_attribute_reward(purchased_product, goal)\n\n r_option, num_option_matches = get_option_reward(\n list(options.values()),\n goal['goal_options'].items()\n if isinstance(goal['goal_options'], dict)\n else goal['goal_options']\n )\n\n total_reward = (\n (num_attr_matches + num_option_matches + r_price) \\\n / (len(goal['attributes']) + len(goal['goal_options']) + 1)\n )\n\n total_reward *= r_type_dict['r_type']\n\n # If verbose flag enabled, store score sub-components into dictionary\n if kwargs.get('verbose', False):\n info = {\n 'r_type': r_type_dict['r_type'],\n 'r_att': r_att,\n 'w_att': len(goal['attributes']) / (len(goal['attributes']) + len(goal['goal_options']) + 1),\n 'query_match': r_type_dict['query_match'],\n 'category_match': r_type_dict['category_match'],\n 'title_score': r_type_dict['title_score'],\n }\n if r_option is not None:\n info['r_option'] = r_option\n info['w_option'] = len(goal['goal_options']) / (len(goal['attributes']) + len(goal['goal_options']) + 1)\n if r_price is not None:\n info['r_price'] = r_price\n info['w_price'] = 1 / (len(goal['attributes']) + len(goal['goal_options']) + 1)\n return total_reward, info\n return total_reward","source_hash":"d6083dbff9e8b3957bef50cf56edd1f371bcd076ad8cf16fdd7eda09ee4fb87e","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.engine.engine","uri":"program://BOLAA/module/webshop.web_agent_site.engine.engine#L1-L362","kind":"module","name":"webshop.web_agent_site.engine.engine","path":"webshop/web_agent_site/engine/engine.py","language":"python","start_line":1,"end_line":362,"context_start_line":1,"context_end_line":362,"code":"\"\"\"\n\"\"\"\nimport os\nimport re\nimport json\nimport random\nfrom collections import defaultdict\nfrom ast import literal_eval\nfrom decimal import Decimal\n\nimport cleantext\nfrom tqdm import tqdm\nfrom rank_bm25 import BM25Okapi\nfrom flask import render_template_string\nfrom rich import print\nfrom pyserini.search.lucene import LuceneSearcher\n\nfrom web_agent_site.utils import (\n BASE_DIR,\n DEFAULT_FILE_PATH,\n DEFAULT_REVIEW_PATH,\n DEFAULT_ATTR_PATH,\n HUMAN_ATTR_PATH\n)\n\nTEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')\n\nSEARCH_RETURN_N = 50\nPRODUCT_WINDOW = 10\nTOP_K_ATTR = 10\n\nEND_BUTTON = 'Buy Now'\nNEXT_PAGE = 'Next >'\nPREV_PAGE = '< Prev'\nBACK_TO_SEARCH = 'Back to Search'\n\nACTION_TO_TEMPLATE = {\n 'Description': 'description_page.html',\n 'Features': 'features_page.html',\n 'Reviews': 'review_page.html',\n 'Attributes': 'attributes_page.html',\n}\n\ndef map_action_to_html(action, **kwargs):\n action_name, action_arg = parse_action(action)\n if action_name == 'start':\n path = os.path.join(TEMPLATE_DIR, 'search_page.html')\n html = render_template_string(\n read_html_template(path=path),\n session_id=kwargs['session_id'],\n instruction_text=kwargs['instruction_text'],\n )\n elif action_name == 'search':\n path = os.path.join(TEMPLATE_DIR, 'results_page.html')\n html = render_template_string(\n read_html_template(path=path),\n session_id=kwargs['session_id'],\n products=kwargs['products'],\n keywords=kwargs['keywords'],\n page=kwargs['page'],\n total=kwargs['total'],\n instruction_text=kwargs['instruction_text'],\n )\n elif action_name == 'click' and action_arg == END_BUTTON:\n path = os.path.join(TEMPLATE_DIR, 'done_page.html')\n html = render_template_string(\n read_html_template(path),\n session_id=kwargs['session_id'],\n reward=kwargs['reward'],\n asin=kwargs['asin'],\n options=kwargs['options'],\n reward_info=kwargs.get('reward_info'),\n goal_attrs=kwargs.get('goal_attrs'),\n purchased_attrs=kwargs.get('purchased_attrs'),\n goal=kwargs.get('goal'),\n mturk_code=kwargs.get('mturk_code'),\n query=kwargs.get('query'),\n category=kwargs.get('category'),\n product_category=kwargs.get('product_category'),\n )\n elif action_name == 'click' and action_arg in ACTION_TO_TEMPLATE:\n path = os.path.join(TEMPLATE_DIR, ACTION_TO_TEMPLATE[action_arg])\n html = render_template_string(\n read_html_template(path),\n session_id=kwargs['session_id'],\n product_info=kwargs['product_info'],\n keywords=kwargs['keywords'],\n page=kwargs['page'],\n asin=kwargs['asin'],\n options=kwargs['options'],\n instruction_text=kwargs.get('instruction_text')\n )\n elif action_name == 'click':\n path = os.path.join(TEMPLATE_DIR, 'item_page.html')\n html = render_template_string(\n read_html_template(path),\n session_id=kwargs['session_id'],\n product_info=kwargs['product_info'],\n keywords=kwargs['keywords'],\n page=kwargs['page'],\n asin=kwargs['asin'],\n options=kwargs['options'],\n instruction_text=kwargs.get('instruction_text'),\n show_attrs=kwargs['show_attrs']\n )\n else:\n raise ValueError('Action name not recognized.')\n return html\n\n\ndef read_html_template(path):\n with open(path) as f:\n template = f.read()\n return template\n\n\ndef parse_action(action):\n \"\"\"\n Parse action string to action name and its arguments.\n \"\"\"\n pattern = re.compile(r'(.+)\\[(.+)\\]')\n m = re.match(pattern, action)\n if m is None:\n action_name = action\n action_arg = None\n else:\n action_name, action_arg = m.groups()\n return action_name, action_arg\n\n\ndef convert_web_app_string_to_var(name, string):\n if name == 'keywords':\n keywords = string\n if keywords.startswith('['):\n keywords = literal_eval(keywords)\n else:\n keywords = [keywords]\n var = keywords\n elif name == 'page':\n page = string\n page = int(page)\n var = page\n else:\n raise ValueError('Name of variable not recognized.')\n return var\n\n\ndef get_top_n_product_from_keywords(\n keywords,\n search_engine,\n all_products,\n product_item_dict,\n attribute_to_asins=None,\n ):\n if keywords[0] == '':\n top_n_products = random.sample(all_products, k=SEARCH_RETURN_N)\n elif keywords[0] == '':\n attribute = ' '.join(keywords[1:]).strip()\n asins = attribute_to_asins[attribute]\n top_n_products = [p for p in all_products if p['asin'] in asins]\n elif keywords[0] == '':\n category = keywords[1].strip()\n top_n_products = [p for p in all_products if p['category'] == category]\n elif keywords[0] == '':\n query = ' '.join(keywords[1:]).strip()\n top_n_products = [p for p in all_products if p['query'] == query]\n else:\n keywords = ' '.join(keywords)\n hits = search_engine.search(keywords, k=SEARCH_RETURN_N)\n docs = [search_engine.doc(hit.docid) for hit in hits]\n top_n_asins = [json.loads(doc.raw())['id'] for doc in docs]\n top_n_products = [product_item_dict[asin] for asin in top_n_asins if asin in product_item_dict]\n return top_n_products\n\n\ndef get_product_per_page(top_n_products, page):\n return top_n_products[(page - 1) * PRODUCT_WINDOW:page * PRODUCT_WINDOW]\n\n\ndef generate_product_prices(all_products):\n product_prices = dict()\n for product in all_products:\n asin = product['asin']\n pricing = product['pricing']\n if not pricing:\n price = 100.0\n elif len(pricing) == 1:\n price = pricing[0]\n else:\n price = random.uniform(*pricing[:2])\n product_prices[asin] = price\n return product_prices\n\n\ndef init_search_engine(num_products=None):\n if num_products == 100:\n indexes = 'indexes_100'\n elif num_products == 1000:\n indexes = 'indexes_1k'\n elif num_products == 100000:\n indexes = 'indexes_100k'\n elif num_products is None:\n indexes = 'indexes'\n else:\n raise NotImplementedError(f'num_products being {num_products} is not supported yet.')\n search_engine = LuceneSearcher(os.path.join(BASE_DIR, f'../search_engine/{indexes}'))\n return search_engine\n\n\ndef clean_product_keys(products):\n for product in products:\n product.pop('product_information', None)\n product.pop('brand', None)\n product.pop('brand_url', None)\n product.pop('list_price', None)\n product.pop('availability_quantity', None)\n product.pop('availability_status', None)\n product.pop('total_reviews', None)\n product.pop('total_answered_questions', None)\n product.pop('seller_id', None)\n product.pop('seller_name', None)\n product.pop('fulfilled_by_amazon', None)\n product.pop('fast_track_message', None)\n product.pop('aplus_present', None)\n product.pop('small_description_old', None)\n print('Keys cleaned.')\n return products\n\n\ndef load_products(filepath, num_products=None, human_goals=True):\n # TODO: move to preprocessing step -> enforce single source of truth\n with open(filepath) as f:\n products = json.load(f)\n print('Products loaded.')\n products = clean_product_keys(products)\n \n # with open(DEFAULT_REVIEW_PATH) as f:\n # reviews = json.load(f)\n all_reviews = dict()\n all_ratings = dict()\n # for r in reviews:\n # all_reviews[r['asin']] = r['reviews']\n # all_ratings[r['asin']] = r['average_rating']\n\n if human_goals:\n with open(HUMAN_ATTR_PATH) as f:\n human_attributes = json.load(f)\n with open(DEFAULT_ATTR_PATH) as f:\n attributes = json.load(f)\n with open(HUMAN_ATTR_PATH) as f:\n human_attributes = json.load(f)\n print('Attributes loaded.')\n\n asins = set()\n all_products = []\n attribute_to_asins = defaultdict(set)\n if num_products is not None:\n # using item_shuffle.json, we assume products already shuffled\n products = products[:num_products]\n for i, p in tqdm(enumerate(products), total=len(products)):\n asin = p['asin']\n if asin == 'nan' or len(asin) > 10:\n continue\n\n if asin in asins:\n continue\n else:\n asins.add(asin)\n\n products[i]['category'] = p['category']\n products[i]['query'] = p['query']\n products[i]['product_category'] = p['product_category']\n\n products[i]['Title'] = p['name']\n products[i]['Description'] = p['full_description']\n products[i]['Reviews'] = all_reviews.get(asin, [])\n products[i]['Rating'] = all_ratings.get(asin, 'N.A.')\n for r in products[i]['Reviews']:\n if 'score' not in r:\n r['score'] = r.pop('stars')\n if 'review' not in r:\n r['body'] = ''\n else:\n r['body'] = r.pop('review')\n products[i]['BulletPoints'] = p['small_description'] \\\n if isinstance(p['small_description'], list) else [p['small_description']]\n\n pricing = p.get('pricing')\n if pricing is None or not pricing:\n pricing = [100.0]\n price_tag = '$100.0'\n else:\n pricing = [\n float(Decimal(re.sub(r'[^\\d.]', '', price)))\n for price in pricing.split('$')[1:]\n ]\n if len(pricing) == 1:\n price_tag = f\"${pricing[0]}\"\n else:\n price_tag = f\"${pricing[0]} to ${pricing[1]}\"\n pricing = pricing[:2]\n products[i]['pricing'] = pricing\n products[i]['Price'] = price_tag\n\n options = dict()\n customization_options = p['customization_options']\n option_to_image = dict()\n if customization_options:\n for option_name, option_contents in customization_options.items():\n if option_contents is None:\n continue\n option_name = option_name.lower()\n\n option_values = []\n for option_content in option_contents:\n option_value = option_content['value'].strip().replace('/', ' | ').lower()\n option_image = option_content.get('image', None)\n\n option_values.append(option_value)\n option_to_image[option_value] = option_image\n options[option_name] = option_values\n products[i]['options'] = options\n products[i]['option_to_image'] = option_to_image\n\n # without color, size, price, availability\n # if asin in attributes and 'attributes' in attributes[asin]:\n # products[i]['Attributes'] = attributes[asin]['attributes']\n # else:\n # products[i]['Attributes'] = ['DUMMY_ATTR']\n # products[i]['instruction_text'] = \\\n # attributes[asin].get('instruction', None)\n # products[i]['instruction_attributes'] = \\\n # attributes[asin].get('instruction_attributes', None)\n\n # without color, size, price, availability\n if asin in attributes and 'attributes' in attributes[asin]:\n products[i]['Attributes'] = attributes[asin]['attributes']\n else:\n products[i]['Attributes'] = ['DUMMY_ATTR']\n \n if human_goals:\n if asin in human_attributes:\n products[i]['instructions'] = human_attributes[asin]\n else:\n products[i]['instruction_text'] = \\\n attributes[asin].get('instruction', None)\n\n products[i]['instruction_attributes'] = \\\n attributes[asin].get('instruction_attributes', None)\n\n products[i]['MainImage'] = p['images'][0]\n products[i]['query'] = p['query'].lower().strip()\n\n all_products.append(products[i])\n\n for p in all_products:\n for a in p['Attributes']:\n attribute_to_asins[a].add(p['asin'])\n\n product_item_dict = {p['asin']: p for p in all_products}\n product_prices = generate_product_prices(all_products)\n return all_products, product_item_dict, product_prices, attribute_to_asins","source_hash":"9b86ffc82951124f5c4a7eb8103de14100dbee11ba8869951ed6fb8feaeef804","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.engine.engine.map_action_to_html","uri":"program://BOLAA/function/webshop.web_agent_site.engine.engine.map_action_to_html#L44-L108","kind":"function","name":"map_action_to_html","path":"webshop/web_agent_site/engine/engine.py","language":"python","start_line":44,"end_line":108,"context_start_line":24,"context_end_line":128,"code":")\n\nTEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')\n\nSEARCH_RETURN_N = 50\nPRODUCT_WINDOW = 10\nTOP_K_ATTR = 10\n\nEND_BUTTON = 'Buy Now'\nNEXT_PAGE = 'Next >'\nPREV_PAGE = '< Prev'\nBACK_TO_SEARCH = 'Back to Search'\n\nACTION_TO_TEMPLATE = {\n 'Description': 'description_page.html',\n 'Features': 'features_page.html',\n 'Reviews': 'review_page.html',\n 'Attributes': 'attributes_page.html',\n}\n\ndef map_action_to_html(action, **kwargs):\n action_name, action_arg = parse_action(action)\n if action_name == 'start':\n path = os.path.join(TEMPLATE_DIR, 'search_page.html')\n html = render_template_string(\n read_html_template(path=path),\n session_id=kwargs['session_id'],\n instruction_text=kwargs['instruction_text'],\n )\n elif action_name == 'search':\n path = os.path.join(TEMPLATE_DIR, 'results_page.html')\n html = render_template_string(\n read_html_template(path=path),\n session_id=kwargs['session_id'],\n products=kwargs['products'],\n keywords=kwargs['keywords'],\n page=kwargs['page'],\n total=kwargs['total'],\n instruction_text=kwargs['instruction_text'],\n )\n elif action_name == 'click' and action_arg == END_BUTTON:\n path = os.path.join(TEMPLATE_DIR, 'done_page.html')\n html = render_template_string(\n read_html_template(path),\n session_id=kwargs['session_id'],\n reward=kwargs['reward'],\n asin=kwargs['asin'],\n options=kwargs['options'],\n reward_info=kwargs.get('reward_info'),\n goal_attrs=kwargs.get('goal_attrs'),\n purchased_attrs=kwargs.get('purchased_attrs'),\n goal=kwargs.get('goal'),\n mturk_code=kwargs.get('mturk_code'),\n query=kwargs.get('query'),\n category=kwargs.get('category'),\n product_category=kwargs.get('product_category'),\n )\n elif action_name == 'click' and action_arg in ACTION_TO_TEMPLATE:\n path = os.path.join(TEMPLATE_DIR, ACTION_TO_TEMPLATE[action_arg])\n html = render_template_string(\n read_html_template(path),\n session_id=kwargs['session_id'],\n product_info=kwargs['product_info'],\n keywords=kwargs['keywords'],\n page=kwargs['page'],\n asin=kwargs['asin'],\n options=kwargs['options'],\n instruction_text=kwargs.get('instruction_text')\n )\n elif action_name == 'click':\n path = os.path.join(TEMPLATE_DIR, 'item_page.html')\n html = render_template_string(\n read_html_template(path),\n session_id=kwargs['session_id'],\n product_info=kwargs['product_info'],\n keywords=kwargs['keywords'],\n page=kwargs['page'],\n asin=kwargs['asin'],\n options=kwargs['options'],\n instruction_text=kwargs.get('instruction_text'),\n show_attrs=kwargs['show_attrs']\n )\n else:\n raise ValueError('Action name not recognized.')\n return html\n\n\ndef read_html_template(path):\n with open(path) as f:\n template = f.read()\n return template\n\n\ndef parse_action(action):\n \"\"\"\n Parse action string to action name and its arguments.\n \"\"\"\n pattern = re.compile(r'(.+)\\[(.+)\\]')\n m = re.match(pattern, action)\n if m is None:\n action_name = action\n action_arg = None\n else:\n action_name, action_arg = m.groups()\n return action_name, action_arg","source_hash":"9b86ffc82951124f5c4a7eb8103de14100dbee11ba8869951ed6fb8feaeef804","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.engine.engine.read_html_template","uri":"program://BOLAA/function/webshop.web_agent_site.engine.engine.read_html_template#L111-L114","kind":"function","name":"read_html_template","path":"webshop/web_agent_site/engine/engine.py","language":"python","start_line":111,"end_line":114,"context_start_line":91,"context_end_line":134,"code":" instruction_text=kwargs.get('instruction_text')\n )\n elif action_name == 'click':\n path = os.path.join(TEMPLATE_DIR, 'item_page.html')\n html = render_template_string(\n read_html_template(path),\n session_id=kwargs['session_id'],\n product_info=kwargs['product_info'],\n keywords=kwargs['keywords'],\n page=kwargs['page'],\n asin=kwargs['asin'],\n options=kwargs['options'],\n instruction_text=kwargs.get('instruction_text'),\n show_attrs=kwargs['show_attrs']\n )\n else:\n raise ValueError('Action name not recognized.')\n return html\n\n\ndef read_html_template(path):\n with open(path) as f:\n template = f.read()\n return template\n\n\ndef parse_action(action):\n \"\"\"\n Parse action string to action name and its arguments.\n \"\"\"\n pattern = re.compile(r'(.+)\\[(.+)\\]')\n m = re.match(pattern, action)\n if m is None:\n action_name = action\n action_arg = None\n else:\n action_name, action_arg = m.groups()\n return action_name, action_arg\n\n\ndef convert_web_app_string_to_var(name, string):\n if name == 'keywords':\n keywords = string\n if keywords.startswith('['):","source_hash":"9b86ffc82951124f5c4a7eb8103de14100dbee11ba8869951ed6fb8feaeef804","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.engine.engine.parse_action","uri":"program://BOLAA/function/webshop.web_agent_site.engine.engine.parse_action#L117-L128","kind":"function","name":"parse_action","path":"webshop/web_agent_site/engine/engine.py","language":"python","start_line":117,"end_line":128,"context_start_line":97,"context_end_line":148,"code":" session_id=kwargs['session_id'],\n product_info=kwargs['product_info'],\n keywords=kwargs['keywords'],\n page=kwargs['page'],\n asin=kwargs['asin'],\n options=kwargs['options'],\n instruction_text=kwargs.get('instruction_text'),\n show_attrs=kwargs['show_attrs']\n )\n else:\n raise ValueError('Action name not recognized.')\n return html\n\n\ndef read_html_template(path):\n with open(path) as f:\n template = f.read()\n return template\n\n\ndef parse_action(action):\n \"\"\"\n Parse action string to action name and its arguments.\n \"\"\"\n pattern = re.compile(r'(.+)\\[(.+)\\]')\n m = re.match(pattern, action)\n if m is None:\n action_name = action\n action_arg = None\n else:\n action_name, action_arg = m.groups()\n return action_name, action_arg\n\n\ndef convert_web_app_string_to_var(name, string):\n if name == 'keywords':\n keywords = string\n if keywords.startswith('['):\n keywords = literal_eval(keywords)\n else:\n keywords = [keywords]\n var = keywords\n elif name == 'page':\n page = string\n page = int(page)\n var = page\n else:\n raise ValueError('Name of variable not recognized.')\n return var\n\n\ndef get_top_n_product_from_keywords(","source_hash":"9b86ffc82951124f5c4a7eb8103de14100dbee11ba8869951ed6fb8feaeef804","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.engine.engine.convert_web_app_string_to_var","uri":"program://BOLAA/function/webshop.web_agent_site.engine.engine.convert_web_app_string_to_var#L131-L145","kind":"function","name":"convert_web_app_string_to_var","path":"webshop/web_agent_site/engine/engine.py","language":"python","start_line":131,"end_line":145,"context_start_line":111,"context_end_line":165,"code":"def read_html_template(path):\n with open(path) as f:\n template = f.read()\n return template\n\n\ndef parse_action(action):\n \"\"\"\n Parse action string to action name and its arguments.\n \"\"\"\n pattern = re.compile(r'(.+)\\[(.+)\\]')\n m = re.match(pattern, action)\n if m is None:\n action_name = action\n action_arg = None\n else:\n action_name, action_arg = m.groups()\n return action_name, action_arg\n\n\ndef convert_web_app_string_to_var(name, string):\n if name == 'keywords':\n keywords = string\n if keywords.startswith('['):\n keywords = literal_eval(keywords)\n else:\n keywords = [keywords]\n var = keywords\n elif name == 'page':\n page = string\n page = int(page)\n var = page\n else:\n raise ValueError('Name of variable not recognized.')\n return var\n\n\ndef get_top_n_product_from_keywords(\n keywords,\n search_engine,\n all_products,\n product_item_dict,\n attribute_to_asins=None,\n ):\n if keywords[0] == '':\n top_n_products = random.sample(all_products, k=SEARCH_RETURN_N)\n elif keywords[0] == '':\n attribute = ' '.join(keywords[1:]).strip()\n asins = attribute_to_asins[attribute]\n top_n_products = [p for p in all_products if p['asin'] in asins]\n elif keywords[0] == '':\n category = keywords[1].strip()\n top_n_products = [p for p in all_products if p['category'] == category]\n elif keywords[0] == '':\n query = ' '.join(keywords[1:]).strip()","source_hash":"9b86ffc82951124f5c4a7eb8103de14100dbee11ba8869951ed6fb8feaeef804","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.engine.engine.get_top_n_product_from_keywords","uri":"program://BOLAA/function/webshop.web_agent_site.engine.engine.get_top_n_product_from_keywords#L148-L173","kind":"function","name":"get_top_n_product_from_keywords","path":"webshop/web_agent_site/engine/engine.py","language":"python","start_line":148,"end_line":173,"context_start_line":128,"context_end_line":193,"code":" return action_name, action_arg\n\n\ndef convert_web_app_string_to_var(name, string):\n if name == 'keywords':\n keywords = string\n if keywords.startswith('['):\n keywords = literal_eval(keywords)\n else:\n keywords = [keywords]\n var = keywords\n elif name == 'page':\n page = string\n page = int(page)\n var = page\n else:\n raise ValueError('Name of variable not recognized.')\n return var\n\n\ndef get_top_n_product_from_keywords(\n keywords,\n search_engine,\n all_products,\n product_item_dict,\n attribute_to_asins=None,\n ):\n if keywords[0] == '':\n top_n_products = random.sample(all_products, k=SEARCH_RETURN_N)\n elif keywords[0] == '':\n attribute = ' '.join(keywords[1:]).strip()\n asins = attribute_to_asins[attribute]\n top_n_products = [p for p in all_products if p['asin'] in asins]\n elif keywords[0] == '':\n category = keywords[1].strip()\n top_n_products = [p for p in all_products if p['category'] == category]\n elif keywords[0] == '':\n query = ' '.join(keywords[1:]).strip()\n top_n_products = [p for p in all_products if p['query'] == query]\n else:\n keywords = ' '.join(keywords)\n hits = search_engine.search(keywords, k=SEARCH_RETURN_N)\n docs = [search_engine.doc(hit.docid) for hit in hits]\n top_n_asins = [json.loads(doc.raw())['id'] for doc in docs]\n top_n_products = [product_item_dict[asin] for asin in top_n_asins if asin in product_item_dict]\n return top_n_products\n\n\ndef get_product_per_page(top_n_products, page):\n return top_n_products[(page - 1) * PRODUCT_WINDOW:page * PRODUCT_WINDOW]\n\n\ndef generate_product_prices(all_products):\n product_prices = dict()\n for product in all_products:\n asin = product['asin']\n pricing = product['pricing']\n if not pricing:\n price = 100.0\n elif len(pricing) == 1:\n price = pricing[0]\n else:\n price = random.uniform(*pricing[:2])\n product_prices[asin] = price\n return product_prices\n","source_hash":"9b86ffc82951124f5c4a7eb8103de14100dbee11ba8869951ed6fb8feaeef804","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.engine.engine.get_product_per_page","uri":"program://BOLAA/function/webshop.web_agent_site.engine.engine.get_product_per_page#L176-L177","kind":"function","name":"get_product_per_page","path":"webshop/web_agent_site/engine/engine.py","language":"python","start_line":176,"end_line":177,"context_start_line":156,"context_end_line":197,"code":" top_n_products = random.sample(all_products, k=SEARCH_RETURN_N)\n elif keywords[0] == '':\n attribute = ' '.join(keywords[1:]).strip()\n asins = attribute_to_asins[attribute]\n top_n_products = [p for p in all_products if p['asin'] in asins]\n elif keywords[0] == '':\n category = keywords[1].strip()\n top_n_products = [p for p in all_products if p['category'] == category]\n elif keywords[0] == '':\n query = ' '.join(keywords[1:]).strip()\n top_n_products = [p for p in all_products if p['query'] == query]\n else:\n keywords = ' '.join(keywords)\n hits = search_engine.search(keywords, k=SEARCH_RETURN_N)\n docs = [search_engine.doc(hit.docid) for hit in hits]\n top_n_asins = [json.loads(doc.raw())['id'] for doc in docs]\n top_n_products = [product_item_dict[asin] for asin in top_n_asins if asin in product_item_dict]\n return top_n_products\n\n\ndef get_product_per_page(top_n_products, page):\n return top_n_products[(page - 1) * PRODUCT_WINDOW:page * PRODUCT_WINDOW]\n\n\ndef generate_product_prices(all_products):\n product_prices = dict()\n for product in all_products:\n asin = product['asin']\n pricing = product['pricing']\n if not pricing:\n price = 100.0\n elif len(pricing) == 1:\n price = pricing[0]\n else:\n price = random.uniform(*pricing[:2])\n product_prices[asin] = price\n return product_prices\n\n\ndef init_search_engine(num_products=None):\n if num_products == 100:\n indexes = 'indexes_100'","source_hash":"9b86ffc82951124f5c4a7eb8103de14100dbee11ba8869951ed6fb8feaeef804","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.engine.engine.generate_product_prices","uri":"program://BOLAA/function/webshop.web_agent_site.engine.engine.generate_product_prices#L180-L192","kind":"function","name":"generate_product_prices","path":"webshop/web_agent_site/engine/engine.py","language":"python","start_line":180,"end_line":192,"context_start_line":160,"context_end_line":212,"code":" top_n_products = [p for p in all_products if p['asin'] in asins]\n elif keywords[0] == '':\n category = keywords[1].strip()\n top_n_products = [p for p in all_products if p['category'] == category]\n elif keywords[0] == '':\n query = ' '.join(keywords[1:]).strip()\n top_n_products = [p for p in all_products if p['query'] == query]\n else:\n keywords = ' '.join(keywords)\n hits = search_engine.search(keywords, k=SEARCH_RETURN_N)\n docs = [search_engine.doc(hit.docid) for hit in hits]\n top_n_asins = [json.loads(doc.raw())['id'] for doc in docs]\n top_n_products = [product_item_dict[asin] for asin in top_n_asins if asin in product_item_dict]\n return top_n_products\n\n\ndef get_product_per_page(top_n_products, page):\n return top_n_products[(page - 1) * PRODUCT_WINDOW:page * PRODUCT_WINDOW]\n\n\ndef generate_product_prices(all_products):\n product_prices = dict()\n for product in all_products:\n asin = product['asin']\n pricing = product['pricing']\n if not pricing:\n price = 100.0\n elif len(pricing) == 1:\n price = pricing[0]\n else:\n price = random.uniform(*pricing[:2])\n product_prices[asin] = price\n return product_prices\n\n\ndef init_search_engine(num_products=None):\n if num_products == 100:\n indexes = 'indexes_100'\n elif num_products == 1000:\n indexes = 'indexes_1k'\n elif num_products == 100000:\n indexes = 'indexes_100k'\n elif num_products is None:\n indexes = 'indexes'\n else:\n raise NotImplementedError(f'num_products being {num_products} is not supported yet.')\n search_engine = LuceneSearcher(os.path.join(BASE_DIR, f'../search_engine/{indexes}'))\n return search_engine\n\n\ndef clean_product_keys(products):\n for product in products:\n product.pop('product_information', None)","source_hash":"9b86ffc82951124f5c4a7eb8103de14100dbee11ba8869951ed6fb8feaeef804","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.engine.engine.init_search_engine","uri":"program://BOLAA/function/webshop.web_agent_site.engine.engine.init_search_engine#L195-L207","kind":"function","name":"init_search_engine","path":"webshop/web_agent_site/engine/engine.py","language":"python","start_line":195,"end_line":207,"context_start_line":175,"context_end_line":227,"code":"\ndef get_product_per_page(top_n_products, page):\n return top_n_products[(page - 1) * PRODUCT_WINDOW:page * PRODUCT_WINDOW]\n\n\ndef generate_product_prices(all_products):\n product_prices = dict()\n for product in all_products:\n asin = product['asin']\n pricing = product['pricing']\n if not pricing:\n price = 100.0\n elif len(pricing) == 1:\n price = pricing[0]\n else:\n price = random.uniform(*pricing[:2])\n product_prices[asin] = price\n return product_prices\n\n\ndef init_search_engine(num_products=None):\n if num_products == 100:\n indexes = 'indexes_100'\n elif num_products == 1000:\n indexes = 'indexes_1k'\n elif num_products == 100000:\n indexes = 'indexes_100k'\n elif num_products is None:\n indexes = 'indexes'\n else:\n raise NotImplementedError(f'num_products being {num_products} is not supported yet.')\n search_engine = LuceneSearcher(os.path.join(BASE_DIR, f'../search_engine/{indexes}'))\n return search_engine\n\n\ndef clean_product_keys(products):\n for product in products:\n product.pop('product_information', None)\n product.pop('brand', None)\n product.pop('brand_url', None)\n product.pop('list_price', None)\n product.pop('availability_quantity', None)\n product.pop('availability_status', None)\n product.pop('total_reviews', None)\n product.pop('total_answered_questions', None)\n product.pop('seller_id', None)\n product.pop('seller_name', None)\n product.pop('fulfilled_by_amazon', None)\n product.pop('fast_track_message', None)\n product.pop('aplus_present', None)\n product.pop('small_description_old', None)\n print('Keys cleaned.')\n return products","source_hash":"9b86ffc82951124f5c4a7eb8103de14100dbee11ba8869951ed6fb8feaeef804","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.engine.engine.clean_product_keys","uri":"program://BOLAA/function/webshop.web_agent_site.engine.engine.clean_product_keys#L210-L227","kind":"function","name":"clean_product_keys","path":"webshop/web_agent_site/engine/engine.py","language":"python","start_line":210,"end_line":227,"context_start_line":190,"context_end_line":247,"code":" price = random.uniform(*pricing[:2])\n product_prices[asin] = price\n return product_prices\n\n\ndef init_search_engine(num_products=None):\n if num_products == 100:\n indexes = 'indexes_100'\n elif num_products == 1000:\n indexes = 'indexes_1k'\n elif num_products == 100000:\n indexes = 'indexes_100k'\n elif num_products is None:\n indexes = 'indexes'\n else:\n raise NotImplementedError(f'num_products being {num_products} is not supported yet.')\n search_engine = LuceneSearcher(os.path.join(BASE_DIR, f'../search_engine/{indexes}'))\n return search_engine\n\n\ndef clean_product_keys(products):\n for product in products:\n product.pop('product_information', None)\n product.pop('brand', None)\n product.pop('brand_url', None)\n product.pop('list_price', None)\n product.pop('availability_quantity', None)\n product.pop('availability_status', None)\n product.pop('total_reviews', None)\n product.pop('total_answered_questions', None)\n product.pop('seller_id', None)\n product.pop('seller_name', None)\n product.pop('fulfilled_by_amazon', None)\n product.pop('fast_track_message', None)\n product.pop('aplus_present', None)\n product.pop('small_description_old', None)\n print('Keys cleaned.')\n return products\n\n\ndef load_products(filepath, num_products=None, human_goals=True):\n # TODO: move to preprocessing step -> enforce single source of truth\n with open(filepath) as f:\n products = json.load(f)\n print('Products loaded.')\n products = clean_product_keys(products)\n \n # with open(DEFAULT_REVIEW_PATH) as f:\n # reviews = json.load(f)\n all_reviews = dict()\n all_ratings = dict()\n # for r in reviews:\n # all_reviews[r['asin']] = r['reviews']\n # all_ratings[r['asin']] = r['average_rating']\n\n if human_goals:\n with open(HUMAN_ATTR_PATH) as f:\n human_attributes = json.load(f)","source_hash":"9b86ffc82951124f5c4a7eb8103de14100dbee11ba8869951ed6fb8feaeef804","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.engine.engine.load_products","uri":"program://BOLAA/function/webshop.web_agent_site.engine.engine.load_products#L230-L362","kind":"function","name":"load_products","path":"webshop/web_agent_site/engine/engine.py","language":"python","start_line":230,"end_line":362,"context_start_line":210,"context_end_line":362,"code":"def clean_product_keys(products):\n for product in products:\n product.pop('product_information', None)\n product.pop('brand', None)\n product.pop('brand_url', None)\n product.pop('list_price', None)\n product.pop('availability_quantity', None)\n product.pop('availability_status', None)\n product.pop('total_reviews', None)\n product.pop('total_answered_questions', None)\n product.pop('seller_id', None)\n product.pop('seller_name', None)\n product.pop('fulfilled_by_amazon', None)\n product.pop('fast_track_message', None)\n product.pop('aplus_present', None)\n product.pop('small_description_old', None)\n print('Keys cleaned.')\n return products\n\n\ndef load_products(filepath, num_products=None, human_goals=True):\n # TODO: move to preprocessing step -> enforce single source of truth\n with open(filepath) as f:\n products = json.load(f)\n print('Products loaded.')\n products = clean_product_keys(products)\n \n # with open(DEFAULT_REVIEW_PATH) as f:\n # reviews = json.load(f)\n all_reviews = dict()\n all_ratings = dict()\n # for r in reviews:\n # all_reviews[r['asin']] = r['reviews']\n # all_ratings[r['asin']] = r['average_rating']\n\n if human_goals:\n with open(HUMAN_ATTR_PATH) as f:\n human_attributes = json.load(f)\n with open(DEFAULT_ATTR_PATH) as f:\n attributes = json.load(f)\n with open(HUMAN_ATTR_PATH) as f:\n human_attributes = json.load(f)\n print('Attributes loaded.')\n\n asins = set()\n all_products = []\n attribute_to_asins = defaultdict(set)\n if num_products is not None:\n # using item_shuffle.json, we assume products already shuffled\n products = products[:num_products]\n for i, p in tqdm(enumerate(products), total=len(products)):\n asin = p['asin']\n if asin == 'nan' or len(asin) > 10:\n continue\n\n if asin in asins:\n continue\n else:\n asins.add(asin)\n\n products[i]['category'] = p['category']\n products[i]['query'] = p['query']\n products[i]['product_category'] = p['product_category']\n\n products[i]['Title'] = p['name']\n products[i]['Description'] = p['full_description']\n products[i]['Reviews'] = all_reviews.get(asin, [])\n products[i]['Rating'] = all_ratings.get(asin, 'N.A.')\n for r in products[i]['Reviews']:\n if 'score' not in r:\n r['score'] = r.pop('stars')\n if 'review' not in r:\n r['body'] = ''\n else:\n r['body'] = r.pop('review')\n products[i]['BulletPoints'] = p['small_description'] \\\n if isinstance(p['small_description'], list) else [p['small_description']]\n\n pricing = p.get('pricing')\n if pricing is None or not pricing:\n pricing = [100.0]\n price_tag = '$100.0'\n else:\n pricing = [\n float(Decimal(re.sub(r'[^\\d.]', '', price)))\n for price in pricing.split('$')[1:]\n ]\n if len(pricing) == 1:\n price_tag = f\"${pricing[0]}\"\n else:\n price_tag = f\"${pricing[0]} to ${pricing[1]}\"\n pricing = pricing[:2]\n products[i]['pricing'] = pricing\n products[i]['Price'] = price_tag\n\n options = dict()\n customization_options = p['customization_options']\n option_to_image = dict()\n if customization_options:\n for option_name, option_contents in customization_options.items():\n if option_contents is None:\n continue\n option_name = option_name.lower()\n\n option_values = []\n for option_content in option_contents:\n option_value = option_content['value'].strip().replace('/', ' | ').lower()\n option_image = option_content.get('image', None)\n\n option_values.append(option_value)\n option_to_image[option_value] = option_image\n options[option_name] = option_values\n products[i]['options'] = options\n products[i]['option_to_image'] = option_to_image\n\n # without color, size, price, availability\n # if asin in attributes and 'attributes' in attributes[asin]:\n # products[i]['Attributes'] = attributes[asin]['attributes']\n # else:\n # products[i]['Attributes'] = ['DUMMY_ATTR']\n # products[i]['instruction_text'] = \\\n # attributes[asin].get('instruction', None)\n # products[i]['instruction_attributes'] = \\\n # attributes[asin].get('instruction_attributes', None)\n\n # without color, size, price, availability\n if asin in attributes and 'attributes' in attributes[asin]:\n products[i]['Attributes'] = attributes[asin]['attributes']\n else:\n products[i]['Attributes'] = ['DUMMY_ATTR']\n \n if human_goals:\n if asin in human_attributes:\n products[i]['instructions'] = human_attributes[asin]\n else:\n products[i]['instruction_text'] = \\\n attributes[asin].get('instruction', None)\n\n products[i]['instruction_attributes'] = \\\n attributes[asin].get('instruction_attributes', None)\n\n products[i]['MainImage'] = p['images'][0]\n products[i]['query'] = p['query'].lower().strip()\n\n all_products.append(products[i])\n\n for p in all_products:\n for a in p['Attributes']:\n attribute_to_asins[a].add(p['asin'])\n\n product_item_dict = {p['asin']: p for p in all_products}\n product_prices = generate_product_prices(all_products)\n return all_products, product_item_dict, product_prices, attribute_to_asins","source_hash":"9b86ffc82951124f5c4a7eb8103de14100dbee11ba8869951ed6fb8feaeef804","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.agents.shop_agent","uri":"program://BOLAA/module/webshop.web_agent_site.agents.shop_agent#L1-L11","kind":"module","name":"webshop.web_agent_site.agents.shop_agent","path":"webshop/web_agent_site/agents/shop_agent.py","language":"python","start_line":1,"end_line":11,"context_start_line":1,"context_end_line":11,"code":"class ShopAgent(object):\n def __init__(self):\n super().__init__()\n \n def forward(self, observation, available_actions):\n if available_actions['has_search_bar']:\n action = 'search[shoes]'\n else:\n action_arg = random.choice(available_actions['clickables'])\n action = f'click[{action_arg}]'\n return action","source_hash":"0dd7760516f35d34556413d4071b81dcca99abfd4b2cafb6536e7c0f27c8e579","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.agents.shop_agent.ShopAgent","uri":"program://BOLAA/class/webshop.web_agent_site.agents.shop_agent.ShopAgent#L1-L11","kind":"class","name":"ShopAgent","path":"webshop/web_agent_site/agents/shop_agent.py","language":"python","start_line":1,"end_line":11,"context_start_line":1,"context_end_line":11,"code":"class ShopAgent(object):\n def __init__(self):\n super().__init__()\n \n def forward(self, observation, available_actions):\n if available_actions['has_search_bar']:\n action = 'search[shoes]'\n else:\n action_arg = random.choice(available_actions['clickables'])\n action = f'click[{action_arg}]'\n return action","source_hash":"0dd7760516f35d34556413d4071b81dcca99abfd4b2cafb6536e7c0f27c8e579","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.agents.shop_agent.__init__","uri":"program://BOLAA/function/webshop.web_agent_site.agents.shop_agent.__init__#L2-L3","kind":"function","name":"__init__","path":"webshop/web_agent_site/agents/shop_agent.py","language":"python","start_line":2,"end_line":3,"context_start_line":1,"context_end_line":11,"code":"class ShopAgent(object):\n def __init__(self):\n super().__init__()\n \n def forward(self, observation, available_actions):\n if available_actions['has_search_bar']:\n action = 'search[shoes]'\n else:\n action_arg = random.choice(available_actions['clickables'])\n action = f'click[{action_arg}]'\n return action","source_hash":"0dd7760516f35d34556413d4071b81dcca99abfd4b2cafb6536e7c0f27c8e579","truncated":false} {"repo_id":"BOLAA","entity_id":"py:webshop.web_agent_site.agents.shop_agent.forward","uri":"program://BOLAA/function/webshop.web_agent_site.agents.shop_agent.forward#L5-L11","kind":"function","name":"forward","path":"webshop/web_agent_site/agents/shop_agent.py","language":"python","start_line":5,"end_line":11,"context_start_line":1,"context_end_line":11,"code":"class ShopAgent(object):\n def __init__(self):\n super().__init__()\n \n def forward(self, observation, available_actions):\n if available_actions['has_search_bar']:\n action = 'search[shoes]'\n else:\n action_arg = random.choice(available_actions['clickables'])\n action = f'click[{action_arg}]'\n return action","source_hash":"0dd7760516f35d34556413d4071b81dcca99abfd4b2cafb6536e7c0f27c8e579","truncated":false} {"repo_id":"BOLAA","entity_id":"file:run_webagent.py","uri":"program://BOLAA/file/run_webagent.py","kind":"file","name":"run_webagent.py","path":"run_webagent.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import os\nimport sys\nimport json\nimport random\nimport argparse\nfrom concurrent.futures import ThreadPoolExecutor\nimport time\n\nfrom web_run.web_env import webshopEnv\nfrom web_run.llms import get_llm_backend, OPENAI_CHAT_MODELS, OPENAI_LLM_MODELS\nfrom web_run.multi_agent_arch import SearchAgent, ClickAgent, ControlAgent\nimport web_run.agent_arch as agent_arch\nfrom web_run.utils import session_save, get_instruction, get_env_botton\nfrom web_run.evaluate import get_file_sess_idx\nfrom web_run.config import available_agent_names\n\nparser = argparse.ArgumentParser(description='Parsing the input of agents, llms and llm context length.')\nparser.add_argument(\"--agent_name\", type=str, help=\"Name of the agent.\", default=\"React\")\nparser.add_argument(\"--llm_name\", type=str, help=\"Name of the llm\", default=\"gpt-3.5-turbo\")\nparser.add_argument(\"--max_context_len\", type=int, help=\"Maximum context length\", default=1700)\nargs = parser.parse_args()","source_hash":"7881aab9ac9444401897a186b7385bcf5c38985185352d163a0cf452330b326f","truncated":false} {"repo_id":"BOLAA","entity_id":"file:run_hotpotqaagent.py","uri":"program://BOLAA/file/run_hotpotqaagent.py","kind":"file","name":"run_hotpotqaagent.py","path":"run_hotpotqaagent.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import os\nimport argparse \nimport numpy as np\nimport pandas as pd\nimport concurrent\nimport joblib\nfrom hotpotqa_run.utils import summarize_trial_detailed, log_trial\nimport hotpotqa_run.utils as utils\nfrom hotpotqa_run.agent_arch import get_agent\nfrom hotpotqa_run.llms import get_llm_backend\nfrom hotpotqa_run.config import available_agent_names\n\n\nparser = argparse.ArgumentParser(description='Parsing the input of agents, llms and llm context length.')\nparser.add_argument(\"--agent_name\", type=str, help=\"Name of the agent.\", default=\"React\")\nparser.add_argument(\"--llm_name\", type=str, help=\"Name of the llm\", default=\"gpt-3.5-turbo\")\nparser.add_argument(\"--max_context_len\", type=int, help=\"Maximum context length\", default=1700)\nargs = parser.parse_args()\n\nagent_name = args.agent_name\nllm_name = args.llm_name","source_hash":"8e7b0bd4cfe46479f31447fca04517a6e36531bff1ff8d9ef5aa3fd61d696449","truncated":false} {"repo_id":"BOLAA","entity_id":"file:web_run/config.py","uri":"program://BOLAA/file/web_run/config.py","kind":"file","name":"web_run/config.py","path":"web_run/config.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":11,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\navailable_agent_names = [\"Zeroshot_Webrun_Agent\",\"ZeroshotThink_Webrun_Agent\",\n \"React_Webrun_Agent\",\"Planner_Webrun_Agent\",\n \"PlannerReact_Webrun_Agent\",\"Search_Click_Control_Webrun_Agent\"]\nOPENAI_API_KEY = \"\"","source_hash":"963bf61d4596fcacfad502a585d85341e4581ad426a76d7da2f6898a51857722","truncated":false} {"repo_id":"BOLAA","entity_id":"file:web_run/agent_arch.py","uri":"program://BOLAA/file/web_run/agent_arch.py","kind":"file","name":"web_run/agent_arch.py","path":"web_run/agent_arch.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport random\nimport re\nimport json \nimport time\nimport os\nimport tiktoken\nimport web_run.pre_prompt as pre_prompt\nfrom web_run.utils import get_query\nfrom web_run.llms import token_enc\n\n\nclass BaseAgent(object):\n def __init__(self, llm, context_len=2000):\n self.type = \"Base_Webrun_Agent\"","source_hash":"8fca5841f4c2d805f5ace23a7168cbfb78d9436776779a88549101ffd96df94d","truncated":false} {"repo_id":"BOLAA","entity_id":"file:web_run/web_env.py","uri":"program://BOLAA/file/web_run/web_env.py","kind":"file","name":"web_run/web_env.py","path":"web_run/web_env.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import requests\nfrom bs4 import BeautifulSoup\nfrom bs4.element import Comment\n\nWEBSHOP_URL = \"http://127.0.0.1:3000\"\nACTION_TO_TEMPLATE = {\n 'Description': 'description_page.html',\n 'Features': 'features_page.html',\n 'Reviews': 'review_page.html',\n 'Attributes': 'attributes_page.html',\n}\nMAX_PRO_OB = 8 \n\ndef clean_str(p):\n return p.encode().decode(\"unicode-escape\").encode(\"latin1\").decode(\"utf-8\")\n\n\ndef tag_visible(element):\n ignore = {'style', 'script', 'head', 'title', 'meta', '[document]'}\n return (\n element.parent.name not in ignore and not isinstance(element, Comment)","source_hash":"c39b484c4e3c701814c5dd5fb5f2722e36e78f39b59b5ee4b90ed6b45fb81cbb","truncated":false} {"repo_id":"BOLAA","entity_id":"file:web_run/utils.py","uri":"program://BOLAA/file/web_run/utils.py","kind":"file","name":"web_run/utils.py","path":"web_run/utils.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport json \nimport re\n\ndef obser_parser(observation, instruction_text):\n obs = observation.encode().decode(\"unicode-escape\").encode(\"latin1\").decode(\"utf-8\")\n # obs = obs.replace(\"[SEP]\",'|')\n obs = obs.replace(\"[button]\",\"[\")\n obs = obs.replace(\"[button_]\",\"]\")\n if obs.startswith('Instruction:'):\n obs = obs.replace(instruction_text,\"\")\n obs = obs.replace('Instruction:',\"\")\n if obs.startswith('You have clicked'):\n obs = obs.split('\\n')[0]\n obs = obs.lstrip()","source_hash":"2bc09f067188fefd5df691b231661b58410a43feb62a2b1c5ce244b2bdcbef34","truncated":false} {"repo_id":"BOLAA","entity_id":"file:web_run/multi_agent_arch.py","uri":"program://BOLAA/file/web_run/multi_agent_arch.py","kind":"file","name":"web_run/multi_agent_arch.py","path":"web_run/multi_agent_arch.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport time\nimport os\nimport web_run.pre_prompt as pre_prompt\nfrom web_run.utils import get_query\nfrom web_run.llms import token_enc\n\n\ncontrol_dict = {\"Search_Webrun_Agent\":\"search\",\n \"Think_Webrun_Agent\":\"think\",\n \"Click_Webrun_Agent\":\"click\"}\n \nclass ClickAgent:\n def __init__(self, llm, context_len=2000):\n self.type = \"Click_Webrun_Agent\"","source_hash":"7b928fb475294d6ea91a0c633556165d1f7fdb0295081748a6fadb3a94184233","truncated":false} {"repo_id":"BOLAA","entity_id":"file:web_run/pre_prompt.py","uri":"program://BOLAA/file/web_run/pre_prompt.py","kind":"file","name":"web_run/pre_prompt.py","path":"web_run/pre_prompt.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nzeroshot = \"\"\"Following the instruction to simulate the web shopping. Based on your observation, you may operate one of the following actions\nsearch: using this action to search products.\nclick: click observed [button], the clickable buttons are in [], for example click [Back to Search] can return back to research.\nUse your best knowledge and take actions. You response should follow action[detail] format, such as search[3 ounce bright citrus deodorant sensitive skin], click[B078GWRC1J], click[bright citrus].\n\"\"\"\n\nzeroshot_think = \"\"\"You are simulating web shopping. Based on your observation, you may operate one of the following actions:\nsearch: using this action to search products.\nthink: using this action to plan your actions and reasoning.\nclick: using this action to click observed [button], the clickable buttons are in [], for example click [Back to Search] can return back to research.\nUse your best knowledge and take actions. You response should follow action[detail] format, such as search[3 ounce bright citrus deodorant sensitive skin], think[B078GWRC1J and B078GTKVXY are bright citrus deodorant less then 50 dollars. I can check B078GWRC1J first.], click[B078GWRC1J], click[bright citrus].\n\"\"\"\n\noneshot = \"\"\"Webshop ","source_hash":"586b9a596752820d653c8c3b3e6cc7b2f5787443a00ec644b935198442c7cffe","truncated":false} {"repo_id":"BOLAA","entity_id":"file:web_run/evaluate.py","uri":"program://BOLAA/file/web_run/evaluate.py","kind":"file","name":"web_run/evaluate.py","path":"web_run/evaluate.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport json\nimport os\nimport re \nfrom collections import defaultdict\nfrom web_run.config import available_agent_names\n\ndef get_complexity(ins_attr_file=\"../webshop/data/items_human_ins_new.json\"):\n with open(ins_attr_file) as f:\n human_attr = json.load(f)\n complexity_dict = {}\n for asin in human_attr:\n for ins in human_attr[asin]:\n instruction = ins[\"instruction\"]\n attribute_complexity = len(ins[\"instruction_attributes\"])","source_hash":"59a43691ed9f112b44168dd6840c70d610f462d6fff92275fc8c514f235b856b","truncated":false} {"repo_id":"BOLAA","entity_id":"file:web_run/llms.py","uri":"program://BOLAA/file/web_run/llms.py","kind":"file","name":"web_run/llms.py","path":"web_run/llms.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport os\nimport sys\nimport json\nimport random\nimport tiktoken\ntoken_enc = tiktoken.get_encoding(\"cl100k_base\")\nimport openai\nfrom langchain import PromptTemplate, OpenAI, LLMChain\nfrom transformers import AutoTokenizer, AutoModelForCausalLM\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.chains import LLMChain\nfrom langchain import PromptTemplate\nfrom langchain.prompts.chat import (\n ChatPromptTemplate,","source_hash":"e8dadcd5c975227c22060fdc5519cc6907b63536aec6f5814eafb56dd95eef88","truncated":false} {"repo_id":"BOLAA","entity_id":"file:hotpotqa_run/config.py","uri":"program://BOLAA/file/hotpotqa_run/config.py","kind":"file","name":"hotpotqa_run/config.py","path":"hotpotqa_run/config.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":9,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\navailable_agent_names = [\"Zeroshot_HotPotQA_run_Agent\",\"ZeroshotThink_HotPotQA_run_Agent\",\"React_HotPotQA_run_Agent\",\"Planner_HotPotQA_run_Agent\",\"PlannerReact_HotPotQA_run_Agent\"]\nOPENAI_API_KEY = \"\"","source_hash":"834865f6e526c92e21eeb20b1ebcec03502024591da49b5deea9c012aaaf2ebc","truncated":false} {"repo_id":"BOLAA","entity_id":"file:hotpotqa_run/wikienv.py","uri":"program://BOLAA/file/hotpotqa_run/wikienv.py","kind":"file","name":"hotpotqa_run/wikienv.py","path":"hotpotqa_run/wikienv.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport ast\nimport json\nimport time\nimport gym\nimport requests\nfrom bs4 import BeautifulSoup\n\n# import wikipedia\n\ndef clean_str(p):\n return p.encode().decode(\"unicode-escape\").encode(\"latin1\").decode(\"utf-8\")\n\n\nclass textSpace(gym.spaces.Space):","source_hash":"b79b874c4a5be411be5ed7262e5557188c4bb5bdbc5f3a2837331c25e294c3ce","truncated":false} {"repo_id":"BOLAA","entity_id":"file:hotpotqa_run/hotpotqa_env.py","uri":"program://BOLAA/file/hotpotqa_run/hotpotqa_env.py","kind":"file","name":"hotpotqa_run/hotpotqa_env.py","path":"hotpotqa_run/hotpotqa_env.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import wikienv, wrappers\n\ndef step(env, action):\n attempts = 0\n while attempts < 10:\n try:\n return env.step(action)\n except requests.exceptions.Timeout:\n attempts += 1\n\nclass HotPotQAEnv:\n def __init__(self, n_tasks=100):\n self.n_tasks = n_tasks\n self.sessions = {}\n env = wikienv.WikiEnv()\n env = wrappers.HotPotQAWrapper(env, split=\"dev\")\n env = wrappers.LoggingWrapper(env)\n for idx in range(self.n_tasks):\n self.sessions[idx] = {'session': idx, \n 'question': question = env.reset(idx=idx)\n }","source_hash":"03a84e448feccc0f54a0e17bcfc7329a4b025ff7a55114477b70b3b7f65d2207","truncated":false} {"repo_id":"BOLAA","entity_id":"file:hotpotqa_run/agent_arch.py","uri":"program://BOLAA/file/hotpotqa_run/agent_arch.py","kind":"file","name":"hotpotqa_run/agent_arch.py","path":"hotpotqa_run/agent_arch.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport random\nimport re, string, os\nimport json \nimport time\nimport tiktoken\nfrom langchain.llms.base import BaseLLM\nfrom langchain import OpenAI, Wikipedia\nfrom langchain.docstore.base import Docstore\nfrom langchain.agents.react.base import DocstoreExplorer\nfrom langchain.prompts import PromptTemplate\nfrom collections import Counter\n\nfrom hotpotqa_run.pre_prompt import (react_agent_prompt, zeroshot_agent_prompt, \n plan_prompt, planner_agent_prompt, plannerreact_agent_prompt)","source_hash":"2d5a7b264d9206bbfa030f9dd685931decf2f50bafed9b0e5540f648329f9269","truncated":false} {"repo_id":"BOLAA","entity_id":"file:hotpotqa_run/utils.py","uri":"program://BOLAA/file/hotpotqa_run/utils.py","kind":"file","name":"hotpotqa_run/utils.py","path":"hotpotqa_run/utils.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport os\nimport joblib\nimport json\n\ndef summarize_trial(agents):\n correct = [a for a in agents if a.is_correct()]\n incorrect = [a for a in agents if a.is_finished() and not a.is_correct()]\n not_finish = [a for a in agents if not a.is_finished()]\n return correct, incorrect, not_finish\n\ndef remove_fewshot(prompt: str) -> str:\n prefix = prompt.split('Here are some examples:')[0]\n suffix = prompt.split('(END OF EXAMPLES)')[1]\n return prefix.strip('\\n').strip() + '\\n' + suffix.strip('\\n').strip()","source_hash":"9220738be27af1d480e8fdf3271c5641bf8444325c3f3dee4b60446548825200","truncated":false} {"repo_id":"BOLAA","entity_id":"file:hotpotqa_run/wrappers.py","uri":"program://BOLAA/file/hotpotqa_run/wrappers.py","kind":"file","name":"hotpotqa_run/wrappers.py","path":"hotpotqa_run/wrappers.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport json\nimport os\nimport gym\nimport numpy as np\nimport re\nimport string\nfrom collections import Counter\n\n \nDATA_DIR = \"data\"\nHOTPOTQA_SPLIT_FILE = {\n \"train\": \"hotpot_train_v1.1_simplified.json\",\n \"dev\": \"hotpot_dev_v1_simplified.json\",\n \"test\": \"hotpot_test_v1_simplified.json\",","source_hash":"0deac649089a79f9de23297850a143449c31b5988a57c2b5507287b0004116e8","truncated":false} {"repo_id":"BOLAA","entity_id":"file:hotpotqa_run/pre_prompt.py","uri":"program://BOLAA/file/hotpotqa_run/pre_prompt.py","kind":"file","name":"hotpotqa_run/pre_prompt.py","path":"hotpotqa_run/pre_prompt.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nfrom langchain.prompts import PromptTemplate\n\nZEROSHOT_INSTRUCTION = \"\"\"Solve a question answering task with interleaving Thought, Action, Observation steps. Thought can reason about the current situation, and Action can be three types: \n(1) Search[entity], which searches the exact entity on Wikipedia and returns the first paragraph if it exists. If not, it will return some similar entities to search. For example, Search[Milhouse]\n(2) Lookup[keyword], which returns the next sentence containing keyword in the last passage successfully found by Search. For example, Lookup[named after]\n(3) Finish[answer], which returns the answer and finishes the task. For example, Finish[Richard Nixon] \nYou may take as many steps as necessary.\nQuestion: {question}{scratchpad}\"\"\"\n\nzeroshot_agent_prompt = PromptTemplate(\n input_variables=[\"question\", \"scratchpad\"],\n template = ZEROSHOT_INSTRUCTION,\n )\n","source_hash":"a0f91ffc099bc5baaa174497fc6aa25d7b316a083a3ff8aa89a5d86335a222eb","truncated":false} {"repo_id":"BOLAA","entity_id":"file:hotpotqa_run/fewshots.py","uri":"program://BOLAA/file/hotpotqa_run/fewshots.py","kind":"file","name":"hotpotqa_run/fewshots.py","path":"hotpotqa_run/fewshots.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nREACT_EXAMPLE = \"\"\"Question: Musician and satirist Allie Goertz wrote a song about the \"The Simpsons\" character Milhouse, who Matt Groening named after who?\nThought 1: The question simplifies to \"The Simpsons\" character Milhouse is named after who. I only need to search Milhouse and find who it is named after.\nAction 1: Search[Milhouse]\nObservation 1: Milhouse Mussolini Van Houten is a recurring character in the Fox animated television series The Simpsons voiced by Pamela Hayden and created by Matt Groening.\nThought 2: The paragraph does not tell who Milhouse is named after, maybe I can look up \"named after\".\nAction 2: Lookup[named after]\nObservation 2: (Result 1 / 1) Milhouse was named after U.S. president Richard Nixon, whose middle name was Milhous. \nThought 3: Milhouse was named after U.S. president Richard Nixon, so the answer is Richard Nixon.\nAction 3: Finish[Richard Nixon]\n\nQuestion: Were Pavel Urysohn and Leonid Levin known for the same type of work?\nThought 1: I need to search Pavel Urysohn and Leonid Levin, find their types of work, then find if they are the same.\nAction 1: Search[Pavel Urysohn]\nObservation 1: Pavel Samuilovich Urysohn (February 3, 1898 – August 17, 1924) was a Soviet mathematician who is best known for his contributions in dimension theory.","source_hash":"579a805ef628546cdec407356c2d8d7302322a601972dea9bfb362ce1ea45547","truncated":false} {"repo_id":"BOLAA","entity_id":"file:hotpotqa_run/evaluate.py","uri":"program://BOLAA/file/hotpotqa_run/evaluate.py","kind":"file","name":"hotpotqa_run/evaluate.py","path":"hotpotqa_run/evaluate.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport json\nimport os\nimport re \nfrom collections import defaultdict\nimport pandas as pd\nimport hotpotqa_run.utils as utils\n\ndef eval_success(result_file) -> list:\n df = pd.read_csv(result_file)\n return df['success'].tolist()\n\ndef eval_reward(result_file) -> list:\n df = pd.read_csv(result_file)\n return df['reward'].tolist()","source_hash":"e857485617da3ecbc25db4fa9345a8692f777abcb0d4c14dccc729e8b5119d63","truncated":false} {"repo_id":"BOLAA","entity_id":"file:hotpotqa_run/llms.py","uri":"program://BOLAA/file/hotpotqa_run/llms.py","kind":"file","name":"hotpotqa_run/llms.py","path":"hotpotqa_run/llms.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"\"\"\"\n Copyright (c) 2023, salesforce.com, inc.\n All rights reserved.\n SPDX-License-Identifier: Apache License 2.0\n For full license text, see the LICENSE file in the repo root or https://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\nimport os\nimport sys\nimport json\nimport random\nimport tiktoken\ntoken_enc = tiktoken.get_encoding(\"cl100k_base\")\nimport openai\nfrom langchain import PromptTemplate, OpenAI, LLMChain\nfrom transformers import AutoTokenizer, AutoModelForCausalLM\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.chains import LLMChain\nfrom langchain import PromptTemplate\nfrom langchain.prompts.chat import (\n ChatPromptTemplate,","source_hash":"e8dadcd5c975227c22060fdc5519cc6907b63536aec6f5814eafb56dd95eef88","truncated":false} {"repo_id":"BOLAA","entity_id":"file:webshop/test.py","uri":"program://BOLAA/file/webshop/test.py","kind":"file","name":"webshop/test.py","path":"webshop/test.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":13,"code":"import re \ndef idx_parser(text):\n pattern = r\"\\d\\s\\w*\" # Matches a word boundary, followed by a digit, and then any word characters\n\n match = re.search(pattern, text)\n if match:\n return int(match.group(0))\n else:\n return None\n \ntext = \"5\\n\\nAction: Buy Now\"\nidx = idx_parser(text)\nprint(idx)","source_hash":"ba979dead6cc1961eaa058c989dc89ba4c931ac62050f3c82434e6c50d93f394","truncated":false} {"repo_id":"BOLAA","entity_id":"file:webshop/tests/web-agent-site/test_utils.py","uri":"program://BOLAA/file/webshop/tests/web-agent-site/test_utils.py","kind":"file","name":"webshop/tests/web-agent-site/test_utils.py","path":"webshop/tests/web-agent-site/test_utils.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import logging\nimport pytest\nimport random\nimport shutil\nfrom pathlib import Path\nfrom web_agent_site.utils import *\n\ndef test_random_idx():\n random.seed(24)\n weights = [random.randint(0, 10) for _ in range(0, 50)]\n cml_weights = [0]\n for w in weights:\n cml_weights.append(cml_weights[-1] + w)\n idx_1, expected_1 = random_idx(cml_weights), 44\n idx_2, expected_2 = random_idx(cml_weights), 15\n idx_3, expected_3 = random_idx(cml_weights), 36\n assert idx_1 == expected_1\n assert idx_2 == expected_2\n assert idx_3 == expected_3\n\ndef test_setup_logger():","source_hash":"67a6212e65db7a6a13a9d284d1468cdd28458582664d9af94ec3c5a5443449d5","truncated":false} {"repo_id":"BOLAA","entity_id":"file:webshop/tests/web-agent-site/engine/test_goal.py","uri":"program://BOLAA/file/webshop/tests/web-agent-site/engine/test_goal.py","kind":"file","name":"webshop/tests/web-agent-site/engine/test_goal.py","path":"webshop/tests/web-agent-site/engine/test_goal.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import pytest\nfrom math import isclose\nfrom web_agent_site.engine.goal import *\n\ndef test_get_type_reward():\n # Exact Match\n goal = {\n 'query': \"Query 1\",\n 'product_category': \"a › b › c\",\n 'name': \"Name 1\"\n }\n purchased = {\n 'query': \"Query 1\",\n 'product_category': \"a › b › c\",\n 'name': \"Name 1\"\n }\n result = get_type_reward(purchased, goal)\n assert result['r_type'] == 1.\n assert result['query_match'] == True\n assert result['category_match'] == True\n assert result['title_score'] == 1","source_hash":"f10b97ca81eb2f4ffd8a3a0b377f421d3c0ce50ee2d5e80d7e1f39fab228055e","truncated":false} {"repo_id":"BOLAA","entity_id":"file:webshop/tests/web-agent-site/engine/test_normalize.py","uri":"program://BOLAA/file/webshop/tests/web-agent-site/engine/test_normalize.py","kind":"file","name":"webshop/tests/web-agent-site/engine/test_normalize.py","path":"webshop/tests/web-agent-site/engine/test_normalize.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import pytest\nfrom web_agent_site.engine.normalize import *\n\ndef test_normalize_color():\n suite = [\n (\"\", \"\"),\n (\"black forest\", \"black\"),\n (\"violet lavender\", \"lavender\"),\n (\"steelivy fuchsia\", \"fuchsia\"),\n (\"123alabaster\", \"alabaster\"),\n (\"webshop\", \"webshop\")\n ]\n for color_string, expected in suite:\n output = normalize_color(color_string)\n assert type(output) is str\n assert output == expected\n\ndef test_normalize_color_size():\n product_prices = {\n (1, \"black forest\", \"3 meter\"): 10.29,\n (2, \"violet lavender\", \"xx-large\"): 23.42,","source_hash":"503168a43640681d8a5863a027727c8b4c2b777358b278e3c0bd45d6f2f476a4","truncated":false} {"repo_id":"BOLAA","entity_id":"file:webshop/tests/transfer/test_predict_help.py","uri":"program://BOLAA/file/webshop/tests/transfer/test_predict_help.py","kind":"file","name":"webshop/tests/transfer/test_predict_help.py","path":"webshop/tests/transfer/test_predict_help.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import json\nimport pytest\nimport requests_mock\n\nfrom transfer.predict_help import (\n convert_dict_to_actions,\n parse_item_page_amz, parse_results_amz,\n parse_item_page_ebay, parse_results_ebay,\n parse_item_page_ws, parse_results_ws,\n Page, WEBSHOP_URL, WEBSHOP_SESSION\n)\n\n@requests_mock.Mocker(kw=\"mock\")\ndef test_parse_item_page_ws(**kwargs):\n # Read mock response data\n mock_file = open(\"tests/transfer/mocks/mock_parse_item_page_ws\", \"rb\")\n mock_body = mock_file.read()\n mock_file.close()\n\n mock_desc_file = open(\"tests/transfer/mocks/mock_parse_item_page_ws_desc\", \"rb\")\n mock_desc_body = mock_desc_file.read()","source_hash":"2f1ed677907f992ff0bf377061e7a82ff04886c655a7dff164bfed0dcddc7d59","truncated":false} {"repo_id":"BOLAA","entity_id":"file:webshop/run_envs/run_web_agent_text_env.py","uri":"program://BOLAA/file/webshop/run_envs/run_web_agent_text_env.py","kind":"file","name":"webshop/run_envs/run_web_agent_text_env.py","path":"webshop/run_envs/run_web_agent_text_env.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"\"\"\"\nTest the text gym environment.\n\nTODO: move to testing dir for more rigorous tests\n\"\"\"\nimport gym\nfrom rich import print\nfrom rich.markup import escape\n\nfrom web_agent_site.envs import WebAgentTextEnv\nfrom web_agent_site.models import RandomPolicy\nfrom web_agent_site.utils import DEBUG_PROD_SIZE\n\nif __name__ == '__main__':\n env = gym.make('WebAgentTextEnv-v0', observation_mode='text', num_products=DEBUG_PROD_SIZE)\n env.reset()\n \n try:\n policy = RandomPolicy()\n \n observation = env.observation","source_hash":"530356dadac65db9e767c677b5b166abd1002d6d9dd5b2c81c4e297a00293751","truncated":false} {"repo_id":"BOLAA","entity_id":"file:webshop/run_envs/run_web_agent_site_env.py","uri":"program://BOLAA/file/webshop/run_envs/run_web_agent_site_env.py","kind":"file","name":"webshop/run_envs/run_web_agent_site_env.py","path":"webshop/run_envs/run_web_agent_site_env.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"\"\"\"\nTest the site gym environment.\n\nTODO: move to testing dir for more rigorous tests\n\"\"\"\nimport gym\nfrom rich import print\nfrom rich.markup import escape\n\nfrom web_agent_site.envs import WebAgentSiteEnv\nfrom web_agent_site.models import (\n HumanPolicy,\n RandomPolicy,\n)\nfrom web_agent_site.utils import DEBUG_PROD_SIZE\n\n\nif __name__ == '__main__':\n #env = gym.make('WebAgentSite-v0')\n #env = WebAgentSiteEnv(render=True, pause=2.0)\n #env = WebAgentSiteEnv(observation_mode='html', render=False)","source_hash":"c40b099b1039acd9bcb2798eb027f25335c82b8b3f4cda56b5d31fe21638d6f8","truncated":false} {"repo_id":"BOLAA","entity_id":"file:webshop/web_agent_site/app.py","uri":"program://BOLAA/file/webshop/web_agent_site/app.py","kind":"file","name":"webshop/web_agent_site/app.py","path":"webshop/web_agent_site/app.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import argparse, json, logging, random\nfrom pathlib import Path\nfrom ast import literal_eval\n\nfrom flask import (\n Flask,\n request,\n redirect,\n url_for\n)\n\nfrom rich import print\n\nfrom web_agent_site.engine.engine import (\n load_products,\n init_search_engine,\n convert_web_app_string_to_var,\n get_top_n_product_from_keywords,\n get_product_per_page,\n map_action_to_html,\n END_BUTTON","source_hash":"b35dc4e8771af298273974a7d1a1dae7986a78009eb671f71981933546ba8586","truncated":false} {"repo_id":"BOLAA","entity_id":"file:webshop/web_agent_site/utils.py","uri":"program://BOLAA/file/webshop/web_agent_site/utils.py","kind":"file","name":"webshop/web_agent_site/utils.py","path":"webshop/web_agent_site/utils.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import bisect\nimport hashlib\nimport logging\nimport random\nfrom os.path import dirname, abspath, join\n\nBASE_DIR = dirname(abspath(__file__))\nDEBUG_PROD_SIZE = None # set to `None` to disable\n\n# DEFAULT_ATTR_PATH = join(BASE_DIR, '../data/items_ins_v2_1000.json')\n# DEFAULT_FILE_PATH = join(BASE_DIR, '../data/items_shuffle_1000.json')\nDEFAULT_ATTR_PATH = join(BASE_DIR, '../data/items_ins_v2.json')\nDEFAULT_FILE_PATH = join(BASE_DIR, '../data/items_shuffle.json')\nDEFAULT_REVIEW_PATH = join(BASE_DIR, '../data/reviews.json')\n\nFEAT_CONV = join(BASE_DIR, '../data/feat_conv.pt')\nFEAT_IDS = join(BASE_DIR, '../data/feat_ids.pt')\n\nHUMAN_ATTR_PATH = join(BASE_DIR, '../data/new_human_ins_sampled_1.json')\n\n# HUMAN_ATTR_PATH = join(BASE_DIR, '../data/items_human_ins.json')","source_hash":"0c78ce4209049cd315e164525edac2bef0a2cdfbbdbb818c90cfa9b2d7073ec6","truncated":false} {"repo_id":"BOLAA","entity_id":"file:webshop/web_agent_site/models/models.py","uri":"program://BOLAA/file/webshop/web_agent_site/models/models.py","kind":"file","name":"webshop/web_agent_site/models/models.py","path":"webshop/web_agent_site/models/models.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"\"\"\"\nModel implementations. The model interface should be suitable for both\nthe ``site env'' and the ``text env''.\n\"\"\"\nimport random\n\nrandom.seed(4)\n\n\nclass BasePolicy:\n def __init__(self):\n pass\n \n def forward(observation, available_actions):\n \"\"\"\n Args:\n observation (`str`):\n HTML string\n\n available_actions ():\n ...","source_hash":"229b2f2fb0feedcac84a8e7ed6484c976e4c0ccb026e22996052215c427445a7","truncated":false} {"repo_id":"BOLAA","entity_id":"file:webshop/web_agent_site/models/__init__.py","uri":"program://BOLAA/file/webshop/web_agent_site/models/__init__.py","kind":"file","name":"webshop/web_agent_site/models/__init__.py","path":"webshop/web_agent_site/models/__init__.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":4,"code":"from web_agent_site.models.models import (\n HumanPolicy,\n RandomPolicy,\n)","source_hash":"06a57f9b9ff18e749dff8b9bbb69cf78819a7515fb79a414ba2c3e2ee27ed626","truncated":false} {"repo_id":"BOLAA","entity_id":"file:webshop/web_agent_site/attributes/generate_attrs.py","uri":"program://BOLAA/file/webshop/web_agent_site/attributes/generate_attrs.py","kind":"file","name":"webshop/web_agent_site/attributes/generate_attrs.py","path":"webshop/web_agent_site/attributes/generate_attrs.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import json\nimport yaml\nimport random\nfrom pathlib import Path\nfrom collections import defaultdict\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_extraction import text as sk_text\nimport pandas as pd\nfrom tqdm import tqdm\nfrom rich import print\n\nITEMS_PATH = './data/ITEMS_mar1.json'\nREVIEWS_PATH = './data/reviews.json'\nATTR_DIR = './data/attributes'\n\nrandom.seed(0)\n\n\ndef get_stop_words():\n extra_stop_words = set([str(i) for i in range(1000)])","source_hash":"b6e079d6765966e1c244e7de31d444c17423d912d24f0ef08844c32daa2efe3a","truncated":false} {"repo_id":"BOLAA","entity_id":"file:webshop/web_agent_site/attributes/annotate.py","uri":"program://BOLAA/file/webshop/web_agent_site/attributes/annotate.py","kind":"file","name":"webshop/web_agent_site/attributes/annotate.py","path":"webshop/web_agent_site/attributes/annotate.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import yaml\nfrom pathlib import Path\nfrom rich import print\n\nATTR_DIR = './data/attributes'\n\nATTR_PATHS = [\n 'narrow_2-gram.yaml',\n 'narrow_1-gram.yaml',\n 'broad_2-gram.yaml',\n 'broad_1-gram.yaml',\n]\nATTR_PATHS = [Path(ATTR_DIR) / af for af in ATTR_PATHS]\n\n\ndef annotate(attr_path):\n with open(attr_path) as f:\n attrs_by_cat = yaml.safe_load(f)\n\n unique_attrs = set()\n all_attrs = []","source_hash":"f64f3f8be3af15794821506014b97c1abc75424973ab9b06d4af4b9c2dec4a45","truncated":false} {"repo_id":"BOLAA","entity_id":"file:webshop/web_agent_site/envs/web_agent_site_env.py","uri":"program://BOLAA/file/webshop/web_agent_site/envs/web_agent_site_env.py","kind":"file","name":"webshop/web_agent_site/envs/web_agent_site_env.py","path":"webshop/web_agent_site/envs/web_agent_site_env.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import gym\nimport random\nimport requests\nimport string\nimport time\n\nfrom bs4 import BeautifulSoup\nfrom bs4.element import Comment\nfrom gym import spaces\nfrom os.path import join, dirname, abspath\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.common.exceptions import ElementNotInteractableException\nfrom web_agent_site.engine.engine import parse_action, END_BUTTON\n\nclass WebAgentSiteEnv(gym.Env):\n \"\"\"Gym environment for HTML mode of WebShop environment\"\"\"\n\n def __init__(self, observation_mode='html', **kwargs):","source_hash":"7b3a43c0250ef2215e2ac1e613ebafbcfbea053a24fcbb773541dc634f124981","truncated":false} {"repo_id":"BOLAA","entity_id":"file:webshop/web_agent_site/envs/web_agent_text_env.py","uri":"program://BOLAA/file/webshop/web_agent_site/envs/web_agent_text_env.py","kind":"file","name":"webshop/web_agent_site/envs/web_agent_text_env.py","path":"webshop/web_agent_site/envs/web_agent_text_env.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import gym\nimport json\nimport random\nimport string\nimport time\nimport torch\n\nfrom bs4 import BeautifulSoup\nfrom bs4.element import Comment\nfrom collections import defaultdict\nfrom flask import Flask\nfrom web_agent_site.engine.engine import (\n load_products,\n init_search_engine,\n get_top_n_product_from_keywords,\n map_action_to_html,\n parse_action,\n get_product_per_page,\n ACTION_TO_TEMPLATE,\n END_BUTTON, NEXT_PAGE, PREV_PAGE, BACK_TO_SEARCH,\n)","source_hash":"d0b7dbe70eb8e802c4437d4c646ea2eb1ddef0a7eac4aeb16aaa6a87b34fa82b","truncated":false} {"repo_id":"BOLAA","entity_id":"file:webshop/web_agent_site/envs/__init__.py","uri":"program://BOLAA/file/webshop/web_agent_site/envs/__init__.py","kind":"file","name":"webshop/web_agent_site/envs/__init__.py","path":"webshop/web_agent_site/envs/__init__.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":14,"code":"from gym.envs.registration import register\n\nfrom web_agent_site.envs.web_agent_site_env import WebAgentSiteEnv\nfrom web_agent_site.envs.web_agent_text_env import WebAgentTextEnv\n\nregister(\n id='WebAgentSiteEnv-v0',\n entry_point='web_agent_site.envs:WebAgentSiteEnv',\n)\n\nregister(\n id='WebAgentTextEnv-v0',\n entry_point='web_agent_site.envs:WebAgentTextEnv',\n)","source_hash":"7cdf100d019fd715d605ff0cd0f0d3d4285d7f7b2dbe4e4634e9a1266ab5e854","truncated":false} {"repo_id":"BOLAA","entity_id":"file:webshop/web_agent_site/engine/normalize.py","uri":"program://BOLAA/file/webshop/web_agent_site/engine/normalize.py","kind":"file","name":"webshop/web_agent_site/engine/normalize.py","path":"webshop/web_agent_site/engine/normalize.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom typing import Tuple\n\nCOLOR_SET = [\n 'alabaster', 'apricot', 'aqua', 'ash', 'asphalt', 'azure',\n 'banana', 'beige', 'black', 'blue', 'blush', 'bordeaux', 'bronze',\n 'brown', 'burgundy', 'camel', 'camo', 'caramel', 'champagne',\n 'charcoal', 'cheetah', 'chestnut', 'chocolate', 'christmas', 'coffee',\n 'cognac', 'copper', 'coral', 'cranberry', 'cream', 'crystal', 'dark',\n 'denim', 'eggplant', 'elephant', 'espresso', 'fuchsia', 'gold', 'granite',\n 'grape', 'graphite', 'grass', 'gray', 'green', 'grey', 'heather', 'indigo',\n 'ivory', 'ivy', 'khaki', 'lavender', 'lemon', 'leopard', 'light', 'lilac',\n 'lime', 'magenta', 'maroon', 'mauve', 'merlot', 'midnight', 'mint', 'mocha',\n 'multicolor', 'mushroom', 'mustard', 'natural', 'navy', 'nude', 'olive',\n 'orange', 'peach', 'pewter', 'pink', 'plum', 'purple', 'rainbow', 'red',\n 'rose', 'royal', 'rust', 'sand', 'sapphire', 'seashell', 'silver', 'skull',\n 'slate', 'steel', 'stone', 'stonewash', 'sunflower', 'tan', 'taupe', 'teal',\n 'tiger', 'turquoise', 'violet', 'walnut', 'wheat', 'white', 'wine', 'yellow',\n]\n\nSIZE_SET = [","source_hash":"1962113ac9e209a636d4f181b2c70544bbea59b03adca9847e48287158d794fb","truncated":false} {"repo_id":"BOLAA","entity_id":"file:webshop/web_agent_site/engine/goal.py","uri":"program://BOLAA/file/webshop/web_agent_site/engine/goal.py","kind":"file","name":"webshop/web_agent_site/engine/goal.py","path":"webshop/web_agent_site/engine/goal.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"\"\"\"\nFunctions for specifying goals and reward calculations.\n\"\"\"\nimport itertools\nimport random\nimport spacy\nfrom collections import defaultdict\nfrom rich import print\nfrom thefuzz import fuzz\nfrom web_agent_site.engine.normalize import normalize_color\n\nnlp = spacy.load(\"en_core_web_lg\")\n\nPRICE_RANGE = [10.0 * i for i in range(1, 100)]\n\ndef get_goals(all_products, product_prices, human_goals=True):\n if human_goals:\n return get_human_goals(all_products, product_prices)\n else:\n return get_synthetic_goals(all_products, product_prices)\n ","source_hash":"d6083dbff9e8b3957bef50cf56edd1f371bcd076ad8cf16fdd7eda09ee4fb87e","truncated":false} {"repo_id":"BOLAA","entity_id":"file:webshop/web_agent_site/engine/engine.py","uri":"program://BOLAA/file/webshop/web_agent_site/engine/engine.py","kind":"file","name":"webshop/web_agent_site/engine/engine.py","path":"webshop/web_agent_site/engine/engine.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"\"\"\"\n\"\"\"\nimport os\nimport re\nimport json\nimport random\nfrom collections import defaultdict\nfrom ast import literal_eval\nfrom decimal import Decimal\n\nimport cleantext\nfrom tqdm import tqdm\nfrom rank_bm25 import BM25Okapi\nfrom flask import render_template_string\nfrom rich import print\nfrom pyserini.search.lucene import LuceneSearcher\n\nfrom web_agent_site.utils import (\n BASE_DIR,\n DEFAULT_FILE_PATH,\n DEFAULT_REVIEW_PATH,","source_hash":"9b86ffc82951124f5c4a7eb8103de14100dbee11ba8869951ed6fb8feaeef804","truncated":false} {"repo_id":"BOLAA","entity_id":"file:webshop/web_agent_site/agents/shop_agent.py","uri":"program://BOLAA/file/webshop/web_agent_site/agents/shop_agent.py","kind":"file","name":"webshop/web_agent_site/agents/shop_agent.py","path":"webshop/web_agent_site/agents/shop_agent.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":11,"code":"class ShopAgent(object):\n def __init__(self):\n super().__init__()\n \n def forward(self, observation, available_actions):\n if available_actions['has_search_bar']:\n action = 'search[shoes]'\n else:\n action_arg = random.choice(available_actions['clickables'])\n action = f'click[{action_arg}]'\n return action","source_hash":"0dd7760516f35d34556413d4071b81dcca99abfd4b2cafb6536e7c0f27c8e579","truncated":false}