Spaces:
Runtime error
Runtime error
140 unmodified lines1411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831846 unmodified lines19119219319419519619755 unmodified lines253254255256257258259260261140 unmodified linesexcept Exception as e:return f"GoogleSearch error: {e}"class FileAttachmentQueryTool(Tool):name = "run_query_with_file"description = """Downloads a file mentioned in a user prompt, adds it to the context, and runs a query on it.This assumes the file is 20MB or less."""inputs = {"task_id": {"type": "string","description": "A unique identifier for the task related to this file, used to download it.","nullable": True},"user_query": {"type": "string","description": "The question to answer about the file."}}output_type = "string"def forward(self, task_id: str | None, user_query: str) -> str:file_url = f"https://agents-course-unit4-scoring.hf.space/files/{task_id}"file_response = requests.get(file_url)if file_response.status_code != 200:return f"Failed to download file: {file_response.status_code} - {file_response.text}"file_data = file_response.contentfrom google.generativeai import GenerativeModelmodel = GenerativeModel(self.model_name)response = model.generate_content([types.Part.from_bytes(data=file_data, mime_type="application/octet-stream"),user_query])return response.text# --- Basic Agent Definition ---class BasicAgent:def __init__(self, provider="deepseek"):print("BasicAgent initialized.")model = self.select_model(provider)client = InferenceClientModel()6 unmodified linesMathSolver(),RiddleSolver(),TextTransformer(),FileAttachmentQueryTool(model_name=GEMINI_MODEL_NAME),]self.agent = CodeAgent(model=model,55 unmodified linesdef select_model(self, provider: str):if provider == "hf":return InferenceClientModel()else:return LiteLLMModel(model_id=GEMINI_MODEL_NAME)def __call__(self, question: str) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")140 unmodified lines1411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901916 unmodified lines19819920020120220320455 unmodified lines260261262263264265266267268269270271272273274275276277278279280281282140 unmodified linesexcept Exception as e:return f"GoogleSearch error: {e}"class FileAttachmentSummarizer(Tool):name = "file_context"description = "Downloads small CSV/JSON/TXT from the GAIA file endpoint and returns brief context."inputs = {"task_id": {"type": "string", "description": "GAIA task id"},"max_chars": {"type": "integer", "description": "truncate length", "nullable": True},}output_type = "string"def forward(self, task_id: str, max_chars: int | None = None) -> str:try:url = f"https://agents-course-unit4-scoring.hf.space/files/{task_id}"r = requests.get(url, timeout=10)if r.status_code != 200:return f"download_error:{r.status_code}"ctype = r.headers.get("content-type", "")b = r.contentif "csv" in ctype:import iodf = pd.read_csv(io.BytesIO(b))return "CSV columns: " + ", ".join(map(str, df.columns)) + \"\nHEAD:\n" + df.head(5).to_csv(index=False)if "json" in ctype:import jsondata = json.loads(b.decode("utf-8", "ignore"))if isinstance(data, dict):keys = list(data.keys())elif isinstance(data, list) and data and isinstance(data[0], dict):keys = sorted({k for obj in data for k in obj.keys()})else:return str(data)[: (max_chars or 2000)]return "JSON keys: " + ", ".join(map(str, keys))if "text" in ctype:s = b.decode("utf-8", "ignore")return s[: (max_chars or 2000)]return "unsupported_file_type"except Exception as e:return f"parse_error:{e}"# --- Basic Agent Definition ---class BasicAgent:def __init__(self, provider="hf"):print("BasicAgent initialized.")model = self.select_model(provider)client = InferenceClientModel()6 unmodified linesMathSolver(),RiddleSolver(),TextTransformer(),FileAttachmentSummarizer()]self.agent = CodeAgent(model=model,55 unmodified linesdef select_model(self, provider: str):if provider == "hf":# Use HF serverless inference (free, rate-limited). Token from env.return InferenceClientModel(model_id=HF_MODEL_NAME, # e.g. Qwen/Qwen2.5-7B-Instructprovider="hf-inference",api_key=os.getenv("HF_TOKEN"),)elif provider == "groq":# Optional free alternative if you have a GROQ_API_KEYreturn LiteLLMModel(model_id="groq/llama-3.1-8b-instant",api_key=os.getenv("GROQ_API_KEY"))else:# Fallback to HFreturn InferenceClientModel(model_id=HF_MODEL_NAME,provider="hf-inference",api_key=os.getenv("HF_TOKEN"),)def __call__(self, question: str) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")
agent.py+55-34