Skip to content
LangChain

Data Analysis Agent with LangChain

Build an AI data analysis agent that processes datasets, runs Python computations, generates charts, and produces insights — powered by LangChain.

data analysisPythonchartsanalytics

Working Code

LangChain
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
@tool
def execute_python(code: str) -> str:
"""Execute Python code for data analysis. pandas and matplotlib are available."""
import subprocess
result = subprocess.run(
["python", "-c", code],
capture_output=True, text=True, timeout=30,
)
return result.stdout or f"Error: {result.stderr}"
@tool
def read_csv_info(path: str) -> str:
"""Get info about a CSV file (columns, types, shape)."""
import pandas as pd
df = pd.read_csv(path)
return f"Shape: {df.shape}\nColumns: {list(df.columns)}\nTypes:\n{df.dtypes}"
model = ChatOpenAI(model="gpt-4o")
model_with_tools = model.bind_tools([execute_python, read_csv_info])
response = model_with_tools.invoke([
("system", "You are a data analyst. Explore datasets using read_csv_info, then use execute_python to run analysis code. Present findings clearly with numbers."),
("user", "Analyze sales_data.csv and find the top performing products by revenue"),
])

Step by Step

1

Install dependencies

Install LangChain and the required tools for this use case.

2

Define your tools

Create the domain-specific tool functions your agent will use to interact with external services.

3

Create the agent and run

Initialize the LangChain agent with your tools, set the system prompt, and execute a query.

Ready to build with LangChain?

Generate a production-ready project with LangChain pre-configured — FastAPI + Next.js, auth, streaming, and more.

Get Started

Ready to build your first production AI agent?

Open-source tools, battle-tested patterns, zero boilerplate. Configure your stack and ship in minutes — not months.