{ "cells": [ { "cell_type": "code", "id": "initial_id", "metadata": { "collapsed": true }, "source": [ "import time\n", "import concurrent\n", "from concurrent import futures\n", "from typing import Any, List, Dict, Tuple\n", "\n", "from PIL import Image\n", "from openai import AzureOpenAI\n", "from tqdm.auto import tqdm\n", "\n", "import json\n", "from pathlib import Path\n", "\n", "import pandas as pd\n", "import requests\n", "from dotenv import dotenv_values\n", "from smolagents import tool, DuckDuckGoSearchTool\n", "import wikipediaapi\n" ], "outputs": [], "execution_count": null }, { "metadata": {}, "cell_type": "code", "source": [ "questions = ['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", " '.rewsna eht sa \"tfel\" drow eht fo etisoppo eht etirw ,ecnetnes siht dnatsrednu uoy fI',\n", " 'Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?',\n", " 'Given this table defining * on the set S = {a, b, c, d, e}\\n\\n|*|a|b|c|d|e|\\n|---|---|---|---|---|---|\\n|a|a|b|c|b|d|\\n|b|b|c|a|e|c|\\n|c|c|a|b|b|a|\\n|d|b|e|b|e|d|\\n|e|d|b|a|d|c|\\n\\nprovide the subset of S involved in any possible counter-examples that prove * is not commutative. Provide your answer as a comma separated list of the elements in the set in alphabetical order.',\n", " 'Examine the video at https://www.youtube.com/watch?v=1htKBjuUWec.\\n\\nWhat does Teal\\'c say in response to the question \"Isn\\'t that hot?\"',\n", " \"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?\",\n", " \"I'm making a grocery list for my mom, but she's a professor of botany and she's a real stickler when it comes to categorizing things. I need to add different foods to different categories on the grocery list, but if I make a mistake, she won't buy anything inserted in the wrong category. Here's the list I have so far:\\n\\nmilk, eggs, flour, whole bean coffee, Oreos, sweet potatoes, fresh basil, plums, green beans, rice, corn, bell pepper, whole allspice, acorns, broccoli, celery, zucchini, lettuce, peanuts\\n\\nI need to make headings for the fruits and vegetables. Could you please create a list of just the vegetables from my list? If you could do that, then I can figure out how to categorize the rest of the list into the appropriate categories. But remember that my mom is a real stickler, so make sure that no botanical fruits end up on the vegetable list, or she won't get them when she's at the store. Please alphabetize the list of vegetables, and place each item in a comma separated list.\",\n", " 'Who did the actor who played Ray in the Polish-language version of Everybody Loves Raymond play in Magda M.? Give only the first name.',\n", " 'How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?',\n", " 'On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?',\n", " \"Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations.\",\n", " \"What country had the least number of athletes at the 1928 Summer Olympics? If there's a tie for a number of athletes, return the first in alphabetical order. Give the IOC country code as your answer.\",\n", " \"Who are the pitchers with the number before and after Taishō Tamai's number as of July 2023? Give them to me in the form Pitcher Before, Pitcher After, use their last names only, in Roman characters.\",\n", " 'What is the first name of the only Malko Competition recipient from the 20th Century (after 1977) whose nationality on record is a country that no longer exists?']" ], "id": "55d7941445304e9b", "outputs": [], "execution_count": null }, { "metadata": {}, "cell_type": "code", "source": [ "from smolagents import GoogleSearchTool\n", "import requests\n", "import urllib.request\n", "from markdownify import markdownify as md\n", "from bs4 import BeautifulSoup\n", "from dotenv import dotenv_values\n", "from openai import AzureOpenAI\n", "import json\n", "\n", "\n", "\n", "def get_search_results_for(query):\n", " encoded_query = urllib.parse.urlencode({'q': query})\n", " url = f'https://html.duckduckgo.com/html?q={encoded_query}'\n", "\n", " request = urllib.request.Request(url)\n", " request.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36')\n", "\n", " raw_response = urllib.request.urlopen(request).read()\n", " html = raw_response.decode(\"utf-8\")\n", "\n", " soup = BeautifulSoup(html, 'html.parser')\n", " a_results = soup.select(\"a.result__a\")\n", "\n", " links = []\n", " for a_result in a_results:\n", " # print(a_result)\n", " url = a_result.attrs['href']\n", " title = a_result.text\n", " links.append({\"title\": title, \"url\": url} )\n", "\n", " return links\n", "\n", "search_tool = GoogleSearchTool(\"serper\")\n", "\n", "def get_google_search_results_for(query: str):\n", " return search_tool.forward(query)\n", "\n", "\n", "def load_page_content(url) -> str:\n", " response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'})\n", " page_content = response.content.decode('utf-8')\n", " page_content_md = md(page_content)\n", "\n", " return page_content_md\n", "\n" ], "id": "bf91141def5a906", "outputs": [], "execution_count": null }, { "metadata": {}, "cell_type": "code", "source": [ "tools = [{\n", " \"type\": \"function\",\n", " \"function\": {\n", " \"name\": \"get_search_results_for\",\n", " \"description\": \"Returns the top 10 results for a DuckDuckGo query.\",\n", " \"parameters\": {\n", " \"type\": \"object\",\n", " \"properties\": {\n", " \"query\": {\n", " \"type\": \"string\",\n", " \"description\": \"query to search for on DuckDuckGo\"\n", " }\n", " },\n", " \"required\": [\n", " \"query\"\n", " ],\n", " \"additionalProperties\": False\n", " },\n", " \"strict\": True\n", " }\n", " },\n", " {\n", " \"type\": \"function\",\n", " \"function\": {\n", " \"name\": \"load_page_content\",\n", " \"description\": \"Returns the content of a particular webpage.\",\n", " \"parameters\": {\n", " \"type\": \"object\",\n", " \"properties\": {\n", " \"url\": {\n", " \"type\": \"string\",\n", " \"description\": \"Url of the webpage for which to retrieve the content\"\n", " }\n", " },\n", " \"required\": [\n", " \"url\"\n", " ],\n", " \"additionalProperties\": False\n", " },\n", " \"strict\": True\n", " }\n", " }\n", "]\n", "\n", "def call_function(name, args):\n", " if name == \"get_search_results_for\":\n", " return get_google_search_results_for(**args)\n", " if name == \"load_page_content\":\n", " return load_page_content(**args)\n", "\n", " return None\n" ], "id": "45340dbef571198f", "outputs": [], "execution_count": null }, { "metadata": {}, "cell_type": "code", "source": [ "query = questions[2]\n", "config = dotenv_values()\n", "\n", "client = AzureOpenAI(\n", " api_key=config[\"AZURE_OPENAI_API_KEY\"],\n", " azure_endpoint=config[\"AZURE_OPENAI_API_BASE\"],\n", " api_version=config[\"AZURE_OPENAI_API_VERSION\"]\n", ")\n", "openai_chatmodel = config[\"AZURE_OPENAI_CHAT_MODEL\"]\n", "\n", "GRAY = \"\\033[90m\"\n", "BOLD = \"\\033[1m\"\n", "RESET = \"\\033[0m\"\n", "\n", "\n", "messages = [\n", " {\n", " \"role\": \"system\",\n", " \"content\": \"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", " {\"role\": \"user\", \"content\": query}\n", "]\n", "\n", "total_input_token_count = 0\n", "total_output_token_count = 0\n", "\n", "while True:\n", " completion = client.chat.completions.create(\n", " model=openai_chatmodel,\n", " messages=messages,\n", " tools=tools\n", " )\n", "\n", " total_input_token_count += completion.usage.prompt_tokens\n", " total_output_token_count += completion.usage.completion_tokens\n", "\n", " if completion.choices[0].finish_reason == \"stop\":\n", " print(f\"{BOLD}Final answer: {completion.choices[0].message.content}{RESET}\")\n", " break\n", " elif completion.choices[0].finish_reason == \"tool_calls\":\n", " messages.append(completion.choices[0].message)\n", " for tool_call in completion.choices[0].message.tool_calls:\n", " name = tool_call.function.name\n", " args = json.loads(tool_call.function.arguments)\n", "\n", " result = call_function(name, args)\n", " print(f\"Called {BOLD}{name}({args}){RESET} and it returned {GRAY}{str(result)[:300]}{RESET}\")\n", "\n", " messages.append({\n", " \"role\": \"tool\",\n", " \"tool_call_id\": tool_call.id,\n", " \"content\": str(result)\n", " })\n", " else:\n", " raise Exception(\"We're not supposed to be here\")" ], "id": "adfd8a6e27fb6069", "outputs": [], "execution_count": null }, { "metadata": {}, "cell_type": "code", "source": [ "def run_agent(task: str):\n", "\n", " messages = [\n", " {\n", " \"role\": \"system\",\n", " \"content\": \"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", " {\"role\": \"user\", \"content\": task}\n", " ]\n", "\n", " while True:\n", " completion = client.chat.completions.create(\n", " model=openai_chatmodel,\n", " messages=messages,\n", " tools=tools\n", " )\n", "\n", " if completion.choices[0].finish_reason == \"stop\":\n", " print(f\"{BOLD}Final answer: {completion.choices[0].message.content}{RESET}\")\n", " return completion.choices[0].message.content\n", " elif completion.choices[0].finish_reason == \"tool_calls\":\n", " messages.append(completion.choices[0].message)\n", " for tool_call in completion.choices[0].message.tool_calls:\n", " name = tool_call.function.name\n", " args = json.loads(tool_call.function.arguments)\n", "\n", " result = call_function(name, args)\n", " print(f\"Called {BOLD}{name}({args}){RESET} and it returned {GRAY}{str(result)[:300]}{RESET}\")\n", "\n", " messages.append({\n", " \"role\": \"tool\",\n", " \"tool_call_id\": tool_call.id,\n", " \"content\": str(result)\n", " })\n", " else:\n", " raise Exception(\"We're not supposed to be here\")\n", "\n", "run_agent(questions[4])" ], "id": "4518e95a30ad7b8a", "outputs": [], "execution_count": null } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.6" } }, "nbformat": 4, "nbformat_minor": 5 }