Skip to content

Lab 2 Analyize & Visualize Data

What You'll Learn

In this lab, you will:

  • Enable the Code Interpreter for the agent
  • Configure the agent to generate and execute Python code for data analysis and visualization
  • Use natural language to create charts and analyze sales data
  • Download and review generated files (charts, JSON, etc.)
  • Explore how the agent orchestrates SQL, Python, and chart generation

Introduction

The Foundry Agent Service Code Interpreter enables the LLM to safely execute Python code for tasks such as creating charts or performing complex data analyses based on user queries. It uses natural language processing (NLP), sales data from a PostgreSQL database accessed through MCP (Model Context Protocol), and user prompts to automate code generation. The LLM-generated Python code executes within a secure sandbox environment, running on a restricted subset of Python to ensure safe and controlled execution.

Lab Exercise

In this lab, you'll enable the Code Interpreter to execute Python code generated by the LLM for analyzing Zava's retail sales data.

  1. Open the app.py.

  2. Define a new instructions file for our agent and add the code interpreter in the agent's toolset. Uncomment the following lines by removing the "# " characters.

    # INSTRUCTIONS_FILE = "instructions/mcp_server_tools_with_code_interpreter.txt"
    
    # code_interpreter = CodeInterpreterTool()
    # toolset.add(code_interpreter)
    

    Warning

    The lines to be uncommented are not adjacent. When removing the # character, ensure you also delete the space that follows it.

  3. Review the code in the app.py file.

    After uncommenting, your code should look like this:

    INSTRUCTIONS_FILE = "instructions/mcp_server_tools.txt"
    INSTRUCTIONS_FILE = "instructions/mcp_server_tools_with_code_interpreter.txt"
    
    
    async def add_agent_tools() -> None:
        """Add tools for the agent."""
        global mcp_tools
    
        # Fetch and build MCP tools dynamically
        mcp_tools = await fetch_and_build_mcp_tools()
    
        # Add the MCP tools to the toolset
        toolset.add(mcp_tools)
    
        # Add the code interpreter tool
        code_interpreter = CodeInterpreterTool()
        toolset.add(code_interpreter)
    

TBD

Run the Agent App

  1. Press F5 to run the app.
  2. In the terminal, the app will start, and the agent app will prompt you to Enter your query.

Start a Conversation with the Agent

Show the top 10 products by revenue by store

Try this question:

  1. Show sales by region as a pie chart

    Once the task is complete, the file will be saved in the shared/files subfolder. Note that this subfolder is created the first time this task is run, and is never checked into source control.

    Open the folder in VS Code and click on the file to view it. (Tip: in Codespaces, you can Control-Click the link that the agent outputs in its response to view the file.)

    Info

    This might feel like magic, so what’s happening behind the scenes to make it all work?

    Foundry Agent Service orchestrates the following steps:

    1. The LLM generates a SQL query to answer the user's question. In this example, the query is:

      SELECT region, SUM(revenue) AS total_revenue FROM sales_data GROUP BY region;

    2. The LLM asks the agent app to call the async_fetch_sales_data_using_sqlite_query function. The SQL command is executed, and the resulting data is returned to the LLM.

    3. Using the returned data, the LLM writes Python code to create a Pie Chart.
    4. Finally, the Code Interpreter executes the Python code to generate the chart.
  2. Download as JSON

    Once the task is complete, check the shared/files folder to see the downloaded file.

    Info

    The agent inferred from the conversation which file you wanted to create, even though you didn't explicitly specify it.

  3. Continue asking questions about Zava sales data to see the Code Interpreter in action. Few examples:

    • Determine which products or categories drive sales. Show as a Bar Chart.
    • What would be the impact of a shock event (e.g., 20% sales drop in one region) on global sales distribution? Show as a Grouped Bar Chart.
      • Follow up with What if the shock event was 50%?
    • Which regions have sales above or below the average? Show as a Bar Chart with Deviation from Average.
    • Which regions have discounts above or below the average? Show as a Bar Chart with Deviation from Average.
    • Simulate future sales by region using a Monte Carlo simulation to estimate confidence intervals. Show as a Line with Confidence Bands using vivid colors.

Debugging the Code Interpreter

You can’t directly debug the Code Interpreter, but you can gain insight into its behavior by asking the agent to display the code it generates. This helps you understand how it interprets your instructions and can guide you in refining them.

From the terminal, type:

  1. show code to see the code generated by the Code Interpreter for the last operation.

Stop the Agent App

When you're done, type exit to clean up the agent resources and stop the app.