Data analysis agents can help process, analyze, and extract insights from data. In this lesson, we’ll learn how to build agents that can work with data effectively.
Let’s start by building a simple data analysis agent:
from praisonaiagents import Agent# Create a basic data analysis agentdata_analysis_agent = Agent( name="DataAnalyst", instructions=""" You are a data analysis specialist who interprets and explains data. When analyzing data: 1. First understand what the data represents 2. Identify key patterns, trends, or anomalies 3. Generate meaningful insights 4. Explain findings in simple, clear language 5. Provide actionable recommendations when appropriate """)# Use the data analysis agent with sample datasample_data = """Monthly Sales Data (2024):January: $12,500February: $13,200March: $15,800April: $14,300May: $16,700June: $18,900"""analysis = data_analysis_agent.start( f""" Analyze the following sales data and provide insights: {sample_data} Questions to answer: 1. What is the overall sales trend? 2. Which month had the highest sales? 3. What is the average monthly sales? 4. What recommendations would you make based on this data? """)print(analysis)
Let’s enhance our agent with basic data processing capabilities:
from praisonaiagents import Agent, Tool# Define a simple calculation tooldef calculate_statistics(data_string): """ Calculate basic statistics from a string of numbers. Args: data_string (str): A string with numbers separated by commas Returns: str: Statistical summary """ try: # Convert string to list of numbers data = [float(x.strip()) for x in data_string.split(',')] # Calculate statistics total = sum(data) average = total / len(data) minimum = min(data) maximum = max(data) return f""" Statistical summary: - Count: {len(data)} - Sum: {total} - Average: {average:.2f} - Minimum: {minimum} - Maximum: {maximum} - Range: {maximum - minimum} """ except Exception as e: return f"Error processing data: {str(e)}"# Create the toolstats_tool = Tool( name="calculate_statistics", function=calculate_statistics, description="Calculate basic statistics from a list of numbers (comma-separated)")# Create an agent with the statistics toolenhanced_data_agent = Agent( name="EnhancedDataAnalyst", instructions=""" You are a data analysis specialist who interprets and explains data. When analyzing data: 1. First understand what the data represents 2. Use the calculate_statistics tool for numerical data 3. Identify key patterns, trends, or anomalies 4. Generate meaningful insights 5. Explain findings in simple, clear language 6. Provide actionable recommendations when appropriate """, tools=[stats_tool])# Use the enhanced data agentnumerical_data = "12500, 13200, 15800, 14300, 16700, 18900"enhanced_analysis = enhanced_data_agent.start( f""" Analyze the following monthly sales data for the first half of 2024: {numerical_data} Provide a complete analysis with trends and recommendations. """)print(enhanced_analysis)
market_analysis_agent = Agent( name="MarketAnalyst", instructions=""" You are a market trend analyst who specializes in identifying patterns and making predictions. When analyzing market data: 1. Identify long-term trends and short-term patterns 2. Compare data points to industry benchmarks 3. Identify potential causes for changes 4. Assess future implications 5. Provide strategic recommendations Present your analysis with clear sections for: - Overall Market Assessment - Key Trends Identified - Growth Opportunities - Risk Factors - Strategic Recommendations """, tools=[stats_tool])# Use the market analysis agentmarket_data = """Industry Growth Rates (2021-2024):2021: 3.2%2022: 2.8%2023: 4.5%2024: 5.1%Our Company Growth:2021: 2.9%2022: 3.1%2023: 4.8%2024: 6.3%Competitor A Growth:2021: 3.5%2022: 3.7%2023: 4.2%2024: 4.5%Competitor B Growth:2021: 3.0%2022: 2.5%2023: 5.0%2024: 5.8%"""market_analysis = market_analysis_agent.start( f""" Analyze the following market and company growth data: {market_data} Provide a comprehensive market analysis and strategic recommendations. """)print(market_analysis)
While our agents can’t directly create visualizations, they can recommend appropriate visualization types:
visualization_agent = Agent( name="VisualizationAdvisor", instructions=""" You are a data visualization specialist who helps select the best ways to visually represent data. When recommending visualizations: 1. Understand the nature of the data (categorical, numerical, time-series, etc.) 2. Consider the key relationships or patterns to highlight 3. Recommend the most appropriate chart or graph type 4. Explain why your recommendation is effective 5. Provide suggestions for layout, color scheme, and labeling Common visualization types to consider: - Line charts (for trends over time) - Bar charts (for comparing categories) - Pie charts (for showing composition, use sparingly) - Scatter plots (for showing relationships between variables) - Heatmaps (for showing patterns in complex data) - Box plots (for showing distributions) """)# Use the visualization agentviz_recommendations = visualization_agent.start( """ I have the following data and need visualization recommendations: 1. Monthly sales data for the past year 2. Customer satisfaction ratings across 5 product categories 3. Market share compared to 3 competitors 4. Customer age distribution What visualizations would you recommend for each of these datasets and why? """)print(viz_recommendations)