When you ask an AI assistant a question about a spreadsheet, it often feels like magic. You ask, “Which region had the highest sales in 2025?” and the AI assistant responds. It all happens so quickly, but there is a lot that might be happening under the hood.
In this blog post, I will share what I understood while developing my own Data Analysis Agent. The goal for the agent is: the user asks a question about CSV, and the agent responds in natural language. I will be covering this in two parts
- Part 1 (Where I am now) - The foundation, and turning the LLM into an agent loop which uses tools to answer the user’s question and also fixes its own mistakes
- Part 2 - Make the agent more autonomous with planning, self-reflection, and reporting its assumptions
Throughout this project, I used dummy sales data to understand the concept. I will be using the same while explaining the article.
Lets start with the simplest version. It has four steps
- Send the user’s question and the data info (column names and data types) to the LLM and ask it to write the corresponding Python code
- The LLM will generate the Python code, save it in a file, and the Python program will run the code automatically.
- The run results will be sent to the LLM, and the LLM is prompted to explain the result.
- The program will finally print the code output along with the explanation
For example, for the user question “Which product category has the highest profit?”, the LLM writes the code as This approach works. But the LLM only writes the code. If something goes wrong in the code, our program has no way to inspect it. Consider the following scenarios.
- The code crashes -The LLM writes df[“profit”], but the column name was “Profit”. The Python code will stop with a KeyError. The user might not understand what this means
- The code runs forever -The LLM wrote a loop that never ends, and now the user has to wait forever to get a response
- The code prints too much - Lets say the LLM wrote code that prints all the rows.
- The code changes the data - The LLM code saves the cleaned data to the original data.
- Wrong Code - The LLM wrote code that gives the wrong results.
To handle some of these issues and to make this simple version work, a few things are added.
- Giving the right context to the agent - The model requires enough information about the data to generate the code. One way is to send the entire dataset to the model along with the user’s question. But this will take up more tokens and might even take up most of the context window, especially if the file is large. So the goal here is to pass all the required information for the model to generate - but nothing more. So, the user’s question, along with details like column names, column types, sample rows, etc., was sent to the model. This summary gave enough context to the model, and the Python code can read and process the data as a variable.
- Set up a Sandbox environment - A sandbox container is created when script generation is complete, and the code is ready to run. The container runs as a regular user with no network access and will be deleted after the code execution. By default, the program checks if Docker is available. If not, it falls back to a plain subprocess and runs the script.
- Put runtime and output limits - This is mainly done to prevent two things
- For code that runs forever - If the code is still running after 30 seconds, the executor stops it and records a timeout error.
- For code that prints too many things - If the code prints a lot of things (For example, printing all the rows in a dataset), the executor keeps the beginning and end of the output before sending it back to the LLM.
- Handling errors - Suppose the LLM generated code that, when executed, raises a KeyError. Without proper handling of errors, the program will raise the error and exit. The end user will get the error message instead. Instead of letting the code crash, the traceback will be captured and saved along with the generated code. This will then be sent to the LLM for explanation. With this, the user will see a clearer message rather than a standard error message. (This is still not an ideal version, and it will be fixed when we discuss agent loops)
There is still one more issue - LLM can write a code that give wrong result. As of now our program doesn’t have any way to detect this. For example, in the above dataset, if the column region had North and north, that would be treated as two separate regions in the current version. Lets see if this can be solved by an agentic workflow.
Let us first try to understand what an agent does here. In the foundation step, our program executes all the steps in a particular order.
- The user asks a question
- The question, along with required context, is sent to the LLM
- LLM completes generation
- The script is executed with some error handling
- The output is sent to the LLM, and the LLM explains the result
No agent is involved here yet. In an agent, the LLM decides what to do next given the current state. But in the current version, the LLM only generates text and doesn’t decide anything. When we say agent, it is an LLM that can make decisions and control the program flow by itself.
In an agentic workflow, the model should decide what to do next, such as ask for a schema, execute code, or return the code explanation. This may look very straightforward because we are doing the exact flow with our program. But the goal is to understand how an agent handles this flow dynamically and also to see whether it can fix mistakes by itself without human supervision
When we make the flow agentic, we also need to provide the agent with all the necessary tools that will help in the decision-making. On a high level, tools are helper functions which the agent can use whenever required. We define these functions using their names, what they do, what arguments they expect, etc. Based on this, the agent will choose any of the functions and request to call one of them. For example, execute_python is a function that will execute code. Its argument is a string containing the code that needs to be executed. In this example, once the LLM generates code, the agent decides to call execute_python next.
{"name": "execute_python", "args": {"code": "print(df['Region'].unique())"}}
In this use case, the agent has access to three tools:
inspect_dataset- This tool is used to provide the dataset summary. The model can call it whenever it requires more rows for the analysisexecute_python- This tool is used to run the Python code in a sandbox environment. It takes the code string as the input and returns the output and any errorfinal_answer- This tool is used to end the task with the answer and a list of assumptions, such as how the data was cleaned.
When specifying the tool, the most important part is the tool description. The model chose each tool based on the available tool description. At any point, the model compares its current output to the available tool description and selects the most appropriate one.
Now that we have the tools, let us try to understand the basic agentic flow
- The user query, along with the past conversations (if any), will be sent to the agent
- The agent needs to call any of the three tools.
- If the tool is
final_answer, then it stops the loop and returns the output from thefinal_answertool - Else, the program runs the tool and adds results to the conversation.
Note
- To prevent the agent from looping forever, a hard limit of 8 turns is set
- The model is always asked to call. If a tool call is not present in the model response, it is prompted again to use a tool or call
final_answer
In each turn, the full conversation is sent again: the question, every tool call, and every result. So the model always sees everything it has done so far.
Lets see how the agent handles the “writing wrong code” scenario**.**
In the example dataset there was a column - region. The baseline model treated “north” and “North” as two different regions. The agent will handle this as follows -
Question - What is the total sales in each region?
Turn 1: The agent calls the inspect_dataset tool and execute using execute_python.
Turn 2: The agent then write the code and then again calls execute_python. The output showed 7 groups in total: east, East, north, North, and so on and the output is passed back to the agent.
Turn 3: The agent now notices the problem. It again write the code that converts the names to lowercase and removes the spaces. Then it call execute_python again and check output. Now there are exactly 4 regions.
Turn 5: It calls final_answer with the correct totals for all four regions.
No errors occurred in any of these steps. The code ran successfully every time. The agent fixed the answer because it reviewed the output and saw it didn’t make sense. This is the real difference between a script and an agent. A script runs its code and reports whatever comes out. An agent can look at the result and decide that it is not done yet.
But this does have a cost. The conversation grows with every turn, and so the tokens add up.
The loop gives the model a chance to fix its mistakes. But not every failure is the model’s mistake, and not every mistake gets fixed by trying again. Mainly, there are two types of errors that I observed.
Errors that are nobody’s fault
Sometimes the LLM API is busy and returns an error like 503 (service unavailable) or 429 (too many requests). In the baseline evaluation, this stopped the whole run, and we had to manually run the same.
But in the agentic version, the agent will retry the same request up to three times, waiting 2, 4, and then 8 seconds. Other errors, such as an invalid API key, are not retried because retrying will not help here.
Errors in the model’s code
When the model’s code fails, the error is sent back to the model so it can fix it. Usually that works. But sometimes the model gets stuck: it makes the same mistake again and again, or generates the same code again.
So the agent keeps track of two things:
- Repeated code: Before running code, the agent compares it with the code that has already run. If it is the same, the code is not run again. Instead, the model is prompted: “This exact code already ran; change your approach.”
- Repeated errors: The agent compares the last line of each error, for example, KeyError: ‘region’. After the same error twice in a row, it adds a hint suggesting a different approach. After three times, it stops the run.
Look at the region example again, which required multiple turns. In every turn, the model’s code started with the same line:
df = pd.read_csv("retail_sale.csv")
This is because every run started as a fresh process. When the process ended, everything in memory was gone, including the cleaned data from the previous step. This is again a problem. The agent should have a continuous memory of whatever was done before.
Saving the Variables
The common solution is a persistent session in which one Python process stays alive and runs each new piece of code in the same memory. But this has other challenges. A process that stays alive is harder to stop cleanly after a timeout, and a crash in one step can leave the memory in a broken state.
So, instead, each step still runs in a fresh, sandboxed process. But the agent doesn’t start from a fresh state.
- After the LLM code generation: Save all variables again, such as dataframes, numbers, lists, and dictionaries.
- Before the LLM code generation: Load the variables saved by earlier steps.
The variables are saved to a file in the run folder, using Python’s pickle module.
But if the model’s code crashes, it never reaches the “save” part. So a failed step never changes the saved state, and the next step starts from the last version that worked. After each step, the model also sees a short list of what is in memory, for example, df: DataFrame (2000, 8). The model no longer has to remember what it created. It can see it. Here, only the variables are saved. Functions and imports are not. So, in every step, pandas and numpy are imported automatically.
Conclusion #
This agent is still far from perfect. It can do very basic tasks, but it cannot plan its analysis before starting; it does not check its numbers, and it does not clearly tell us what it assumed. That is the goal for Part 2 - an agent that plans, cleans the data deliberately, verifies its own results, and reports its assumptions.
Thank you for reading this post! Let me know if you liked it, have questions, or spotted an error. Please feel free to contact or follow me on LinkedIn.