Build an AI Agent for Strategic Budget Planning with LangGraph and n8n

What if a simple Email was the interface for complex budget planning, with an AI agent handling the optimisation behind the scenes?

Build an AI Agent for Strategic Budget Planning with LangGraph and n8n
If I could just send ‘Run 2026 budget with XXX caps and Y% on Sustainability’ and get a decision back, that would change our budget review.

That is how the VP Supply Chain of an international retailer framed the problem when we discussed automating budget planning for their annual CAPEX approval cycle.

Example of CAPEX Application — (Image by Samir Saci)

Because companies must invest in expensive equipment, directors receive budget applications from operational teams for short and long-term plans.

This is a complex exercise, as decision makers need to balance return on investment (ROI) with long-term strategy.

As a data scientist, how can you help large companies “partially automate” this decision-making process.

We can use linear programming to help decide which projects to fund to maximise ROI while respecting multi-year budget constraints.

In this article, I will introduce an AI Agent for Budget Planning that turns email requests into an optimised Capital Expenditure (CAPEX) portfolio.

This AI-powered workflow is built using LangGraph coupled with n8n (for orchestration) to create a reasoning agent connected to a FastAPI microservice that executes a linear programming model.

Objective of the Workflow — (Image by Samir Saci)

I will first introduce the problem with an actual example of a budget planning review.

We will then review the architecture and explore the results using a real request for budget optimisation with a constraint of a minimum 20% allocation for sustainability projects.

Budget Planning Optimisation with Python

Problem Statement: Operational Budget Planning

For this exercise, we are helping a regional director of an international logistics company based in the Asia Pacific.

This company provides warehousing and transportation services to other companies across four different countries.

Scope of the example — (Image by Samir Saci)

These operations support 48 customers grouped in over eight market verticals (Luxury, Cosmetics …).

Within their scope, for instance, they manage a 30,000 sqm distribution centre for a large luxury fashion retailer in Guangzhou, which delivers to 50 stores in South China.

Guangzhou Site Manager: We need 150k euros for a new conveyor belt that will increase our receiving productivity by 20%.

Every year, in December, he receives an Excel file titled "CAPEX Applications."

Examples of CAPEX Application — (Image by Samir Saci)

This file contains a list of all the projects that require capital expenditure (CAPEX) from 17 warehouse managers across the APAC region.

For each project, the application includes a brief project description, a three-year cost profile, and the projected Return On Investment.

These projects can also bring additional benefits:

  • Business Development: unlock new revenue (e.g., capacity for a new customer or product line)
  • Sustainability (CO₂ Reduction): lower emissions via energy-efficient equipment or layout changes
  • Digital Transformation: improve data visibility, automate repetitive tasks, and enable AI-driven decisions
  • Operational Excellence: increase throughput, reduce defects and rework, shorten changeovers, and stabilise processes.
  • HSE (Health, Safety & Environment): reduce incident risk and insurance exposure with safer equipment
  • CSR (Corporate Social Responsibility): strengthen community and workforce initiatives (e.g., training, accessibility)

A warehouse automation project can reduce the usage of packaging material (sustainability), decrease operator fatigue (CSR), and accelerate digital transformation.

These benefits are linked to the top management guidelines that our director needs to follow.

APAC Director: “How should I allocate my budget of XX M€ to maximise the ROI while respecting my top management guidelines?

As the director receives over 50 projects each session, we proposed to build a linear programming module to determine the optimal selection, taking into account external constraints.

Objective of the solution — (Image by Samir Saci)

As inputs, we get the available budget and the management objectives, along with the spreadsheet of CAPEX applications.

Example of CAPEX Application Spreadsheet — (Image by Samir Saci)

This will be part of the inputs of our solution.

FastAPI Microservice: 0–1 Mixed-Integer Optimiser for CAPEX Budget Planning

I designed this module using the PuLP library of Python.

The solution is packaged in a FastAPI microservice deployed on the cloud.

Decision Variables

For each project i, we define a binary value to inform if we allocate a budget or not:

Decision Variables — (Image by Samir Saci)

Objective Function

