File size: 5,723 Bytes
e836bd4 06074b9 02c61e8 aafca9e 02c61e8 a3a06d3 06074b9 02c61e8 06074b9 188a166 02c61e8 06074b9 02c61e8 06074b9 02c61e8 6d51abb 06074b9 02c61e8 06074b9 02c61e8 aafca9e 02c61e8 aafca9e 02c61e8 aafca9e 02c61e8 aafca9e 5c17f6c aafca9e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
import os
import base64
import requests
import re
from openai import OpenAI
from duckduckgo_search import DDGS
class BasicAgent:
def __init__(self):
self.llm = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
print("BasicAgent initialized.")
def web_search(self, query: str, max_results: int = 5) -> str:
"""Search the web using DuckDuckGo for current information."""
try:
with DDGS() as ddgs:
results = list(ddgs.text(query, max_results=max_results))
if not results:
return f"No results found for query: {query}"
formatted_results = f"Web search results for '{query}':\n\n"
for i, result in enumerate(results, 1):
title = result.get('title', 'No title')
body = result.get('body', 'No description')
href = result.get('href', 'No URL')
formatted_results += f"{i}. {title}\n"
formatted_results += f" URL: {href}\n"
formatted_results += f" Description: {body}\n\n"
return formatted_results
except Exception as e:
return f"Error performing web search: {str(e)}"
def fetch_file(self, task_id):
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
try:
url = f"{DEFAULT_API_URL}/files/{task_id}"
r = requests.get(url, timeout=10)
r.raise_for_status()
return url, r.content, r.headers.get("Content-Type", "")
except:
return None, None, None
def describe_image(self, img_path: str) -> str:
# Stub for vision support; return message for now
return "[Image analysis not implemented in this agent.]"
def __call__(self, question: str, task_id: str = None) -> str:
search_snippet = self.web_search(question)
full_prompt = (
"You are a general AI assistant. I will ask you a question. "
"Report your thoughts, and finish your answer with the following template: "
"FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. "
"If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. "
"If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. "
"If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.\n\n"
f"Here are web search results and the question:\n{search_snippet}\n\nQuestion: {question}"
)
# First LLM call
response = self.llm.chat.completions.create(
model="gpt-4o",
messages=[{"role": "system", "content": full_prompt}],
temperature=0.0,
max_tokens=512,
)
answer = response.choices[0].message.content.strip()
final_line = ""
for line in answer.splitlines():
if line.strip().lower().startswith("final answer:"):
final_line = line.split(":", 1)[-1].strip(" .\"'")
break
# Retry on weak answers
bads = [
"", "unknown", "unable to determine", "unable to provide page numbers",
"unable to access video content directly", "unable to analyze video content",
"unable to determine without code", "unable to determine without file",
"follow the steps to locate the paper and find the nasa award number in the acknowledgment section",
"i am unable to view images or access external content directly", "unable to determine without access to the file",
"no results found", "n/a"
]
if final_line.lower() in bads or final_line.lower().startswith("unable") or final_line.lower().startswith("follow the steps") or final_line.lower().startswith("i am unable"):
retry_prompt = (
"Return only the answer to the following question, in the correct format and with no explanation or apologies. "
f"Here are web search results:\n{search_snippet}\n\nQuestion: {question}\nFINAL ANSWER:"
)
response2 = self.llm.chat.completions.create(
model="gpt-4o",
messages=[{"role": "system", "content": retry_prompt}],
temperature=0.0,
max_tokens=128,
)
retry_answer = response2.choices[0].message.content.strip()
for line in retry_answer.splitlines():
if line.strip().lower().startswith("final answer:"):
final_line = line.split(":", 1)[-1].strip(" .\"'")
break
elif retry_answer:
final_line = retry_answer.strip(" .\"'")
# If still blank, fallback to first number in web search
if not final_line:
numbers = re.findall(r'\b\d+\b', search_snippet)
if numbers:
final_line = numbers[0]
else:
# Or fallback to first plausible word or phrase
match = re.search(r"Description:\s*(.*)", search_snippet)
if match:
final_line = match.group(1).split('.')[0]
# Remove enclosing quotes from lists
if final_line.startswith('"') and final_line.endswith('"'):
final_line = final_line[1:-1]
return final_line |