| import argparse |
| import os |
| import json |
| from tqdm import tqdm |
| from planner import get_answer_llamacpp, get_answer_openai |
| from openai import OpenAI |
| from dotenv import load_dotenv |
| from multiprocessing import Pool, Manager |
|
|
| |
| parser = argparse.ArgumentParser() |
| parser.add_argument('--validator_select', type=str, default='data/multi-agents/validator/gpt-4o-mini-validator_select_bird_with_evidence_train.jsonl') |
| parser.add_argument('--validator_condition', type=str, default='data/multi-agents/validator/gpt-4o-mini-validator_condition_bird_with_evidence_train.jsonl') |
| parser.add_argument('--validator_join', type=str, default='data/multi-agents/validator/gpt-4o-mini-validator_join_bird_with_evidence_train.jsonl') |
| parser.add_argument('--validator_order', type=str, default='data/multi-agents/validator/gpt-4o-mini-validator_order_bird_with_evidence_train.jsonl') |
| parser.add_argument('--output_file', type=str, default='./data/multi-agents/fixed/gpt-4o-mini-fixed-bird_with_evidence_train.jsonl') |
| parser.add_argument('--endpoint_type', type=str, default='openai', choices=['openai', 'vllm']) |
| args = parser.parse_args() |
|
|
| |
| class FixAgent: |
| def __init__(self, prompt_template, endpoint_type='llamacpp'): |
| self.prompt_template = prompt_template |
|
|
| load_dotenv() |
|
|
| if endpoint_type == 'llamacpp': |
| self.get_answer = get_answer_llamacpp |
| elif endpoint_type == 'vllm': |
| |
| client = OpenAI( |
| base_url="http://localhost:8003/v1", |
| api_key="no-key", |
| ) |
| self.get_answer = lambda x: get_answer_openai(client, x, model='Qwen/Qwen2.5-14B-Instruct/') |
| elif endpoint_type == 'openai': |
| client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) |
| self.get_answer = lambda x: get_answer_openai(client, x) |
|
|
| def generate(self, sample, feedback_select, feedback_condition, feedback_join, feedback_order): |
| prompt = self.prompt_template.format( |
| schema=sample['schema_sequence'], |
| question=sample['question'], |
| evidence=sample['evidence'], |
| sql_query=sample['sql'], |
| execution_response=sample['pred_result'], |
| feedback_select=feedback_select, |
| feedback_condition=feedback_condition, |
| feedback_join=feedback_join, |
| feedback_order=feedback_order |
| ) |
| answer = self.get_answer([{"role": "user", "content": prompt}]) |
| return answer |
|
|
|
|
| |
| PROMPT = """You are a SQL tutor that helps fixing the SQL query generated by a student. Given a database schema and a question with external knowledge. Generate Fixed SQL query based on the feedback. Write the SQL query directly, do not add more thoughts. |
| |
| {schema} |
| |
| Question: {question} |
| External knowledge: {evidence} |
| |
| Generated SQL query from student with the execution response. |
| SQL query: {sql_query} |
| |
| Execution response [written in pandas format]: |
| {execution_response} |
| |
| The feedback for the SQL query: |
| {feedback_select} |
| |
| {feedback_condition} |
| |
| {feedback_join} |
| |
| {feedback_order} |
| |
| FIXED SQL:""" |
|
|
| |
| input_files = [ |
| args.validator_select, |
| args.validator_condition, |
| args.validator_join, |
| args.validator_order |
| ] |
|
|
| |
| input_data = [[], [], [], []] |
| for i, input_file in enumerate(input_files): |
| with open(input_file, 'r') as f: |
| for line in f: |
| input_data[i].append(json.loads(line)) |
|
|
| |
| |
| question_select = [sample['question'] for sample in input_data[0]] |
| question_condition = [sample['question'] for sample in input_data[1]] |
| question_join = [sample['question'] for sample in input_data[2]] |
| question_order = [sample['question'] for sample in input_data[3]] |
|
|
| subset_questions = set(question_select) & set(question_condition) & set(question_join) & set(question_order) |
|
|
| |
| for i in range(len(input_data)): |
| input_data[i] = [sample for sample in input_data[i] if sample['question'] in subset_questions] |
|
|
| |
| |
| question_to_sample = {} |
| for i in [0, 2, 3]: |
| question_to_sample[i] = {sample['question']: sample for sample in input_data[i]} |
|
|
| |
| ordered_questions = [sample['question'] for sample in input_data[1]] |
| for i in [0, 2, 3]: |
| input_data[i] = [question_to_sample[i][question] for question in ordered_questions] |
|
|
| |
| for i in range(len(input_data)): |
| print(f"Length of input_data[{i}]: {len(input_data[i])}") |
|
|
| |
| for i in tqdm(range(len(input_data[0])), desc="Checking input alignment"): |
| question_0 = input_data[0][i]['question'] |
| question_1 = input_data[1][i]['question'] |
| question_2 = input_data[2][i]['question'] |
| question_3 = input_data[3][i]['question'] |
| assert question_0 == question_1 == question_2 == question_3 |
|
|
| |
| processed_questions = set() |
| if os.path.exists(args.output_file): |
| with open(args.output_file, 'r') as f: |
| for line in f: |
| processed_sample = json.loads(line) |
| processed_questions.add(processed_sample['question']) |
|
|
| |
| os.makedirs(os.path.dirname(args.output_file), exist_ok=True) |
|
|
| |
| def main(): |
| |
| indices_to_process = [i for i in range(len(input_data[0])) if input_data[0][i]['question'] not in processed_questions] |
| data_to_process = [] |
| for i in indices_to_process: |
| sample_select = input_data[0][i] |
| if sample_select['question'] in processed_questions: |
| continue |
| sample_condition = input_data[1][i] |
| sample_join = input_data[2][i] |
| sample_order = input_data[3][i] |
| data_to_process.append((sample_select, sample_condition, sample_join, sample_order)) |
|
|
| with Manager() as manager: |
| lock = manager.Lock() |
| output_file_path = args.output_file |
| with Pool(processes=8, initializer=init_process, initargs=(output_file_path, lock, args.endpoint_type)) as pool: |
| list(tqdm( |
| pool.imap_unordered(process_sample, data_to_process), |
| total=len(data_to_process), |
| desc="Generating Fixed SQL" |
| )) |
|
|
| |
| def init_process(output_file_path_arg, lock_arg, endpoint_type_arg): |
| global output_file_path |
| global lock |
| global fixed_sql_agent |
| output_file_path = output_file_path_arg |
| lock = lock_arg |
| fixed_sql_agent = FixAgent(PROMPT, endpoint_type=endpoint_type_arg) |
|
|
| |
| def process_sample(samples): |
| global output_file_path |
| global lock |
| global fixed_sql_agent |
| sample_select, sample_condition, sample_join, sample_order = samples |
|
|
| select_correct = sample_select['feedback_conclude'] |
| condition_correct = sample_condition['feedback_conclude'] |
| join_correct = sample_join['feedback_conclude'] |
| order_correct = sample_order['feedback_conclude'] if sample_order['validator_order'] is not None else True |
|
|
| print(select_correct, condition_correct, join_correct, order_correct) |
|
|
| if select_correct and condition_correct and join_correct and order_correct: |
| return None |
|
|
| feedback_select = sample_select['validator_select'] |
| feedback_condition = sample_condition['validator_condition'] |
| feedback_join = sample_join['validator_join'] |
| feedback_order = sample_order['validator_order'] |
|
|
| if feedback_select is None: |
| feedback_select = "SELECT.\nNone" |
| if feedback_condition is None: |
| feedback_condition = "CONDITION.\nNone" |
| if feedback_join is None: |
| feedback_join = "JOIN.\nNone" |
| if feedback_order is None: |
| feedback_order = "ORDER BY.\nNone" |
|
|
| sample_select['validator_condition'] = sample_condition['validator_condition'] |
| sample_select['validator_join'] = sample_join['validator_join'] |
| sample_select['validator_order'] = sample_order['validator_order'] |
|
|
| |
| fixed_sql = fixed_sql_agent.generate(sample_select, feedback_select, feedback_condition, feedback_join, feedback_order) |
| sample_select['fixed_sql'] = fixed_sql |
|
|
| |
| result = json.dumps(sample_select) |
| with lock: |
| with open(output_file_path, 'a') as output_fp: |
| output_fp.write(result + '\n') |
|
|
| |
| if __name__ == "__main__": |
| main() |
|
|