The objective is to maximise the total return on investment of the portfolio of projects we selected:

Objective Function — (Image by Samir Saci)

Constraints

As we cannot spend more than what we have allocated per year, we must consider the budget constraints for the next three years.

Constraints — (Image by Samir Saci)
APAC Director: “The CEO want us to invest 20% of our budget on projects supporting our sustainability roadmap.”

Moreover, we may also have constraints on the minimum budget for specific management objectives.

Example of Constraint for Sustainability — (Image by Samir Saci)

In the example above, we ensure that the total investment for sustainability projects is equal to or greater than S_min.

Now that we have defined our model, we can package it as a FastAPI microservice using the code shared in this article.

This overall workflow will accept a specific schema defined using Pydantic for validation and defaults.

LaunchParamsBudget captures the optimisation inputs:

  • The three annual budget caps (budget_year1/2/3 in euros)
  • The optional minimum-allocation rule toggled by set_min_budget with its target management objective min_budget_objective and the required share min_budget_perc in %.

We need to ensure that the Agent respects this schema; if not, it will be unable to query the API.

What can we expect as outputs?

The agent will receive the details of the allocated budget, including the annual split, along with information on the selected projects.

With these results and a proper system prompt, our agent can provide a concise summary of the budget allocation to the VP of Logistics.

Building an Agentic Workflow with LangGraph and n8n

End-to-End Workflow Description

Let us assume that our Asia Pacific Director received a spreadsheet with all the CAPEX applications.

Example of CAPEX Application Spreadsheet — (Image by Samir Saci)

The idea is to receive the hypotheses regarding the budget amount and constraints in plain English via email, along with the spreadsheet attached.

Email request with 20% on sustainability — (Image by Samir Saci)

Based on this email, the workflow should automatically select projects for optimal budget allocation.

Project Selected or Not (✅/❌)— (Image by Samir Saci)

The director also expects a concise explanation of the choices made to build this optimal investment portfolio.

Example of Summary Generated by the Agent — (Image by Samir Saci)

We can build an automated workflow using LangGraph and n8n for orchestration to perform these tasks.

Objective of the workflow — (Image by Samir Saci)

This will be a workflow in 4 steps:

  • Step 1: Using the n8n Gmail node, we send the email body and the spreadsheet attached to the FastAPI Backend
  • Step 2: An AI Agent Parser will collect the parameters from the email and call the other API for Budget Planning
  • Step 3: The outputs will be sent to an AI Agent Summarizer that will use them to generate the summary
  • Step 4: The user receives a reply by email with the summary via a Gmail node in n8n

The core LangGraph agentic workflow will be implemented within a FastAPI microservice, which will be wrapped in an n8n workflow for orchestration.

n8n orchestration workflow — (Image by Samir Saci)

The first two nodes on the top will extract the content of the spreadsheet and upload it to the API.

Then, we extract the email content in the Extract Email Body node and send it to the agent endpoint using the node Query AI Agent.

The outputs of the API include:

  • A detailed explanation of the optimal budget allocation that is sent by email using the Reply node
  • A JSON with the allocation by project used by the node Update Allocation to add the ✅ and ❌ in the spreadsheet

Ultimately, our director receives a comprehensive analysis of the optimal portfolio, which includes three distinct sections.

Budget Summary — (Image by Samir Saci)

A Budget Summary provides details on the allocated budget and the return on investment.

Portfolio Composition — (Image by Samir Saci)

The Portfolio Composition details the number of projects awarded per management objective.

Recommendation — (Image by Samir Saci)

Finally, the agent concludes with a Recommendation based on its understanding of the objective.

Let us see how we built the core LangGraph Budget Agent, which parses an email to return a complete analysis.

Budget Planning AI Agent with LangGraph

The code shared in this section has been greatly simplified for concision.

Before creating the graph, let us build the different blocks:

  • EmailParser is used to parse the email body received from the n8n HTTP node to extract the parameters of the Budget API
  • BudgetPlanInterpreter will call the API, retrieve the results and generate the summary

For your information, I have used this approach with standalone blocks because we reuse them in other workflows that combine multiple agents.

