Update app.py
Browse files
app.py
CHANGED
|
@@ -12,30 +12,36 @@ from openai import OpenAI
|
|
| 12 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 13 |
OPENAI_FALLBACK_KEY = "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" # <<< Replace with your actual key here
|
| 14 |
|
| 15 |
-
# --- OpenAI Agent with
|
| 16 |
class OpenAIAgent:
|
| 17 |
def __init__(self, model="gpt-4"):
|
| 18 |
self.model = model
|
| 19 |
self.system_prompt = (
|
| 20 |
"You are a precise assistant that always returns a single, direct answer, with no explanation or justification. "
|
| 21 |
-
"If the task
|
| 22 |
-
"
|
| 23 |
-
"
|
| 24 |
)
|
| 25 |
-
|
| 26 |
-
# Use env key or fallback
|
| 27 |
api_key = os.getenv("OPENAI_API_KEY") or OPENAI_FALLBACK_KEY
|
| 28 |
if not api_key or "sk-" not in api_key:
|
| 29 |
raise ValueError("A valid OpenAI API key must be set in the environment or OPENAI_FALLBACK_KEY.")
|
| 30 |
self.client = OpenAI(api_key=api_key)
|
| 31 |
|
| 32 |
-
def __call__(self, question: str, task_id: str = None) -> str:
|
| 33 |
context = ""
|
| 34 |
-
if task_id:
|
| 35 |
try:
|
| 36 |
context = self._fetch_file_context(task_id)
|
| 37 |
except Exception as e:
|
| 38 |
print(f"Warning: Failed to fetch or parse file for task {task_id}: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
user_input = f"{question}\n\nAdditional context:\n{context}" if context else question
|
| 40 |
return self._call_openai(user_input)
|
| 41 |
|
|
@@ -71,10 +77,10 @@ class OpenAIAgent:
|
|
| 71 |
|
| 72 |
if extension == ".pdf":
|
| 73 |
return self._parse_pdf(tmp_file.name)
|
| 74 |
-
elif extension in [".txt", ".csv"]:
|
| 75 |
return response.text
|
| 76 |
else:
|
| 77 |
-
return f"[Non-text file of type {extension},
|
| 78 |
|
| 79 |
def _parse_pdf(self, filepath):
|
| 80 |
doc = fitz.open(filepath)
|
|
@@ -114,10 +120,11 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 114 |
for item in questions_data:
|
| 115 |
task_id = item.get("task_id")
|
| 116 |
question_text = item.get("question")
|
|
|
|
| 117 |
if not task_id or question_text is None:
|
| 118 |
continue
|
| 119 |
try:
|
| 120 |
-
submitted_answer = agent(question_text, task_id=task_id)
|
| 121 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 122 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 123 |
except Exception as e:
|
|
|
|
| 12 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 13 |
OPENAI_FALLBACK_KEY = "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" # <<< Replace with your actual key here
|
| 14 |
|
| 15 |
+
# --- OpenAI Agent with enhanced formatting and logic ---
|
| 16 |
class OpenAIAgent:
|
| 17 |
def __init__(self, model="gpt-4"):
|
| 18 |
self.model = model
|
| 19 |
self.system_prompt = (
|
| 20 |
"You are a precise assistant that always returns a single, direct answer, with no explanation or justification. "
|
| 21 |
+
"If the task asks for a list, format it exactly as instructed (e.g., comma-separated, alphabetized). "
|
| 22 |
+
"If there is a file missing, infer the answer using the question context. "
|
| 23 |
+
"Avoid all disclaimers, apologies, or messages about being a language model."
|
| 24 |
)
|
|
|
|
|
|
|
| 25 |
api_key = os.getenv("OPENAI_API_KEY") or OPENAI_FALLBACK_KEY
|
| 26 |
if not api_key or "sk-" not in api_key:
|
| 27 |
raise ValueError("A valid OpenAI API key must be set in the environment or OPENAI_FALLBACK_KEY.")
|
| 28 |
self.client = OpenAI(api_key=api_key)
|
| 29 |
|
| 30 |
+
def __call__(self, question: str, task_id: str = None, file_name: str = "") -> str:
|
| 31 |
context = ""
|
| 32 |
+
if task_id and file_name:
|
| 33 |
try:
|
| 34 |
context = self._fetch_file_context(task_id)
|
| 35 |
except Exception as e:
|
| 36 |
print(f"Warning: Failed to fetch or parse file for task {task_id}: {e}")
|
| 37 |
+
# Add custom cues based on the question content
|
| 38 |
+
if "comma separated" in question.lower():
|
| 39 |
+
question = "Format your answer as a comma-separated list in alphabetical order.\n\n" + question
|
| 40 |
+
if "only list the ingredients" in question.lower():
|
| 41 |
+
question = "Output just the ingredient names, comma-separated.\n\n" + question
|
| 42 |
+
if "numeric output" in question.lower():
|
| 43 |
+
question = "Only provide the final numeric result, no units or explanation.\n\n" + question
|
| 44 |
+
|
| 45 |
user_input = f"{question}\n\nAdditional context:\n{context}" if context else question
|
| 46 |
return self._call_openai(user_input)
|
| 47 |
|
|
|
|
| 77 |
|
| 78 |
if extension == ".pdf":
|
| 79 |
return self._parse_pdf(tmp_file.name)
|
| 80 |
+
elif extension in [".txt", ".csv", ".py"]:
|
| 81 |
return response.text
|
| 82 |
else:
|
| 83 |
+
return f"[Non-text file of type {extension}, not processed.]"
|
| 84 |
|
| 85 |
def _parse_pdf(self, filepath):
|
| 86 |
doc = fitz.open(filepath)
|
|
|
|
| 120 |
for item in questions_data:
|
| 121 |
task_id = item.get("task_id")
|
| 122 |
question_text = item.get("question")
|
| 123 |
+
file_name = item.get("file_name", "")
|
| 124 |
if not task_id or question_text is None:
|
| 125 |
continue
|
| 126 |
try:
|
| 127 |
+
submitted_answer = agent(question_text, task_id=task_id, file_name=file_name)
|
| 128 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 129 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 130 |
except Exception as e:
|