Spaces:
Build error
Build error
File size: 6,813 Bytes
545a3e8 fff240e 4217ae4 e5d5db6 89ee4a3 4217ae4 bc82aea 89ee4a3 545a3e8 4217ae4 a437c57 4217ae4 a437c57 4217ae4 a437c57 e5d5db6 89ee4a3 184ee10 545a3e8 184ee10 545a3e8 | 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 | 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
@tool
def multiply(a: float, b: float) -> float:
"""Multiply a and """
return a * b
@tool
def divide(a: int, b: int) -> float:
"""Divide a and b"""
return a / b
@tool
def add(a: int, b: int) -> int:
"""Add a and b"""
return a + b
@tool
def subtract(a: int, b: int) -> int:
"""Subtract b from a"""
return a - b
@tool
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())
@tool
def wikidata_search(query: str) -> str:
"""Search the wikidata for information"""
return wikidata.run(query)
# wiki search
wikipedia = WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper())
@tool
def wikipedia_search(query: str) -> str:
"""Search the wikipedia for information"""
return wikipedia.run(query)
# arxiv search
arxiv = ArxivAPIWrapper()
@tool
def arxiv_search(query: str) -> str:
"""Search the arxiv for information"""
return arxiv.run(query)
# image analysis tool
@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
@tool
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
@tool
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
@tool
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
@tool
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
|