Block 1: AI Agent Parser

Let us build the block for this agent that we will call AI Agent Parser:

We include the parameters that will be used for the Graph State variables.

This block EmailParser turns a plain-text email body into typed, schema-valid parameters for our Budget Planning API using an LLM.

  1. On initialisation, we load the chat model from the config and build a LangChain chat model.
  2. The function parse() takes the raw email content sent by n8n HTTP node and the system prompt to invoke the model with structured outputs defined with the LaunchParamsBudget Pydantic schema.

The EmailParser system_prompt stored in the YAML config file (minimal version for concision):

It includes a list of fields to parse, along with concise explanations and strict format rules.

The output looks like this:

This will be sent to the second agent for call tooling (our other FastAPI Microservice) and results interpretation.

Block 2: Block for Tool Calling and Interpretation

Two blocks will be used to call the Budget Planning API and to process the API’s output.

As I will be using this Budget Planning API for multiple agents, I created a standalone function to call it.

We can now call this function in the block BudgetPlanInterpreter defined below.

It runs the budget optimiser and turns its JSON into an “executive summary” in HTML format.

  • We use run_plan() to call the FastAPI microservice utilising the function run_budget_api(s) to retrieve the results
  • The function interpret() generates the analysis based on the API's outputs, following the instructions of a system prompt.

We now have our three foundation blocks that can be used to build a graph with nodes and conditional edges.

LangGraph Builder with nodes and conditional edges

Now that we have the three blocks, we can build our graph.

LangGraph — (Image by Samir Saci)

This is a small experimental LangGraph state machine that includes the three steps (parsing, running, interpretation) with error handling at every step.

This block is fundamental as it defines the shared state passed between LangGraph nodes

  • session_id: included in the API call
  • email_text: raw email body received from the n8n node
  • params: structured inputs parsed from the email by EmailParser
  • budget_results: JSON output of the FastAPI microservice
  • html_summary: the analysis (in HTML format) generated by interpret() based on the output budget_results
  • error: storing an error message if needed

We should now define the functions of each node that will receive the current AgentState and return a partial update.

Function : handle_error(state)

  • Returns an error message in HTML format, which will be sent to the Gmail node in n8n to notify the user
Example of error message — (Image by Samir Saci)

In this case, for the support team, it is more practical as the user just has to forward the email.

Note: In the production version, we have added a run_id to help track the issues in the logs.

Function 2: parse_email(state)

  • Uses EmailParser to transform the email body received into parameters for Budget Planning in JSON format
  • On success: returns {"params": …} used to call the FastAPI Microservice

Function 3: run_budget(state)

  • Uses BudgetPlanInterpreter to call the function run_plan that will execute the budget optimisation via the FastAPI microservice
  • On success: returns the output of the optimiser in JSON format as budget_results

This output can be used to generate a summary of the budget allocation.

Function 4: summarize(state)

  • Reuses interpreter from state (or creates one), then calls interpret()
  • On success: returns a concise and professional summary of the budget allocation in HTML format, ready to be sent by email {"html_summary": …}

This output html_summary is then returned by the API to the Gmail node on n8n to reply to the sender.

Now that we have all the functions, we can create the nodes and “wire” the Graph using the function build_budagent_graph() defined below:

These four nodes are connected using Routers:

  • route_after_parse will direct the flow based on the output of the email parsing: if error in state → go to "error"; else → "run".
  • route_after_run will direct the flow based on the output of the FastAPI Microservice calling: if error in state → go to "error"; else → "summarize".

We are nearly done!

We need to package this in a FastAPI endpoint:

It will be queried by the Query Agent API node of our n8n workflow to return input parameters in params, Budget Optimiser results in budget_results and the summary generated by the Agent Interpreter in html_summary.

A fully functional AI Workflow for Budget Planning

We can now activate the workflow on n8n and test the tool with different scenarios.

What if we don’t have a minimum budget for any management objectives?

I will try to adapt the email to have set_min_budget at False.

Example of email — (Image by Samir Saci)

