Update agent.py
Browse files1234567891011121347 unmodified lines616263646566676869import osimport base64from langchain_core.messages import HumanMessage, SystemMessagefrom langchain_openai import ChatOpenAIfrom langchain_community.tools import DuckDuckGoSearchResultsfrom langchain_community.utilities import DuckDuckGoSearchAPIWrapperimport wikipediaapiimport jsonimport asyncioimport aiohttpfrom langchain_core.tools import toolfrom langgraph.graph import START, StateGraph, MessagesStatefrom langgraph.prebuilt import tools_condition47 unmodified linestopic="general",)tools = [tavily_search_tool,search_wiki]def build_graph():1234567891011121314151647 unmodified lines646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316import osimport base64import tempfilefrom langchain_core.messages import HumanMessage, SystemMessagefrom langchain_openai import ChatOpenAIfrom langchain_community.tools import DuckDuckGoSearchResultsfrom langchain_community.utilities import DuckDuckGoSearchAPIWrapperimport wikipediaapiimport jsonfrom urllib.parse import urlparseimport pytesseractfrom PIL import Image, ImageDraw, ImageFont, ImageEnhance, ImageFilterimport cmathfrom langchain_core.tools import toolfrom langgraph.graph import START, StateGraph, MessagesStatefrom langgraph.prebuilt import tools_condition47 unmodified linestopic="general",)@tooldef save_and_read_file(content: str, filename: Optional[str] = None) -> str:"""Save content to a file and return the path.Args:content (str): the content to save to the filefilename (str, optional): the name of the file. If not provided, a random name file will be created."""temp_dir = tempfile.gettempdir()if filename is None:temp_file = tempfile.NamedTemporaryFile(delete=False, dir=temp_dir)filepath = temp_file.nameelse:filepath = os.path.join(temp_dir, filename)with open(filepath, "w") as f:f.write(content)return f"File saved to {filepath}. You can read this file to process its contents."@tooldef download_file_from_url(url: str, filename: Optional[str] = None) -> str:"""Download a file from a URL and save it to a temporary location.Args:url (str): the URL of the file to download.filename (str, optional): the name of the file. If not provided, a random name file will be created."""try:# Parse URL to get filename if not providedif not filename:path = urlparse(url).pathfilename = os.path.basename(path)if not filename:filename = f"downloaded_{uuid.uuid4().hex[:8]}"# Create temporary filetemp_dir = tempfile.gettempdir()filepath = os.path.join(temp_dir, filename)# Download the fileresponse = requests.get(url, stream=True)response.raise_for_status()# Save the filewith open(filepath, "wb") as f:for chunk in response.iter_content(chunk_size=8192):f.write(chunk)return f"File downloaded to {filepath}. You can read this file to process its contents."except Exception as e:return f"Error downloading file: {str(e)}"@tooldef sum(a: int, b:int) -> int:"""Sum up two numbers.Args:a: first intb: second int"""return a + b@tooldef extract_text_from_image(image_path: str) -> str:"""Extract text from an image using OCR library pytesseract (if available).Args:image_path (str): the path to the image file."""try:# Open the imageimage = Image.open(image_path)# Extract text from the imagetext = pytesseract.image_to_string(image)return f"Extracted text from image:\n\n{text}"except Exception as e:return f"Error extracting text from image: {str(e)}"@tooldef analyze_csv_file(file_path: str, query: str) -> str:"""Analyze a CSV file using pandas and answer a question about it.Args:file_path (str): the path to the CSV file.query (str): Question about the data"""try:# Read the CSV filedf = pd.read_csv(file_path)# Run various analyses based on the queryresult = f"CSV file loaded with {len(df)} rows and {len(df.columns)} columns.\n"result += f"Columns: {', '.join(df.columns)}\n\n"# Add summary statisticsresult += "Summary statistics:\n"result += str(df.describe())return resultexcept Exception as e:return f"Error analyzing CSV file: {str(e)}"@tooldef analyze_excel_file(file_path: str, query: str) -> str:"""Analyze an Excel file using pandas and answer a question about it.Args:file_path (str): the path to the Excel file.query (str): Question about the data"""try:# Read the Excel filedf = pd.read_excel(file_path)# Run various analyses based on the queryresult = (f"Excel file loaded with {len(df)} rows and {len(df.columns)} columns.\n")result += f"Columns: {', '.join(df.columns)}\n\n"# Add summary statisticsresult += "Summary statistics:\n"result += str(df.describe())return resultexcept Exception as e:return f"Error analyzing Excel file: {str(e)}"@tooldef analyze_image(image_base64: str) -> Dict[str, Any]:"""Analyze basic properties of an image (size, mode, color analysis, thumbnail preview).Args:image_base64 (str): Base64 encoded image stringReturns:Dictionary with analysis result"""try:img = decode_image(image_base64)width, height = img.sizemode = img.modeif mode in ("RGB", "RGBA"):arr = np.array(img)avg_colors = arr.mean(axis=(0, 1))dominant = ["Red", "Green", "Blue"][np.argmax(avg_colors[:3])]brightness = avg_colors.mean()color_analysis = {"average_rgb": avg_colors.tolist(),"brightness": brightness,"dominant_color": dominant,}else:color_analysis = {"note": f"No color analysis for mode {mode}"}thumbnail = img.copy()thumbnail.thumbnail((100, 100))thumb_path = save_image(thumbnail, "thumbnails")thumbnail_base64 = encode_image(thumb_path)return {"dimensions": (width, height),"mode": mode,"color_analysis": color_analysis,"thumbnail": thumbnail_base64,}except Exception as e:return {"error": str(e)}@tooldef transform_image(image_base64: str, operation: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:"""Apply transformations: resize, rotate, crop, flip, brightness, contrast, blur, sharpen, grayscale.Args:image_base64 (str): Base64 encoded input imageoperation (str): Transformation operationparams (Dict[str, Any], optional): Parameters for the operationReturns:Dictionary with transformed image (base64)"""try:img = decode_image(image_base64)params = params or {}if operation == "resize":img = img.resize((params.get("width", img.width // 2),params.get("height", img.height // 2),))elif operation == "rotate":img = img.rotate(params.get("angle", 90), expand=True)elif operation == "crop":img = img.crop((params.get("left", 0),params.get("top", 0),params.get("right", img.width),params.get("bottom", img.height),))elif operation == "flip":if params.get("direction", "horizontal") == "horizontal":img = img.transpose(Image.FLIP_LEFT_RIGHT)else:img = img.transpose(Image.FLIP_TOP_BOTTOM)elif operation == "adjust_brightness":img = ImageEnhance.Brightness(img).enhance(params.get("factor", 1.5))elif operation == "adjust_contrast":img = ImageEnhance.Contrast(img).enhance(params.get("factor", 1.5))elif operation == "blur":img = img.filter(ImageFilter.GaussianBlur(params.get("radius", 2)))elif operation == "sharpen":img = img.filter(ImageFilter.SHARPEN)elif operation == "grayscale":img = img.convert("L")else:return {"error": f"Unknown operation: {operation}"}result_path = save_image(img)result_base64 = encode_image(result_path)return {"transformed_image": result_base64}except Exception as e:return {"error": str(e)}tools = [tavily_search_tool,search_wiki,save_and_read_file,transform_image,analyze_image,analyze_excel_file,analyze_csv_file,extract_text_from_image,download_file_from_url]def build_graph():
agent.py+250-3