Spaces:
No application file
No application file
File size: 28,857 Bytes
613a6ac |
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 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "94c8b42c",
"metadata": {},
"outputs": [],
"source": [
"import getpass\n",
"import os\n",
"from langchain.chat_models import init_chat_model\n",
"\n",
"if not os.environ.get(\"GOOGLE_API_KEY\"):\n",
" os.environ[\"GOOGLE_API_KEY\"] = getpass.getpass(\"Enter API key for Google Gemini: \")\n",
"llm = init_chat_model(\"gemini-2.5-flash-preview-04-17\", model_provider=\"google_genai\", temperature=0)"
]
},
{
"cell_type": "code",
"execution_count": 18,
"id": "ce83aa2a",
"metadata": {},
"outputs": [],
"source": [
"import re\n",
"from langchain.document_loaders import WebBaseLoader\n",
"from langchain_community.tools import DuckDuckGoSearchResults\n",
"def download_web_pages(query: str) -> str:\n",
" \"\"\"\n",
" Performs a web search using the given query, downloads the content of two relevant web pages,\n",
" and returns their combined content as a raw string.\n",
"\n",
" This is useful when the task requires analysis of web page content, such as retrieving poems, \n",
" changelogs, or other textual resources.\n",
"\n",
" Args:\n",
" query (str): The search query.\n",
"\n",
" Returns:\n",
" str: The combined raw text content of the two retrieved web pages.\n",
" \"\"\"\n",
" search_engine = DuckDuckGoSearchResults(output_format=\"list\", num_results=2)\n",
" page_urls = [url[\"link\"] for url in search_engine(query)]\n",
"\n",
" loader = WebBaseLoader(web_paths=(page_urls))\n",
" docs = loader.load()\n",
"\n",
" combined_text = \"\\n\\n\".join(doc.page_content[:15000] for doc in docs)\n",
"\n",
" # Clean up excessive newlines, spaces and strip leading/trailing whitespace\n",
" cleaned_text = re.sub(r'\\n{3,}', '\\n\\n', combined_text).strip()\n",
" cleaned_text = re.sub(r'[ \\t]{6,}', ' ', cleaned_text)\n",
"\n",
" # Strip leading/trailing whitespace\n",
" cleaned_text = cleaned_text.strip()\n",
" return cleaned_text"
]
},
{
"cell_type": "code",
"execution_count": 24,
"id": "586df437",
"metadata": {},
"outputs": [],
"source": [
"from langchain_community.retrievers import WikipediaRetriever\n",
"\n",
"def wikipedia_search(query: str) -> str:\n",
" \"\"\"\n",
" Searches for a Wikipedia articles using the provided query and returns the content of the corresponding Wikipedia pages.\n",
"\n",
" Args:\n",
" query (str): The search term to look up on Wikipedia.\n",
"\n",
" Returns:\n",
" str: The text content of the Wikipedia articles related to the query.\n",
" \"\"\"\n",
" retriever = WikipediaRetriever()\n",
" docs = retriever.invoke(query)\n",
" combined_text = \"\\n\\n\".join(doc.page_content for doc in docs)\n",
" return combined_text"
]
},
{
"cell_type": "code",
"execution_count": 25,
"id": "fac2cb01",
"metadata": {},
"outputs": [],
"source": [
"from google import genai\n",
"from google.genai import types\n",
"\n",
"def youtube_viewer(youtube_url: str, question: str) -> str:\n",
" \"\"\"\n",
" Analyzes a YouTube video from the provided URL and returns an answer \n",
" to the given question based on the analysis results.\n",
"\n",
" Args:\n",
" youtube_url (str): The URL of the YouTube video, in the format \n",
" \"https://www.youtube.com/...\".\n",
" question (str): A question related to the content of the video.\n",
"\n",
" Returns:\n",
" str: An answer to the question based on the video's content.\n",
" \"\"\"\n",
" client = genai.Client()\n",
" response = client.models.generate_content(\n",
" model='models/gemini-2.5-flash-preview-04-17',\n",
" contents=types.Content(\n",
" parts=[\n",
" types.Part(\n",
" file_data=types.FileData(file_uri=youtube_url)\n",
" ),\n",
" types.Part(text=question)\n",
" ]\n",
" )\n",
" )\n",
" return response.text"
]
},
{
"cell_type": "code",
"execution_count": 26,
"id": "4c498a3d",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Key 'title' is not supported in schema, ignoring\n",
"Key 'title' is not supported in schema, ignoring\n",
"Key 'title' is not supported in schema, ignoring\n"
]
}
],
"source": [
"tools = [download_web_pages, wikipedia_search, youtube_viewer]\n",
"\n",
"# Bind the tools to the agent\n",
"llm_with_tools = llm.bind_tools(tools)"
]
},
{
"cell_type": "code",
"execution_count": 27,
"id": "10628e0f",
"metadata": {},
"outputs": [],
"source": [
"from typing import TypedDict, Annotated, Optional\n",
"from langchain_core.messages import AnyMessage\n",
"from langgraph.graph.message import add_messages\n",
"\n",
"class AgentState(TypedDict):\n",
" \"\"\"Agent state for the graph.\"\"\"\n",
" input_file: Optional[str]\n",
" messages: Annotated[list[AnyMessage], add_messages]"
]
},
{
"cell_type": "code",
"execution_count": 28,
"id": "f1594fb9",
"metadata": {},
"outputs": [],
"source": [
"from langchain_core.messages import SystemMessage, HumanMessage\n",
"\n",
"def assistant(state: AgentState):\n",
" sys_msg = SystemMessage(\n",
" content=\n",
" \"\"\"\n",
"You are a helpful assistant tasked with answering questions using a set of tools. When given a question, follow these steps:\n",
"1. Create a clear, step-by-step plan to solve the question.\n",
"2. If a tool is necessary, select the most appropriate tool based on its functionality. If one tool isn't working, use another with similar functionality.\n",
"3. Execute your plan and provide the response in the following format:\n",
"\n",
"FINAL ANSWER: [YOUR FINAL ANSWER]\n",
"\n",
"Your final answer should be:\n",
"\n",
"- A number (without commas or units unless explicitly requested),\n",
"- A short string (avoid articles, abbreviations, and use plain text for digits unless otherwise specified),\n",
"- A comma-separated list (apply the formatting rules above for each element, with exactly one space after each comma).\n",
"\n",
"Ensure that your answer is concise and follows the task instructions strictly. If the answer is more complex, break it down in a way that follows the format.\n",
"Begin your response with \"FINAL ANSWER: \" followed by the answer, and nothing else.\n",
" \"\"\"\n",
" )\n",
"\n",
" return {\n",
" \"messages\": [llm_with_tools.invoke([sys_msg] + state[\"messages\"])],\n",
" \"input_file\": state[\"input_file\"]\n",
" }"
]
},
{
"cell_type": "code",
"execution_count": 29,
"id": "b36bc36c",
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAANgAAAD5CAIAAADKsmwpAAAQAElEQVR4nOzdB1xT1x4H8JNBQhIIkLCXAqKCKG6qtI7qw1EXTtC2jmfr6mut2qGttVpbbWuf1omrddddreLWJ+6+WieIgiAWEiKbkL14f8gr5fECassN5+ae74dPPuHekEDy48x7z+VWVlYigmhqXEQQGCBBJLBAgkhggQSRwAIJIoEFEkQCCySIdRl05iKZQVNh1lSYzKZ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uGPmlrj/g7K/PJeoxqnG0g8l6dUQN0HeWqKVJoyqga3sVKer3QRWSJjyLWGmsDTW0JjZgX+dlNh1Dl4x6VModKWqPqO9UZEU3imJvmUL0MzL+c6cLlYrlAhnTphThAimsgzBREGLacva6GUlSifUDvD2yRKc0t5LO2waU3f3mWy5xikgAJDKjVnX8tTFjjIxclKZcr75x+HtOIOmOCLiCb1fNOpsYOlkTGuF34sLsrSVHKcxF4iOq5DolXqKwo1Fr3e099p4KfN+AIHObiB1p57Xt/Dmzd0ip8iR5d5S5V15wlfyLVYWBwep3qtTi7C8tR0NptlNJgsBpPJYDZojXwBO7y9S8uOXmRlRHz8yQNMfJs7w9dLwzxLFIbyoqrTO9TlJrPJbDbhGESeM5vNYYvEQqGY4xnAc3Fj6mmyGPurRzpJfHnwhQjiryGXoqUTkRuX1oseSHxhxtV2nUmm9ulEIGIXyfSInowGS16G2s3Tdv1JgkgnPs2cjXq6LspTotA3cIgnCSKdBLUUsljo5jlaLlZ2bpc8dki9i+bjdb1m4llcOFhoNFaGtRNL/Wmwqj6MqJQX6v+1W/HaR8Gi+scrSBBpKfVqedoVpV5j1mmoWhmmUXgF8ssKDCFtRbGDPRu+nCUJIo3BR2fQYR3ESkuls+iZJq5IEAkskHFEAgskiAQWSBAJLJAgElggQSSwQIJIYOE/AAAA//9IOO73AAAABklEQVQDAFPPIzkUheU2AAAAAElFTkSuQmCC",
"text/plain": [
"<IPython.core.display.Image object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"from langgraph.prebuilt import ToolNode, tools_condition\n",
"from IPython.display import Image, display\n",
"from langgraph.graph import StateGraph, START\n",
"\n",
"# Build the state graph\n",
"# The graph\n",
"builder = StateGraph(AgentState)\n",
"\n",
"# Define nodes: these do the work\n",
"builder.add_node(\"assistant\", assistant)\n",
"builder.add_node(\"tools\", ToolNode(tools))\n",
"# Define edges: these determine how the control flow moves\n",
"builder.add_edge(START, \"assistant\")\n",
"builder.add_conditional_edges(\n",
" \"assistant\",\n",
" tools_condition,\n",
")\n",
"builder.add_edge(\"tools\", \"assistant\")\n",
"react_graph = builder.compile()\n",
"# Show the butler's thought process\n",
"display(Image(react_graph.get_graph(xray=True).draw_mermaid_png()))"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "ead8e45f",
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "ed21ed00ada141289cbee25b93029435",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"VBox(children=(HTML(value='<center> <img\\nsrc=https://huggingface.co/front/assets/huggingface_logo-noborder.sv…"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"from huggingface_hub import login\n",
"\n",
"# This will prompt you for your token\n",
"login()"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "b4b1299d",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Logged in as: SpyFox\n"
]
}
],
"source": [
"from huggingface_hub import whoami\n",
"\n",
"info = whoami()\n",
"username = info[\"name\"]\n",
"\n",
"print(f\"Logged in as: {username}\")"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "45e5f7ca",
"metadata": {},
"outputs": [],
"source": [
"DEFAULT_API_URL = \"https://agents-course-unit4-scoring.hf.space\" \n",
"api_url = DEFAULT_API_URL\n",
"questions_url = f\"{api_url}/questions\"\n",
"submit_url = f\"{api_url}/submit\"\n",
"files_url = f\"{api_url}/files\""
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "af2e50c9",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Fetching questions from: https://agents-course-unit4-scoring.hf.space/questions\n",
"Fetched 20 questions.\n",
"{'task_id': 'cabe07ed-9eca-40ea-8ead-410ef5e83f91', 'question': \"What is the surname of the equine veterinarian mentioned in 1.E Exercises from the chemistry materials licensed by Marisa Alviar-Agnew & Henry Agnew under the CK-12 license in LibreText's Introductory Chemistry materials as compiled 08/21/2023?\", 'Level': '1', 'file_name': ''}\n"
]
}
],
"source": [
"import requests\n",
"print(f\"Fetching questions from: {questions_url}\")\n",
"try:\n",
" response = requests.get(questions_url, timeout=15)\n",
" response.raise_for_status()\n",
" questions_data = response.json()\n",
" if not questions_data:\n",
" print(\"Fetched questions list is empty.\")\n",
" print(f\"Fetched {len(questions_data)} questions.\")\n",
"except requests.exceptions.RequestException as e:\n",
" print(f\"Error fetching questions: {e}\")\n",
"except requests.exceptions.JSONDecodeError as e:\n",
" print(f\"Error decoding JSON response from questions endpoint: {e}\")\n",
" print(f\"Response text: {response.text[:500]}\")\n",
"except Exception as e:\n",
" print(f\"An unexpected error occurred fetching questions: {e}\")\n",
"\n",
"print(questions_data[7])"
]
},
{
"cell_type": "code",
"execution_count": 30,
"id": "3c6996e6",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Running agent on 20 questions...\n",
"Question: How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"C:\\Users\\wasyl\\AppData\\Local\\Temp\\ipykernel_22488\\81366616.py:19: LangChainDeprecationWarning: The method `BaseTool.__call__` was deprecated in langchain-core 0.1.47 and will be removed in 1.0. Use :meth:`~invoke` instead.\n",
" page_urls = [url[\"link\"] for url in search_engine(query)]\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Answer: 3\n",
"Question: In the video https://www.youtube.com/watch?v=L1vXCYZAYYM, what is the highest number of bird species to be on camera simultaneously?\n",
"Answer: 3\n"
]
},
{
"ename": "KeyboardInterrupt",
"evalue": "",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mKeyboardInterrupt\u001b[0m Traceback (most recent call last)",
"Cell \u001b[1;32mIn[30], line 28\u001b[0m\n\u001b[0;32m 26\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mAnswer: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00msubmitted_answer\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m 27\u001b[0m answers_payload\u001b[38;5;241m.\u001b[39mappend({\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mtask_id\u001b[39m\u001b[38;5;124m\"\u001b[39m: task_id, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124msubmitted_answer\u001b[39m\u001b[38;5;124m\"\u001b[39m: submitted_answer})\n\u001b[1;32m---> 28\u001b[0m time\u001b[38;5;241m.\u001b[39msleep(\u001b[38;5;241m10\u001b[39m) \u001b[38;5;66;03m# Sleep for 10 seconds to avoid rate limiting\u001b[39;00m\n\u001b[0;32m 29\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[0;32m 30\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mError running agent on task \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mtask_id\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00me\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n",
"\u001b[1;31mKeyboardInterrupt\u001b[0m: "
]
}
],
"source": [
"import time\n",
"\n",
"def extract_after_final_answer(text):\n",
" keyword = \"FINAL ANSWER: \"\n",
" index = text.find(keyword)\n",
" if index != -1:\n",
" return text[index + len(keyword):]\n",
" else:\n",
" return \"\"\n",
"\n",
"answers_payload = []\n",
"\n",
"print(f\"Running agent on {len(questions_data)} questions...\")\n",
"for item in questions_data:\n",
" task_id = item.get(\"task_id\")\n",
" question_text = item.get(\"question\")\n",
" print(f\"Question: {question_text}\")\n",
" messages = [HumanMessage(content=question_text)]\n",
"\n",
" if not task_id or question_text is None:\n",
" print(f\"Skipping item with missing task_id or question: {item}\")\n",
" continue\n",
" try:\n",
" submitted_answer = react_graph.invoke({\"messages\": messages, \"input_file\": None})\n",
" submitted_answer = extract_after_final_answer(submitted_answer['messages'][-1].content)\n",
" print(f\"Answer: {submitted_answer}\")\n",
" answers_payload.append({\"task_id\": task_id, \"submitted_answer\": submitted_answer})\n",
" time.sleep(10) # Sleep for 10 seconds to avoid rate limiting\n",
" except Exception as e:\n",
" print(f\"Error running agent on task {task_id}: {e}\")\n"
]
},
{
"cell_type": "code",
"execution_count": 27,
"id": "8e47414a",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Agent finished. Submitting 20 answers for user 'SpyFox'...\n"
]
}
],
"source": [
"submission_data = {\"username\": username.strip(), \"agent_code\": \"https://huggingface.co/spaces/SpyFox/agents_final_test/tree/main\", \"answers\": answers_payload}\n",
"status_update = f\"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'...\"\n",
"print(status_update)"
]
},
{
"cell_type": "code",
"execution_count": 28,
"id": "a086f73f",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Submitting 20 answers to: https://agents-course-unit4-scoring.hf.space/submit\n",
"Submission successful.\n",
"Submission Successful!\n",
"User: SpyFox\n",
"Overall Score: 45.0% (9/20 correct)\n",
"Message: Score calculated successfully: 9/20 total questions answered correctly (20 valid tasks attempted). High score updated on leaderboard.\n"
]
}
],
"source": [
"print(f\"Submitting {len(answers_payload)} answers to: {submit_url}\")\n",
"\n",
"response = requests.post(submit_url, json=submission_data, timeout=60)\n",
"response.raise_for_status()\n",
"result_data = response.json()\n",
"final_status = (\n",
" f\"Submission Successful!\\n\"\n",
" f\"User: {result_data.get('username')}\\n\"\n",
" f\"Overall Score: {result_data.get('score', 'N/A')}% \"\n",
" f\"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\\n\"\n",
" f\"Message: {result_data.get('message', 'No message received.')}\"\n",
")\n",
"print(\"Submission successful.\")\n",
"print(final_status)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "base",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.4"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|