The email has been well parsed with now set_min_budget at the value False.

And we can see the results in the summary:

Results of the new run - Image by Samir Saci

As we could expect, the performance is better:

  • Total ROI: €1,050,976 (vs. €1,024,051)
  • ROI/€: €0.26 (vs. €0.24)

Conclusion

This workflow has been presented to the regional team, who started to “play with it”.

We learned that they use it to prepare slides with different scenarios of portfolio allocation for the board meetings.

This remains a “strategic tool” that is used only a couple of times per year.

However, we plan to reuse the same architecture for more “tactical” tools that supply chain departments can use for ABC Analysis, Stock Management, or Supply Chain Optimisation, as well as human resources for Workforce Planning or business controlling teams.

Can we go beyond this simple workflow?

I am still not satisfied with the contribution of the Agentic part of the workflow.

Indeed, it’s nice to have a tool that can be triggered by an email and provide a concise summary.

However, I would like to explore the idea of having multiple agents proposing different scenarios that would compete against each other.

What would be the impact on the ROI if we increase the minimum budget of sustainability by 15%?

For instance, we can ask agents to run multiple scenarios and provide a comparative study.

We are still experimenting with various types of orchestration to determine the most efficient approach.

For instance, we tested the MCP Servers in the example below.

This will be the topic of the following articles.

Other examples of Agentic Workflows?

This is not the first time I am trying to link an optimisation tool (packaged in a FastAPI Microservice) with an Agentic Workflow.

My initial attempt was to create a Production Planning Optimisation Agent.

Production Planning Agent — (Image by Samir Saci)

Like here, I packaged an optimisation algorithm in a FastAPI Microservice that I wanted to connect to an email workflow.

Production Planning FastAPI Microservices — (Image by Samir Saci)

Unlike here, the Agentic part of the workflow was handled in n8n with two Agent nodes.

Workflow — (Image by Samir Saci)

The results were quite satisfying, as you can see in the short video linked below.

The user experience was very smooth.

However, the maintenance proved to be challenging for the team.

This is why we wanted to explore the use of Python and TypeScript frameworks for the agentic workflow, like here.

What’s next? Agentic Approach of Business Planning

At our startup, LogiGreen, we are attempting (through experiments like this one) to extend beyond supply chain optimisation and encompass business decision-making.

On my roadmap, I have a tool that I have developed to help small and medium-sized company optimise their cash flow.

In another article published in Towards Data Science, I have introduced how I used Python to simulate the financial flows of a company selling renewable paper cups to coffee shops.

“We have to refuse orders as we don’t have enough cash to pay suppliers for stock replenishment.”

A close friend, who owns a small business, was complaining about cash flow issues limiting the development of his company.

I started by tackling the problem of inventory management with an optimised built-in solution using Python.

Inventory Management Rule — (Image by Samir Saci)

Then I enriched the model considering sales channel strategy, payment terms and many other strategic business parameters to help him find the optimal business plan to maximise profitability.

Example of scenarios generated — (Image by Samir Saci)

This solution is the next candidate in our experimentation with using agentic workflows to support business and operational decision-making.

For more information, you can view this brief presentation of the tool.

Currently, it is packaged in a FastAPI microservice connected to a React frontend (and streamlit for the public demo).

UI of the tool available in LogiGreen Apps — (Image by Samir Saci)

I would like to implement an AI workflow that would

  1. Take multiple scenarios (like the ones presented in the video)
  2. Call the API for each scenario
  3. Collect and process the results
  4. Provide a comparative analysis to recommend the best decision

Basically, I would like to outsource to a single (or multiple agents) the complete study presented in the article and the video.

For that, we are exploring multiple approaches to agent orchestration.

We will share our findings in a future article. Stay tuned!

About Me

Let’s connect on Linkedin and Twitter. I am a Supply Chain Engineer who uses data analytics to improve logistics operations and reduce costs.

For consulting or advice on analytics and sustainable supply chain transformation, feel free to contact me via Logigreen Consulting.

If you are interested in Data Analytics and Supply Chain, look at my website.

Samir Saci | Data Science & Productivity