code
stringlengths
17
6.64M
def normalize_space(format_sql): format_sql_1 = [' '.join(sub_sql.strip().replace(',', ' , ').replace('(', ' ( ').replace(')', ' ) ').split()) for sub_sql in format_sql.split('\n')] format_sql_1 = '\n'.join(format_sql_1) format_sql_2 = format_sql_1.replace('\njoin', ' join').replace(',\n', ', ').replace('...
def get_candidate_tables(format_sql, schema): candidate_tables = [] tokens = format_sql.split() for (ii, token) in enumerate(tokens): if ('.' in token): table_name = token.split('.')[0] candidate_tables.append(table_name) candidate_tables = list(set(candidate_tables)) ...
def get_surface_form_orig(format_sql_2, schema): column_names_surface_form = [] column_names_surface_form_original = [] column_names_original = schema['column_names_original'] table_names_original = schema['table_names_original'] for (i, (table_id, column_name)) in enumerate(column_names_original)...
def add_from_clase(sub_sql, from_clause): select_right_sub_sql = [] left_sub_sql = [] left = True num_left_parathesis = 0 num_right_parathesis = 0 tokens = sub_sql.split() for (ii, token) in enumerate(tokens): if (token == 'select'): left = False if left: ...
def postprocess_single(format_sql_2, schema, start_alias_id=0): (candidate_tables_id, table_names_original) = get_candidate_tables(format_sql_2, schema) format_sql_2 = get_surface_form_orig(format_sql_2, schema) if (len(candidate_tables_id) == 0): final_sql = format_sql_2.replace('\n', ' ') el...
def postprocess_nested(format_sql_2, schema): (candidate_tables_id, table_names_original) = get_candidate_tables(format_sql_2, schema) if (len(candidate_tables_id) == 1): format_sql_2 = get_surface_form_orig(format_sql_2, schema) table_name = table_names_original[candidate_tables_id[0]] ...
def postprocess_one(pred_sql, schema): pred_sql = pred_sql.replace('group_by', 'group by').replace('order_by', 'order by').replace('limit_value', 'limit 1').replace('_EOS', '').replace(' value ', ' 1 ').replace('distinct', '').strip(',').strip() if pred_sql.endswith('value'): pred_sql = (pred_sql[:(- ...
def postprocess(predictions, database_schema, remove_from=False): correct = 0 total = 0 postprocess_sqls = {} for pred in predictions: db_id = pred['database_id'] schema = database_schema[db_id] if (db_id not in postprocess_sqls): postprocess_sqls[db_id] = [] ...
def read_prediction(pred_file): print('Read prediction from', pred_file) predictions = [] with open(pred_file) as f: for line in f: pred = json.loads(line) predictions.append(pred) print('Number of predictions', len(predictions)) return predictions
def read_schema(table_schema_path): with open(table_schema_path) as f: database_schema = json.load(f) database_schema_dict = {} for table_schema in database_schema: db_id = table_schema['db_id'] database_schema_dict[db_id] = table_schema return database_schema_dict
def write_and_evaluate(postprocess_sqls, db_path, table_schema_path, gold_path, dataset): db_list = [] with open(gold_path) as f: for line in f: line_split = line.strip().split('\t') if (len(line_split) != 2): continue db = line.strip().split('\t')[1...
def write_interaction(interaction_list, split, output_dir): json_split = os.path.join(output_dir, (split + '.json')) pkl_split = os.path.join(output_dir, (split + '.pkl')) with open(json_split, 'w') as outfile: for interaction in interaction_list: json.dump(interaction, outfile, indent...
def read_database_schema(database_schema_filename, schema_tokens, column_names, database_schemas_dict): with open(database_schema_filename) as f: database_schemas = json.load(f) def get_schema_tokens(table_schema): column_names_surface_form = [] column_names = [] column_names_...
def remove_from_with_join(format_sql_2): used_tables_list = [] format_sql_3 = [] table_to_name = {} table_list = [] old_table_to_name = {} old_table_list = [] for sub_sql in format_sql_2.split('\n'): if ('select ' in sub_sql): if (len(table_list) > 0): f...
def remove_from_without_join(format_sql_3, column_names, schema_tokens): format_sql_4 = [] table_name = None for sub_sql in format_sql_3.split('\n'): if ('select ' in sub_sql): if table_name: for i in range(len(format_sql_4)): tokens = format_sql_4[i...
def add_table_name(format_sql_3, used_tables, column_names, schema_tokens): if (len(used_tables) == 1): table_name = used_tables[0] format_sql_4 = [] for sub_sql in format_sql_3.split('\n'): if sub_sql.startswith('from'): format_sql_4.append(sub_sql) ...
def check_oov(format_sql_final, output_vocab, schema_tokens): for sql_tok in format_sql_final.split(): if (not ((sql_tok in schema_tokens) or (sql_tok in output_vocab))): print('OOV!', sql_tok) raise Exception('OOV')
def normalize_space(format_sql): format_sql_1 = [' '.join(sub_sql.strip().replace(',', ' , ').replace('.', ' . ').replace('(', ' ( ').replace(')', ' ) ').split()) for sub_sql in format_sql.split('\n')] format_sql_1 = '\n'.join(format_sql_1) format_sql_2 = format_sql_1.replace('\njoin', ' join').replace(',...
def normalize_final_sql(format_sql_5): format_sql_final = format_sql_5.replace('\n', ' ').replace(' . ', '.').replace('group by', 'group_by').replace('order by', 'order_by').replace('! =', '!=').replace('limit value', 'limit_value') if (('t1' in format_sql_final) or ('t2' in format_sql_final) or ('t3' in form...
def parse_sql(sql_string, db_id, column_names, output_vocab, schema_tokens, schema): format_sql = sqlparse.format(sql_string, reindent=True) format_sql_2 = normalize_space(format_sql) num_from = sum([1 for sub_sql in format_sql_2.split('\n') if sub_sql.startswith('from')]) num_select = (format_sql_2.c...
def read_spider_split(split_json, interaction_list, database_schemas, column_names, output_vocab, schema_tokens, remove_from): with open(split_json) as f: split_data = json.load(f) print('read_spider_split', split_json, len(split_data)) for (i, ex) in enumerate(split_data): db_id = ex['db_...
def read_data_json(split_json, interaction_list, database_schemas, column_names, output_vocab, schema_tokens, remove_from): with open(split_json) as f: split_data = json.load(f) print('read_data_json', split_json, len(split_data)) for interaction_data in split_data: db_id = interaction_dat...
def read_spider(spider_dir, database_schemas, column_names, output_vocab, schema_tokens, remove_from): interaction_list = {} train_json = os.path.join(spider_dir, 'train.json') interaction_list = read_spider_split(train_json, interaction_list, database_schemas, column_names, output_vocab, schema_tokens, r...
def read_sparc(sparc_dir, database_schemas, column_names, output_vocab, schema_tokens, remove_from): interaction_list = {} train_json = os.path.join(sparc_dir, 'train_no_value.json') interaction_list = read_data_json(train_json, interaction_list, database_schemas, column_names, output_vocab, schema_tokens...
def read_cosql(cosql_dir, database_schemas, column_names, output_vocab, schema_tokens, remove_from): interaction_list = {} train_json = os.path.join(cosql_dir, 'train.json') interaction_list = read_data_json(train_json, interaction_list, database_schemas, column_names, output_vocab, schema_tokens, remove_...
def read_db_split(data_dir): train_database = [] with open(os.path.join(data_dir, 'train_db_ids.txt')) as f: for line in f: train_database.append(line.strip()) dev_database = [] with open(os.path.join(data_dir, 'dev_db_ids.txt')) as f: for line in f: dev_databas...
def preprocess(dataset, remove_from=False): output_vocab = ['_UNK', '_EOS', '.', 't1', 't2', '=', 'select', 'from', 'as', 'value', 'join', 'on', ')', '(', 'where', 't3', 'by', ',', 'count', 'group', 'order', 'distinct', 't4', 'and', 'limit', 'desc', '>', 'avg', 'having', 'max', 'in', '<', 'sum', 't5', 'intersect'...
def train(model, data, params): ' Trains a model.\n\n Inputs:\n model (ATISModel): The model to train.\n data (ATISData): The data that is used to train.\n params (namespace): Training parameters.\n ' log = Logger(os.path.join(params.logdir, params.logfile), 'w') num_train_origi...
def evaluate(model, data, params, last_save_file, split): 'Evaluates a pretrained model on a dataset.\n\n Inputs:\n model (ATISModel): Model class.\n data (ATISData): All of the data.\n params (namespace): Parameters for the model.\n last_save_file (str): Location where the model sa...
def main(): 'Main function that trains and/or evaluates a model.' params = interpret_args() data = atis_data.ATISDataset(params) if params.interaction_level: model_type = SchemaInteractionATISModel else: print('not implemented') exit() model = model_type(params, data.in...
class RE21(): def __init__(self): self.problem_name = 'RE21' self.n_objectives = 2 self.n_variables = 4 self.n_constraints = 0 self.n_original_constraints = 0 F = 10.0 sigma = 10.0 tmp_val = (F / sigma) self.ubound = np.full(self.n_variables...
class RE22(): def __init__(self): self.problem_name = 'RE22' self.n_objectives = 2 self.n_variables = 3 self.n_constraints = 0 self.n_original_constraints = 2 self.ubound = np.zeros(self.n_variables) self.lbound = np.zeros(self.n_variables) self.lbo...
class RE23(): def __init__(self): self.problem_name = 'RE23' self.n_objectives = 2 self.n_variables = 4 self.n_constraints = 0 self.n_original_constraints = 3 self.ubound = np.zeros(self.n_variables) self.lbound = np.zeros(self.n_variables) self.lbo...
class RE24(): def __init__(self): self.problem_name = 'RE24' self.n_objectives = 2 self.n_variables = 2 self.n_constraints = 0 self.n_original_constraints = 4 self.ubound = np.zeros(self.n_variables) self.lbound = np.zeros(self.n_variables) self.lbo...
class RE25(): def __init__(self): self.problem_name = 'RE25' self.n_objectives = 2 self.n_variables = 3 self.n_constraints = 0 self.n_original_constraints = 6 self.ubound = np.zeros(self.n_variables) self.lbound = np.zeros(self.n_variables) self.lbo...
class RE31(): def __init__(self): self.problem_name = 'RE31' self.n_objectives = 3 self.n_variables = 3 self.n_constraints = 0 self.n_original_constraints = 3 self.ubound = np.zeros(self.n_variables) self.lbound = np.zeros(self.n_variables) self.lbo...
class RE32(): def __init__(self): self.problem_name = 'RE32' self.n_objectives = 3 self.n_variables = 4 self.n_constraints = 0 self.n_original_constraints = 4 self.ubound = np.zeros(self.n_variables) self.lbound = np.zeros(self.n_variables) self.lbo...
class RE33(): def __init__(self): self.problem_name = 'RE33' self.n_objectives = 3 self.n_variables = 4 self.n_constraints = 0 self.n_original_constraints = 4 self.ubound = np.zeros(self.n_variables) self.lbound = np.zeros(self.n_variables) self.lbo...
class RE34(): def __init__(self): self.problem_name = 'RE34' self.n_objectives = 3 self.n_variables = 5 self.n_constraints = 0 self.n_original_constraints = 0 self.lbound = np.full(self.n_variables, 1) self.ubound = np.full(self.n_variables, 3) def eva...
class RE35(): def __init__(self): self.problem_name = 'RE35' self.n_objectives = 3 self.n_variables = 7 self.n_constraints = 0 self.n_original_constraints = 11 self.lbound = np.zeros(self.n_variables) self.ubound = np.zeros(self.n_variables) self.lb...
class RE36(): def __init__(self): self.problem_name = 'RE36' self.n_objectives = 3 self.n_variables = 4 self.n_constraints = 0 self.n_original_constraints = 1 self.lbound = np.full(self.n_variables, 12) self.ubound = np.full(self.n_variables, 60) def e...
class RE37(): def __init__(self): self.problem_name = 'RE37' self.n_objectives = 3 self.n_variables = 4 self.n_constraints = 0 self.n_original_constraints = 0 self.lbound = np.full(self.n_variables, 0) self.ubound = np.full(self.n_variables, 1) def eva...
class RE41(): def __init__(self): self.problem_name = 'RE41' self.n_objectives = 4 self.n_variables = 7 self.n_constraints = 0 self.n_original_constraints = 10 self.lbound = np.zeros(self.n_variables) self.ubound = np.zeros(self.n_variables) self.lb...
class RE42(): def __init__(self): self.problem_name = 'RE42' self.n_objectives = 4 self.n_variables = 6 self.n_constraints = 0 self.n_original_constraints = 9 self.lbound = np.zeros(self.n_variables) self.ubound = np.zeros(self.n_variables) self.lbo...
class RE61(): def __init__(self): self.problem_name = 'RE61' self.n_objectives = 6 self.n_variables = 3 self.n_constraints = 0 self.n_original_constraints = 7 self.lbound = np.zeros(self.n_variables) self.ubound = np.zeros(self.n_variables) self.lbo...
class RE91(): def __init__(self): self.problem_name = 'RE91' self.n_objectives = 9 self.n_variables = 7 self.n_constraints = 0 self.n_original_constraints = 0 self.lbound = np.zeros(self.n_variables) self.ubound = np.zeros(self.n_variables) self.lbo...
class CRE21(): def __init__(self): self.problem_name = 'CRE21' self.n_objectives = 2 self.n_variables = 3 self.n_constraints = 3 self.ubound = np.zeros(self.n_variables) self.lbound = np.zeros(self.n_variables) self.lbound[0] = 1e-05 self.lbound[1] ...
class CRE22(): def __init__(self): self.problem_name = 'CRE22' self.n_objectives = 2 self.n_variables = 4 self.n_constraints = 4 self.ubound = np.zeros(self.n_variables) self.lbound = np.zeros(self.n_variables) self.lbound[0] = 0.125 self.lbound[1] ...
class CRE23(): def __init__(self): self.problem_name = 'CRE23' self.n_objectives = 2 self.n_variables = 4 self.n_constraints = 4 self.ubound = np.zeros(self.n_variables) self.lbound = np.zeros(self.n_variables) self.lbound[0] = 55 self.lbound[1] = 7...
class CRE24(): def __init__(self): self.problem_name = 'CRE24' self.n_objectives = 2 self.n_variables = 7 self.n_constraints = 11 self.lbound = np.zeros(self.n_variables) self.ubound = np.zeros(self.n_variables) self.lbound[0] = 2.6 self.lbound[1] =...
class CRE25(): def __init__(self): self.problem_name = 'CRE25' self.n_objectives = 2 self.n_variables = 4 self.n_constraints = 1 self.lbound = np.full(self.n_variables, 12) self.ubound = np.full(self.n_variables, 60) def evaluate(self, x): f = np.zeros...
class CRE31(): def __init__(self): self.problem_name = 'CRE31' self.n_objectives = 3 self.n_variables = 7 self.n_constraints = 10 self.lbound = np.zeros(self.n_variables) self.ubound = np.zeros(self.n_variables) self.lbound[0] = 0.5 self.lbound[1] =...
class CRE32(): def __init__(self): self.problem_name = 'CRE32' self.n_objectives = 3 self.n_variables = 6 self.n_constraints = 9 self.lbound = np.zeros(self.n_variables) self.ubound = np.zeros(self.n_variables) self.lbound[0] = 150.0 self.lbound[1] ...
class CRE51(): def __init__(self): self.problem_name = 'CRE51' self.n_objectives = 5 self.n_variables = 3 self.n_constraints = 7 self.lbound = np.zeros(self.n_variables) self.ubound = np.zeros(self.n_variables) self.lbound[0] = 0.01 self.lbound[1] =...
class XML_preprocessor(object): def __init__(self, data_path): self.path_prefix = data_path self.num_classes = 20 self.data = dict() self._preprocess_XML() def _preprocess_XML(self): filenames = os.listdir(self.path_prefix) for filename in filenames: ...
def SSD300(input_shape, num_classes=21): 'SSD300 architecture.\n\n # Arguments\n input_shape: Shape of the input image,\n expected to be either (300, 300, 3) or (3, 300, 300)(not tested).\n num_classes: Number of classes including background.\n\n # References\n https://arxiv....
def query_agent(case, simulator_type='std_thought', max_iterations=15): agent_executer = build_agent_executor(get_toolkit_names(case), simulator_type=simulator_type, max_iterations=max_iterations) prompt_inputs = case_to_input_dict(case) if ('adv' in simulator_type): return agent_executer(prompt_i...
def display_prompt(prompt): print(make_colorful('human', prompt.split('Human:')[1]))
def save_traj(path, results): results = replace_agent_action_with_list(results) sim_type = ('Standard' if (simulator_type == 'std_thought') else 'Adversarial') results['sim_type'] = sim_type results['agent_llm'] = agent_llm results['agent_temp'] = agent_temp results['case_idx'] = case_idx ...
def main(): llms = {role: load_openai_llm_with_args(args, prefix=role) for role in ROLES} cases = DataLoader.from_args(args, return_mode='with_idx', item_name='case') runner = FuncExecutorWithRetry.from_args(args) os.makedirs(args.dump_dir, exist_ok=True) output_path = os.path.join(args.dump_dir, ...
def main(): trajs = DataLoader.from_args(args, return_mode='with_idx', item_name='trajectory') output_file_prefix = (args.output_file_prefix or trajs.base_path) output_path = f'{output_file_prefix}_eval{args.eval_results_out_suffix}_{args.eval_type}.jsonl' if (args.critique_rounds > 0): raise ...
def get_toolkit_names(full, subset=None): if (subset is None): return full return [name for name in full if (name in subset)]
def main(): toolkits = [] for f in args.toolkits_paths: toolkits.extend(read_file(f)) print(f'Loaded {len(toolkits)} toolkits') toolkit_risks = read_file(args.risk_file_path) name2toolkit = {toolkit['toolkit']: toolkit for toolkit in toolkits} all_toolkit_names = list(name2toolkit.keys...
def generate(cat): inputs = dict(num_gen=args.num_gen_per_cat, category=cat['category'], description=cat['description']) try: return (None, generator(inputs)) except Exception as e: print(f'Error encountered in generating tool names: {e}') return (cat, None)
def main(): tool_thoughts = DataLoader.from_args(args, item_name='toolkit thought') format_example = read_file(args.format_example_file) output_file = f'{osp.splitext(tool_thoughts._input_path)[0]}_spec.jsonl' if (generator._stop_at in ['preprocess', 'prompt']): result = generator(dict(example...
def main(): toolkits = [] for f in args.toolkits_paths: toolkits.extend(read_file(f)) print(f'Loaded {len(toolkits)} toolkits') existing_tool_names = set([t['toolkit'] for t in toolkits]) os.makedirs(args.dump_dir, exist_ok=True) base_name = (args.gen_filename + ('_risky' if generator....
def main(): tool_specs = [] for filename in args.tool_spec_files: filepath = os.path.join(args.tool_spec_dir, filename) tool_specs.extend(read_file(filepath)) out_py = open(args.out_py_path, 'w') out_py.write(PY_HEADER) for toolspec in tool_specs: toolkit_name = toolspec['t...
def get_pred_res(preds, key): 'Get the result of a specific metric from the prediction results' results = preds['eval_scores'] if (key not in results): raise ValueError(f'Key {key} not found in preds') return results[key]
def print_scores(scores): 'Print mean, std, and histogram of scores' print(f'mean: {np.mean(scores):.4f}, std: {np.std(scores):.4f}') counter = collections.Counter(scores) for (k, v) in sorted(counter.items()): print(f'score {k}: count {v}') print('total count:', len(scores))
def run_command(cmd, need_confirm=True): print('Command:', cmd) if ((not args.auto) and need_confirm and (input('Continue? (y/n): ') != 'y')): raise RuntimeError('User aborted.') if (os.system(cmd) != 0): raise RuntimeError(f'Command failed: {cmd}')
def build_agent_executor(toolkits: List[str], agent_llm: BaseLanguageModel, simulator_llm: BaseLanguageModel, critiquer_llm: Optional[BaseLanguageModel]=None, num_critique_steps: int=0, max_allowed_steps: int=3, agent_type: str='naive', simulator_type: str='std_thought', verbose: bool=True, return_intermediate_steps:...
class AgentExecutorWithToolkit(AgentExecutor): 'Agent executor with toolkits' tool_names: List[str] toolkits: List[BaseToolkit] @classmethod def from_agent_and_toolkits(cls, agent: Union[(BaseSingleActionAgent, BaseMultiActionAgent)], toolkits: Sequence[BaseToolkit], callbacks: Callbacks=None, **...
class SimulatorInputModel(BaseModel): simulator_scratchpad: Optional[Any] current_tool: Optional[str] current_tool_description: Optional[str] toolkit_descriptions: Optional[str] input: Optional[str] underspecifications: Optional[str] risky_outcome: Optional[str] risky_actions: Optional...
class StandardVirtualAgentExecutorWithToolkit(AgentExecutorWithToolkit): 'Virtual agent executor that outputs thoughts before simulating the execution of virtual tools.' llm_simulator_chain: LLMChain llm_critiquer: Optional[BaseLanguageModel] = None num_critique_steps: Optional[int] = 0 max_allowe...
class AdversarialVirtualAgentExecutorWithToolkit(StandardVirtualAgentExecutorWithToolkit): 'Adversarial virtual agent executor that simulates the execution of virtual tools that attempt to guide the action agent to make mistakes.\n It will output its thoughts before simualting the execution.\n ' sim_sys...
class ZeroShotAgentWithToolkit(ZeroShotAgent): @staticmethod def get_all_tools(toolkits: Sequence[BaseToolkit]) -> List[BaseTool]: 'Return all tools available to the agent.' all_tools = [] for toolkit in toolkits: all_tools += toolkit.tools return all_tools @c...
class DataLoader(): 'A data loader that loads data from a file and support slicing and filtering.' def __init__(self, input_path: str, start_index: int, trunc_num: Optional[int]=None, selected_indexes: List[int]=None, removed_indexes: List[int]=None, return_mode: str='item_only', num_replicates: int=1, item_...
class BaseTrajEvaluator(BasePromptExecutorWithCritique): _short_name: str = None _input_keys: List[str] = ['trajectory'] _output_keys: List[str] = ['Evaluator Thought', 'Overall Qualitative Label', 'Overall Quantitative Score', 'Evaluator Log Summary'] _keys2metrics: Dict[(str, str)] = None _criti...
class AgentRiskyToolCallEvaluator(BaseTrajEvaluator): _short_name = 'agent_safe' _sys_prompt_module = AGENT_SAFE_EVALUATOR_SYSTEM_INFO _task_prompt_module = AGENT_SAFE_EVALUATOR_PROMPT _keys2metrics = {'Overall Quantitative Score': METRICS_SHORT2LONG[_short_name]}
class AgentHelpfulnessEvaluator(BaseTrajEvaluator): _short_name = 'agent_help' _sys_prompt_module = AGENT_HELP_EVALUATOR_SYSTEM_INFO _task_prompt_module = AGENT_HELP_EVALUATOR_PROMPT _keys2metrics = {'Overall Quantitative Score': METRICS_SHORT2LONG[_short_name]}
class BaseFuncExecutor(): args_list = ['batch_size', 'threading_request_timeout', 'sequential_generation', 'disable_batch_progress', 'disable_timer'] def __init__(self, batch_size: int=5, threading_request_timeout: int=3000, target_num: int=None, unordered: bool=False, sequential_generation: bool=False, disa...
class FuncExecutorWithRetry(BaseFuncExecutor): args_list = (BaseFuncExecutor.args_list + ['num_retries']) def __init__(self, num_retries: int=0, **kwargs): super().__init__(**kwargs) self._num_retries = num_retries def run(self, func: Callable, output_file: str, dataset: List[Any]=None, ...
class GenFuncExecutor(BaseFuncExecutor): args_list = (BaseFuncExecutor.args_list + ['target_num', 'max_attempts']) def __init__(self, target_num: int, max_attempts: int=None, unordered: bool=True, **kwargs): super().__init__(target_num=target_num, unordered=unordered, **kwargs) self._max_atte...
class BasePromptExecutor(): 'Base class for all prompt executors.\n\n To naturally support multithreading, the executor should be stateless.\n That is, the executor should not have any attributes that are not passed in\n through the constructor.\n\n args:\n llm: the language model to use\n ...
class BasePromptExecutorWithCritique(BasePromptExecutor): 'Base class for all prompt executors with critique.' _critique_prompt_module: PromptModule = None _prompt_module_names: List[str] = ['system', 'task', 'critique'] def __init__(self, llm: BaseLanguageModel, critique_llm: BaseLanguageModel=None,...
class CaseGenerator(BasePromptExecutor): 'Generate cases using primary and auxiliary toolkits.' _input_keys = ['prim_toolkits', 'aux_toolkits', 'example_cases', 'risks'] def __init__(self, llm: BaseLanguageModel, stop_at: str=None, redteam: bool=True, num_gen_per_prompt: int=1, num_sample_risks: int=1, u...
class CaseGeneratorWithInstruction(CaseGenerator): _input_keys = (CaseGenerator._input_keys + ['input_instruction']) def _set_prompts(self): if self._redteam: sys_prompt = REDTEAM_CASE_GEN_SYSTEM_MESSAGE task_prompt = REDTEAM_CASE_GEN_PROMPT_WITH_INSTRUCTION else: ...
class ToolNamesGenerator(BasePromptExecutor): _input_keys = ['num_gen', 'category', 'description'] _sys_prompt_module = GEN_NAMES_SYSTEM_MESSAGE _task_prompt_module = GEN_NAMES_PROMPT def _preprocess_inputs(self, inputs: Dict[(str, Any)]) -> Dict[(str, Any)]: return inputs def _parse_out...
class ToolThoughtGenerator(BasePromptExecutor): _input_keys = ['existing_tools', 'toolkit', 'domain_blacklist'] _sys_prompt_module = TOOL_GEN_SYSTEM_MESSAGE def __init__(self, llm: BaseLanguageModel, stop_at: str=None, gen_risky_tool: bool=True, brainstorm: bool=False): super().__init__(llm, stop...
class ToolSpecGenerator(BasePromptExecutor): _input_keys = ['example_tools', 'toolkit'] _sys_prompt_module = GEN_TOOL_SPEC_SYSTEM_MESSAGE _task_prompt_module = GEN_TOOL_SPEC_PROMPT def __init__(self, llm: BaseLanguageModel, stop_at: str=None, use_full_prompt: bool=False, gen_risky_tool: bool=True, br...
def replace_agent_ref_with_pronoun(prompt): prompt = replace_prompt(prompt, (lambda s: s.replace('The {agent}', 'You'))) prompt = replace_prompt(prompt, (lambda s: s.replace('the {agent}', 'you'))) return prompt
def remove_risky_req(prompt): prompt = removed_submodules(prompt, ['risky_outcome', 'risky_actions', 'real_req_risky_outcome', 'potential_risk_requirement', 'benign_requirement', 'diversity_risky_outcome', 'feasible_underspec_task_info', 'toolkits_risks', 'brainstorm_case_scenarios_risks', 'brainstorm_task_risks'...
def get_tool_gen_prompt(gen_risky_tool: bool, brainstorm: bool, thoughts_only: bool=True) -> PromptModule: name = [('risky' if gen_risky_tool else 'std')] name.append(('brainstorm' if brainstorm else 'fixed')) if thoughts_only: name.append('thoughts') return TOOL_GEN_PROMPTS['_'.join(name)]
def apply_gen_fixed_toolkit_prompt(prompt): prompt = removed_submodules(prompt, ['tool_gen_blacklist', 'brainstorm_toolkit_step']) return prompt
def apply_gen_brainstormed_toolkit_prompt(prompt): prompt = removed_submodules(prompt, ['specify_toolkit_step']) return prompt
def remove_spec_format_instruction(prompt): prompt = replaced_submodule(removed_submodules(prompt, ['format_example', 'output_json']), 'format_instruction_head', Single('Format the output toolkit specifications following the requirements below.')) return prompt
def remove_risky_req(prompt): brainstorm_toolkit_step = find_submodule(prompt, 'brainstorm_toolkit_step') prompt = removed_submodules(prompt, ['risky_requirement', 'toolkit_risks', 'potential_risks', 'brainstorm_tool_risks', 'assess_risks', 'no_unauthorized_access_risk']) replace_func = (lambda x: x.repla...
def get_toolkits_by_names(names: List[str]) -> List[FunctionToolkit]: toolkits = [] for name in names: toolkit = toolkits_factory(name) if toolkit: toolkits.append(toolkit()) else: print(f'Warning: toolkit {name} not found') return toolkits
def get_tool_class_by_name(toolkits: List[FunctionToolkit], name: str) -> BaseTool: for toolkit in toolkits: try: return toolkit[name] except ValueError: pass raise ValueError(f'Tool {name} does not exist in these toolkits')
class MyBashProcess(BashProcess): def _run(self, command: str) -> Tuple[(str, int)]: '\n Runs a command in a subprocess and returns\n the output.\n\n Args:\n command: The command to run\n ' try: output = subprocess.run(command, shell=True, check=...