|
| 1 | +import argparse |
| 2 | +import json |
| 3 | +import os |
| 4 | +import time |
| 5 | + |
| 6 | +from collections import defaultdict |
| 7 | +from multiprocessing.dummy import Pool |
| 8 | + |
| 9 | +from dotenv import load_dotenv |
| 10 | +from openai import OpenAI |
| 11 | +from tenacity import retry, stop_after_attempt, wait_random_exponential |
| 12 | +from tqdm import tqdm |
| 13 | + |
| 14 | + |
| 15 | +load_dotenv() |
| 16 | + |
| 17 | +# Retry policy constants |
| 18 | +WAIT_MIN = 5 # minimum backoff delay in seconds |
| 19 | +WAIT_MAX = 30 # maximum backoff delay in seconds |
| 20 | +MAX_TRIES = 10 # maximum number of retry attempts |
| 21 | + |
| 22 | +WORKERS = 5 # number of parallel worker processes |
| 23 | + |
| 24 | +ANSWER_PROMPT = """ |
| 25 | + You are an intelligent memory assistant tasked with retrieving accurate information from conversation memories. |
| 26 | +
|
| 27 | + # CONTEXT: |
| 28 | + You have access to memories from a conversation. These memories contain |
| 29 | + timestamped information that may be relevant to answering the question. |
| 30 | +
|
| 31 | + # INSTRUCTIONS: |
| 32 | + 1. Carefully analyze all provided memories |
| 33 | + 2. Pay special attention to the timestamps to determine the answer |
| 34 | + 3. If the question asks about a specific event or fact, look for direct evidence in the memories |
| 35 | + 4. If the memories contain contradictory information, prioritize the most recent memory |
| 36 | + 5. If there is a question about time references (like "last year", "two months ago", etc.), |
| 37 | + calculate the actual date based on the memory timestamp. For example, if a memory from |
| 38 | + 4 May 2022 mentions "went to India last year," then the trip occurred in 2021. |
| 39 | + 6. Always convert relative time references to specific dates, months, or years. For example, |
| 40 | + convert "last year" to "2022" or "two months ago" to "March 2023" based on the memory |
| 41 | + timestamp. Ignore the reference while answering the question. |
| 42 | + 7. Focus only on the content of the memories. Do not confuse character |
| 43 | + names mentioned in memories with the actual users who created those memories. |
| 44 | + 8. The answer should be less than 5-6 words. |
| 45 | +
|
| 46 | + # APPROACH (Think step by step): |
| 47 | + 1. First, examine all memories that contain information related to the question |
| 48 | + 2. Examine the timestamps and content of these memories carefully |
| 49 | + 3. Look for explicit mentions of dates, times, locations, or events that answer the question |
| 50 | + 4. If the answer requires calculation (e.g., converting relative time references), show your work |
| 51 | + 5. Formulate a precise, concise answer based solely on the evidence in the memories |
| 52 | + 6. Double-check that your answer directly addresses the question asked |
| 53 | + 7. Ensure your final answer is specific and avoids vague time references |
| 54 | +
|
| 55 | + Memories: |
| 56 | +
|
| 57 | + {context} |
| 58 | +
|
| 59 | + Question: {question} |
| 60 | + Answer: |
| 61 | + """ |
| 62 | + |
| 63 | + |
| 64 | +class OpenAIPredict: |
| 65 | + def __init__(self, model="gpt-4o-mini"): |
| 66 | + self.model = model |
| 67 | + self.openai_client = OpenAI( |
| 68 | + api_key=os.getenv("OPENAI_API_KEY"), base_url=os.getenv("OPENAI_BASE_URL") |
| 69 | + ) |
| 70 | + self.results = defaultdict(list) |
| 71 | + |
| 72 | + def search_memory(self, idx): |
| 73 | + with open(f"openai_memory/{idx}.txt", encoding="utf-8") as file: |
| 74 | + memories = file.read().strip().replace("\n\n", "\n") |
| 75 | + |
| 76 | + return memories, 0 |
| 77 | + |
| 78 | + def process_question(self, val, idx): |
| 79 | + question = val.get("question", "") |
| 80 | + answer = val.get("answer", "") |
| 81 | + category = val.get("category", -1) |
| 82 | + |
| 83 | + response, search_memory_time, response_time, context = self.answer_question(idx, question) |
| 84 | + |
| 85 | + result = { |
| 86 | + "question": question, |
| 87 | + "answer": response, |
| 88 | + "category": category, |
| 89 | + "golden_answer": answer, |
| 90 | + "search_context": context, |
| 91 | + "response_duration_ms": response_time, |
| 92 | + "search_duration_ms": search_memory_time, |
| 93 | + } |
| 94 | + |
| 95 | + return result |
| 96 | + |
| 97 | + @retry( |
| 98 | + wait=wait_random_exponential(min=WAIT_MIN, max=WAIT_MAX), |
| 99 | + stop=stop_after_attempt(MAX_TRIES), |
| 100 | + reraise=True, |
| 101 | + ) |
| 102 | + def answer_question(self, idx, question): |
| 103 | + memories, search_memory_time = self.search_memory(idx) |
| 104 | + |
| 105 | + answer_prompt = ANSWER_PROMPT.format(context=memories, question=question) |
| 106 | + |
| 107 | + t1 = time.time() |
| 108 | + response = self.openai_client.chat.completions.create( |
| 109 | + model=self.model, |
| 110 | + messages=[{"role": "system", "content": answer_prompt}], |
| 111 | + temperature=0.0, |
| 112 | + ) |
| 113 | + t2 = time.time() |
| 114 | + response_time = (t2 - t1) * 1000 |
| 115 | + return response.choices[0].message.content, search_memory_time, response_time, memories |
| 116 | + |
| 117 | + def process_data_file(self, file_path, output_file_path): |
| 118 | + with open(file_path, encoding="utf-8") as f: |
| 119 | + data = json.load(f) |
| 120 | + |
| 121 | + # Function to process each conversation |
| 122 | + def process_conversation(item): |
| 123 | + idx, conversation = item |
| 124 | + results_for_conversation = [] |
| 125 | + |
| 126 | + # Process each question in the conversation |
| 127 | + for question_item in tqdm( |
| 128 | + conversation["qa"], desc=f"Processing questions for conversation {idx}", leave=False |
| 129 | + ): |
| 130 | + if int(question_item.get("category", "")) == 5: |
| 131 | + continue |
| 132 | + result = self.process_question(question_item, idx) |
| 133 | + results_for_conversation.append(result) |
| 134 | + |
| 135 | + return idx, results_for_conversation |
| 136 | + |
| 137 | + # Use multiprocessing to process the conversations in parallel |
| 138 | + with Pool(processes=WORKERS) as pool: |
| 139 | + results = list( |
| 140 | + tqdm( |
| 141 | + pool.imap(process_conversation, list(enumerate(data))), |
| 142 | + total=len(data), |
| 143 | + desc="Processing conversations", |
| 144 | + ) |
| 145 | + ) |
| 146 | + |
| 147 | + # Reorganize results and store them in self.results |
| 148 | + for idx, results_for_conversation in results: |
| 149 | + self.results[f"locomo_exp_user_{idx}"] = results_for_conversation |
| 150 | + |
| 151 | + # Save results to output file |
| 152 | + with open(output_file_path, "w") as f: |
| 153 | + json.dump(self.results, f, indent=4) |
| 154 | + |
| 155 | + |
| 156 | +def main(version): |
| 157 | + os.makedirs(f"results/locomo/openai-{version}/", exist_ok=True) |
| 158 | + output_file_path = f"results/locomo/openai-{version}/openai_locomo_responses.json" |
| 159 | + openai_predict = OpenAIPredict() |
| 160 | + openai_predict.process_data_file("data/locomo/locomo10.json", output_file_path) |
| 161 | + |
| 162 | + |
| 163 | +if __name__ == "__main__": |
| 164 | + parser = argparse.ArgumentParser() |
| 165 | + parser.add_argument( |
| 166 | + "--version", |
| 167 | + type=str, |
| 168 | + default="default", |
| 169 | + help="Version identifier for loading results (e.g., 1010)", |
| 170 | + ) |
| 171 | + args = parser.parse_args() |
| 172 | + version = args.version |
| 173 | + main(version) |
0 commit comments