Spaces:
Sleeping
Sleeping
Update app.py
Browse files28 unmodified lines29303132333435365 unmodified lines4243444546474814 unmodified lines636465666768697018 unmodified lines8990919293941 unmodified line969798991001011021039 unmodified lines11311411511611711811912 unmodified lines1321331341351361371382 unmodified lines1411421431441451461471481491501511524 unmodified lines15715815916016116216312 unmodified lines1761771781791801811821831845 unmodified lines19019119219319419519619719819910 unmodified lines2102112122132142153 unmodified lines21922022122222328 unmodified linesdef normalize_answer(raw: any) -> str:"""Приводим ответ инструмента или LLM к простому строковому значению.Убираем лишние кавычки, точки в конце и т.д."""ans = rawif isinstance(ans, dict) and 'output' in ans:5 unmodified linesans = ans[:-1].strip()# Извлекаем содержимое в первых кавычкахm = re.search(r'"([^",]+)"', ans)if m:return m.group(1)# NASA award number14 unmodified linesPay very close attention to any formatting instructions in the question: use full names, correct spelling, exact casing, no abbreviations unless explicitly allowed.If the answer is number, write it in digits (for example, as answer to question 'How many...' or 'How much...')Process for each question:1. Think which tool to use.2. Call that tool only.18 unmodified linesreturn "Please login to Hugging Face.", Noneusername = profile.usernamequestions_url = f"{DEFAULT_API_URL}/questions"submit_url = f"{DEFAULT_API_URL}/submit"1 unmodified linetry:llm = ChatOpenAI(model_name=config.OPENAI_MODEL,openai_api_key=config.OPENAI_API_KEY,temperature = 0.0)tool_classes = [GaiaQATool, WikiSearchTool, SearchSummaryTool,9 unmodified linestools=tools,llm=llm,agent="zero-shot-react-description",max_iterations=50,early_stopping_method="generate",handle_parsing_errors=True,verbose=False12 unmodified linesresults = []payload = []# Обработка каждого вопросаfor item in questions:tid = item.get("task_id")q = item.get("question", "").strip()2 unmodified lines# Скачиваем файл, если естьfile_path = Noneif item.get("has_file") and item.get("file_name"):file_name = item["file_name"]try:fresp = requests.get(f"{DEFAULT_API_URL}/files/{tid}/{file_name}", timeout=20)fresp.raise_for_status()ext = os.path.splitext(file_name)[-1]file_path = f"/tmp/{tid}{ext}"with open(file_path, "wb") as f:f.write(fresp.content)4 unmodified linesif file_path and file_path.lower().endswith(('.png', '.jpg', '.jpeg')):raw = ChessTool()._run(file_path)ans = normalize_answer(raw)results.append({"Task ID": tid, "Question": q, "Submitted Answer": ans})payload.append({"task_id": tid, "submitted_answer": ans})continueif file_path and file_path.lower().endswith('.py'):12 unmodified lines# Формируем ввод для агентаinput_text = f"File: {file_path}\nQuestion: {q}" if file_path else q# Вызываем агента с префиксомtry:raw = agent.invoke(system_prefix + "\n" + input_text) # use invoke to avoid unsupported stop parameterexcept Exception:raw = agent.invoke(system_prefix + "\n" + q)5 unmodified linesresults.append({"Task ID": tid, "Question": q, "Submitted Answer": ans})payload.append({"task_id": tid, "submitted_answer": ans})# Отправляем ответы на серверsubmission = {"username": username,"agent_code": f"https://huggingface.co/spaces/{os.getenv('SPACE_ID', '?')}/tree/main","answers": payload}try:10 unmodified linesreturn status, pd.DataFrame(results)# Gradio UIwith gr.Blocks() as demo:gr.Markdown("# AI Agents Course — Final Exam Runner")3 unmodified linestable = gr.DataFrame(label="Results")run_btn.click(fn=run_and_submit_all, outputs=[status_box, table])if __name__ == "__main__":demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)))28 unmodified lines29303132333435365 unmodified lines4243444546474814 unmodified lines63646566676818 unmodified lines878889909192931 unmodified line95969798991001019 unmodified lines11111211311411511611712 unmodified lines1301311321331341352 unmodified lines1381391401411421431441451461471481491504 unmodified lines15515615715815916016116212 unmodified lines1751761771781791801811821835 unmodified lines18919019119219319419519619719810 unmodified lines2092102112122132142153 unmodified lines21922022122222322428 unmodified linesdef normalize_answer(raw: any) -> str:"""Приводит ответ инструмента или LLM к простому строковому значению:убирает лишние кавычки, точки в конце и т.д."""ans = rawif isinstance(ans, dict) and 'output' in ans:5 unmodified linesans = ans[:-1].strip()# Извлекаем содержимое в первых кавычкахm = re.search(r'"([^\",]+)"', ans)if m:return m.group(1)# NASA award number14 unmodified linesPay very close attention to any formatting instructions in the question: use full names, correct spelling, exact casing, no abbreviations unless explicitly allowed.Process for each question:1. Think which tool to use.2. Call that tool only.18 unmodified linesreturn "Please login to Hugging Face.", Noneusername = profile.username# Endpointsquestions_url = f"{DEFAULT_API_URL}/questions"submit_url = f"{DEFAULT_API_URL}/submit"1 unmodified linetry:llm = ChatOpenAI(model_name=config.OPENAI_MODEL,openai_api_key=config.OPENAI_API_KEY)tool_classes = [GaiaQATool, WikiSearchTool, SearchSummaryTool,9 unmodified linestools=tools,llm=llm,agent="zero-shot-react-description",max_iterations=60,early_stopping_method="generate",handle_parsing_errors=True,verbose=False12 unmodified linesresults = []payload = []for item in questions:tid = item.get("task_id")q = item.get("question", "").strip()2 unmodified lines# Скачиваем файл, если естьfile_path = Noneif item.get("has_file"):try:fresp = requests.get(f"{DEFAULT_API_URL}/files/{tid}", timeout=20)fresp.raise_for_status()# Определяем расширение из имениfname = item.get("file_name", "")ext = os.path.splitext(fname)[-1] or ""file_path = f"/tmp/{tid}{ext}"with open(file_path, "wb") as f:f.write(fresp.content)4 unmodified linesif file_path and file_path.lower().endswith(('.png', '.jpg', '.jpeg')):raw = ChessTool()._run(file_path)ans = normalize_answer(raw)cols = {"Task ID": tid, "Question": q, "Submitted Answer": ans}results.append(cols)payload.append({"task_id": tid, "submitted_answer": ans})continueif file_path and file_path.lower().endswith('.py'):12 unmodified lines# Формируем ввод для агентаinput_text = f"File: {file_path}\nQuestion: {q}" if file_path else q# Вызываем агентаtry:raw = agent.invoke(system_prefix + "\n" + input_text)except Exception:raw = agent.invoke(system_prefix + "\n" + q)5 unmodified linesresults.append({"Task ID": tid, "Question": q, "Submitted Answer": ans})payload.append({"task_id": tid, "submitted_answer": ans})# Отправляем ответыsubmission = {"username": username,"agent_code": f"https://huggingface.co/spaces/{os.getenv('SPACE_ID','?')}/tree/main","answers": payload}try:10 unmodified linesreturn status, pd.DataFrame(results)# Gradio UIwith gr.Blocks() as demo:gr.Markdown("# AI Agents Course — Final Exam Runner")3 unmodified linestable = gr.DataFrame(label="Results")run_btn.click(fn=run_and_submit_all, outputs=[status_box, table])if __name__ == "__main__":demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)))
app.py+20-19