Spaces:
Build error
Build error
Download unit4agent.py from drackon/Final_Assignment_Template: direct link, hf CLI and curl.
- Browser
- Download file 6.81 kB
-
https://huggingface.co/spaces/drackon/Final_Assignment_Template/resolve/main/unit4agent.py
- Command line
-
hf download hf://spaces/drackon/Final_Assignment_Template/unit4agent.py
-
curl -L -o unit4agent.py https://huggingface.co/spaces/drackon/Final_Assignment_Template/resolve/main/unit4agent.py
6.81 kB
| from langchain_core.tools import tool | |
| from langchain_tavily import TavilySearch | |
| from langchain_community.utilities import ArxivAPIWrapper | |
| from langchain_community.tools import WikipediaQueryRun | |
| from langchain_community.utilities import WikipediaAPIWrapper | |
| from langchain_community.tools.wikidata.tool import WikidataAPIWrapper, WikidataQueryRun | |
| from typing import List, TypedDict, Annotated, Optional | |
| from langchain_core.messages import AnyMessage, SystemMessage, HumanMessage | |
| from langchain.chat_models import init_chat_model | |
| from langgraph.prebuilt import create_react_agent | |
| from langchain_openai import ChatOpenAI | |
| import os | |
| import base64 | |
| import requests | |
| import pandas as pd | |
| from openai import OpenAI | |
| from langchain_experimental.utilities import PythonREPL | |
| import io | |
| import sys | |
| import runpy | |
| import subprocess | |
| llm = ChatOpenAI(model="gpt-4.1") | |
| python_repl = PythonREPL() | |
| # tools /////////////////////////////////// | |
| # calculations | |
| def multiply(a: float, b: float) -> float: | |
| """Multiply a and """ | |
| return a * b | |
| def divide(a: int, b: int) -> float: | |
| """Divide a and b""" | |
| return a / b | |
| def add(a: int, b: int) -> int: | |
| """Add a and b""" | |
| return a + b | |
| def subtract(a: int, b: int) -> int: | |
| """Subtract b from a""" | |
| return a - b | |
| def square_root(a: int) -> float: | |
| """Square root of a""" | |
| return a ** 0.5 | |
| # web search, Tavily | |
| TAVILY_API_KEY = os.getenv("TAVILY_API_KEY") | |
| web_search_tool = TavilySearch( | |
| max_results=5, | |
| topic="general", | |
| # include_answer=False, | |
| # include_raw_content=False, | |
| # include_images=False, | |
| # include_image_descriptions=False, | |
| # search_depth="basic", | |
| # time_range="day", | |
| # include_domains=None, | |
| # exclude_domains=None | |
| ) | |
| # wikidata search | |
| wikidata = WikidataQueryRun(api_wrapper=WikidataAPIWrapper()) | |
| def wikidata_search(query: str) -> str: | |
| """Search the wikidata for information""" | |
| return wikidata.run(query) | |
| # wiki search | |
| wikipedia = WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper()) | |
| def wikipedia_search(query: str) -> str: | |
| """Search the wikipedia for information""" | |
| return wikipedia.run(query) | |
| # arxiv search | |
| arxiv = ArxivAPIWrapper() | |
| def arxiv_search(query: str) -> str: | |
| """Search the arxiv for information""" | |
| return arxiv.run(query) | |
| # image analysis tool | |
| def download_image_and_analyze(image_file_extension: str, image_url: str, image_analysis_question: str) -> str: | |
| """Download and analyze the image""" | |
| # download the image using requests library | |
| response = requests.get(image_url) | |
| # convert the image to base64 | |
| image_base64 = base64.b64encode(response.content).decode("utf-8") | |
| img_format = "jpeg" | |
| if image_file_extension.upper() == "PNG": | |
| img_format = "png" | |
| msg = llm.invoke( | |
| [ | |
| HumanMessage( | |
| content=[ | |
| {"type": "text", "text": image_analysis_question}, | |
| { | |
| "type": "image_url", | |
| "image_url": { | |
| "url": f"data:image/{img_format};base64,{image_base64}" | |
| }, | |
| }, | |
| ] | |
| ) | |
| ] | |
| ) | |
| return msg.content | |
| def get_excel_file_content(excel_file_url: str) -> str: | |
| """Download Excel file and extract its content""" | |
| # download the image using requests library | |
| response = requests.get(excel_file_url) | |
| # save the file to a temporary location | |
| temp_file_path = "/tmp/temp.xlsx" | |
| with open(temp_file_path, "wb") as file: | |
| file.write(response.content) | |
| # read the content of the file | |
| df = pd.read_excel(temp_file_path) | |
| # convert the content to a string | |
| content = df.to_string() | |
| # return the content | |
| return content | |
| def transcribe_audio_mp3_file(mp3_file_url: str) -> str: | |
| """Download Mp3 file, transcribe audio and return text""" | |
| # download the image using requests library | |
| response = requests.get(mp3_file_url) | |
| # save the file to a temporary location | |
| temp_file_path = "/tmp/temp.mp3" | |
| with open(temp_file_path, "wb") as file: | |
| file.write(response.content) | |
| client = OpenAI() | |
| audio_file = open(temp_file_path, "rb") | |
| transcription = client.audio.transcriptions.create( | |
| model="gpt-4o-transcribe", | |
| file=audio_file, | |
| response_format="text" | |
| ) | |
| # return the content | |
| return transcription | |
| def execute_python_code(python_code_file_url: str) -> str: | |
| """Download python code from URL and execute it""" | |
| # download the file using requests library | |
| response = requests.get(python_code_file_url) | |
| # save the file to a temporary location | |
| temp_file_path = "/tmp/temp.py" | |
| with open(temp_file_path, "wb") as file: | |
| file.write(response.content) | |
| # output = runpy.run_path(temp_file_path) | |
| # python_code = open(temp_file_path).read() | |
| # original_stdout = sys.stdout | |
| # # Create a StringIO buffer | |
| # buffer = io.StringIO() | |
| # sys.stdout = buffer # Redirect stdout to the buffer | |
| # # exec("python " python_code) | |
| # exec("python " + temp_file_path) | |
| # sys.stdout = original_stdout | |
| # # Get the output from the buffer | |
| # output = buffer.getvalue() | |
| result = subprocess.run(["python", temp_file_path], capture_output=True, text=True) | |
| return result.stdout | |
| def get_youtube_video_transcript(youtube_video_url: str) -> str: | |
| """Get the transcript of a youtube video from URL""" | |
| SEARCHAPI_API_KEY = os.getenv("SEARCHAPI_API_KEY") | |
| # extract video id from url, https://www.youtube.com/watch?v=dQw4w9WgXcQ | |
| video_id = youtube_video_url.split("v=")[1] | |
| # get the transcript of the video | |
| url = "https://www.searchapi.io/api/v1/search" | |
| params = { | |
| "engine": "youtube_transcripts", | |
| "video_id": video_id, | |
| "api_key": SEARCHAPI_API_KEY | |
| } | |
| response = requests.get(url, params=params) | |
| response_json = response.json() | |
| return response_json["transcripts"] | |
| def compile_agent(): | |
| tools = [multiply, divide, add, subtract, square_root, web_search_tool, arxiv_search, | |
| wikipedia_search, download_image_and_analyze, get_excel_file_content, transcribe_audio_mp3_file, execute_python_code, | |
| get_youtube_video_transcript] | |
| # HUGGINGFACEHUB_API_TOKEN = os.getenv("HUGGINGFACEHUB_API_TOKEN") | |
| # read system prompt from file | |
| with open("system_prompt.txt", "r") as file: | |
| system_prompt = file.read() | |
| # llm = HuggingFaceEndpoint( | |
| # repo_id="Qwen/Qwen2.5-Coder-32B-Instruct", | |
| # huggingfacehub_api_token=HUGGINGFACEHUB_API_TOKEN | |
| # ) | |
| ai_agent = create_react_agent( | |
| model=llm, | |
| tools=tools, | |
| prompt=system_prompt | |
| ) | |
| return ai_agent | |