# Introduction to Langchain Deep Agents

> Source: <https://pub.towardsai.net/introduction-to-langchain-deep-agents-ad5090403038?source=rss----98111c9905da---4>
> Published: 2026-09-09 18:01:02+00:00

Langchain introduced Managed Deep Agents a few days ago. In this article, I will go through the basics of Deep Agents and use them in a simple use case.

Many of you reading this article will be familiar with agents. Agents are programs that are designed to achieve an output based on instructions provided by the user. Agents are special because they can use tools like a normal person would.

Deep Agents is a framework created by LangChain which gives us a batteries-included approach to creating AI agents. It supports all the important features which an agent needs — tool usage, context management and delegation of tasks to subagents.

In other words, Deep Agents provides a “harness” which acts as a guiding principle for the agent. It ends up saving us a lot of time and effort while creating agents.

I’ll consider a simple supply chain problem.

A planner has a small spreadsheet with current inventory, average daily demand, and supplier lead time for a handful of SKUs. Instead of manually calculating which items are at risk of stocking out, they ask a Deep Agent: *“Look at this inventory file and tell me which SKUs are at risk of stockout in the next 2 weeks, and draft an alert email for the ones that are critical.”*

Anyone who has run an S&OP cycle knows the real bottleneck isn’t the math, it’s the manual grind. Pulling inventory numbers, checking them against the demand forecast, deciding what’s urgent and then writing up an email or report so someone else can act on it. Each step is simple. Doing all of them, correctly and on time, every single day, is where things break down.

This is where something like an agent can help because it can plan out its tasks and approach the problem just like a junior analyst would.

In this example I will use *Managed Deep Agents.* It is an offering from LangChain which bundles the agent harness and the infrastructure into a platform so that I can focus more on the business part of the problem.

I don’t have to worry about deploying the agent as it will be available in LangSmith deployments. And I’ll be able to use a UI for changing things around which can be quite useful.

I’ll explain things as I go through this article. First, we need to set up everything needed to run our agent.

We need the following things for running Deep Agents

I am going to assume that you know how to get these. It’s actually quite simple. There are tons of videos on YouTube on how to do this.

I like putting a lot of comments in the code to make sure I don’t miss anything if I make any changes to it later.

First, I’ll open VSCode and create a virtual environment using the terminal. (You need to make sure you have uv installed in your system).

``` bash
$ uv tool install managed-deepagents$ mda init stockout-watcher$ cd stockout-watcher
```

This creates a basic scaffold for the project. My final project structure will look something like the one shown below.

```
stockout-watcher/├── agent.py                        # Core agent definition├── instructions.md                 # Managed context├── identity.py├── pyproject.toml├── tools   ├── __init.py__   ├── check_stockout_risk.py   ├── send_mail.py                # Dependencies and secrets├── .env
```

I’ll add the API keys to my .env file.

```
LANGSMITH_API_KEY=<LANGSMITH_API_KEY> ANTHROPIC_API_KEY=<ANTHROPIC_API_KEY>
```

Now, I’ll load the dataset and see what kind of data I’m working with (I’ve taken a simple dataset for this article).

``` python
import osimport pandas as pd
df = pd.read_csv("directory/inventory_data.csv")print(df)
```

So I have a small dataset with 12 SKUs. We have 3 inputs per row: the current stock, average daily demand and supplier lead time. I think that information should be enough for my agent to calculate days-of-cover and flag any risks.

This is the point where I lay out a process of how my agent is going to think and perform its tasks. It should be somewhat similar to how a junior analyst might go about.

Read the inventory file → Calculate days-of-cover for each SKU → Identify which SKUs fall below a safety threshold → Draft an email for the at risk items

With this in mind, I will go ahead and build the system logic

First, I’ll write the ***system instructions*** for the agent. The system prompt tells the agent what role it is playing and how it should approach the task. I’ll edit the instructions.md file.

```
You are a supply chain risk analyst. Your job is to review inventory data and identify SKUs at risk of stocking out before replenishment can arrive. When given an inventory file: 1. Use the check_stockout_risk tool to calculate days-of-cover for every SKU. 2. Write a short report to a file named risk_report.md summarizing the results for all SKUs. 3. Draft a plain-language alert email listing only the SKUs flagged AT RISK, explaining why each one needs attention. Be concise and avoid unnecessary technical jargon in the email - it will be read by a supply chain planner, not an engineer.
```

The agent, by itself can’t run and understand calculations. So I need to give it ***tools*** which will help it perform its tasks. Giving it a tool ensures that it doesn’t just eyeball the math but rather gives us a precise number. I’ll create a tools folder and inside, I’ll create a new filecheck_stockout_risk.py

```
##tools/check_stockout_risk.pyimport pandas as pddef check_stockout_risk(file_path: str) -> str:    """    Reads an inventory CSV and calculates days-of-cover for each SKU,    comparing it against supplier lead time to flag stockout risk.    Args:        file_path: Path to the inventory CSV file.    Returns:        A string summary of each SKU's days-of-cover and risk status.    """    df = pd.read_csv(file_path)    df["Days_Of_Cover"] = df["Current_Stock_Units"] / df["Avg_Daily_Demand_Units"]    df["At_Risk"] = df["Days_Of_Cover"] < df["Supplier_Lead_Time_Days"]    lines = []    for _, row in df.iterrows():        status = "AT RISK" if row["At_Risk"] else "OK"        lines.append(            f"{row['SKU_ID']} ({row['Product_Name']}): "            f"{row['Days_Of_Cover']:.1f} days of cover, "            f"lead time {row['Supplier_Lead_Time_Days']} days - {status}"        )    return "\n".join(lines)
```

Now the agent has everything it needs to do its task. So, I’ll modify the agent.py file where I’ll import the tool and add it to the agent.

``` python
## agent.pyfrom managed_deepagents import define_deep_agentfrom tools.check_stockout_risk import check_stockout_riskagent = define_deep_agent(    name="stockout-watcher",    model="claude-sonnet-5",    tools=[check_stockout_risk])
```

I think I’ll test out my agent at this point. Using the commands below.

``` bash
$ uv sync$ mda dev
```

This will compile the agent and automatically launch a browser window with the LangSmith Studio open. This is where we can talk to the agent.

When I point it to my file, I can see it does some kind of a calculation to come up with some results.

And I can see it is giving me some kind of analysis.

It means that the agent is acting like it is supposed to. There is still the matter of sending out the mail because right now, the result is still contained within LangSmith Studio.

I’ll use **Resend** as my mailing service. Resend is a platform which will help our agent send out mails. It’s quite easy to configure and set up for sending the email notification.

What I will do here is *set up my Resend service as a tool* for the agent to use. For that, I’ll have to create an account on Resend and get an API key.

``` python
## tools/send_mail.pyimport resendimport osfrom dotenv import load_dotenvfrom langchain.tools import toolload_dotenv()resend_api_key = os.getenv("RESEND_API_KEY")resend.api_key = resend_api_key@tooldef send_mail(body: str) -> str:    """    Sends an email to a recipient/list of recipients    Args:        to: The receiver's email address        subject: the email subject        body: the email body    Returns:        None    """    params = resend.Emails.SendParams = {        "from": "Acme <onboarding@resend.dev>",        "to": "arunabh223@gmail.com",        "subject": "Stock Watcher Update",        "html": body    }    email = resend.Emails.send(params)    return("Email sent successfully")
```

We can have a pre-defined mailing list. I am defining the *From* address as “onboarding@resend.dev” as I don’t currently have an active domain. So I will use the address provided by Resend to test my agent.

With everything in place, I’ll go to LangSmith Studio again and start talking to my agent. I repeat the same steps as last time.

``` bash
$ mda dev
```

We can see that this time, the agent will use the send_mail tool to compose and send the mail.

I’ll cross-verify it on my Resend dashboard too.

And finally, I’ll check my inbox.

The catch here is that the mail is going into my Spam folder. This might be because the mail is not being sent from a valid domain. Of course, this is open to further investigation. But for the sake of simplicity, I’ll not go into that now. The formatting of the mail body could also use some work.

What matters is that the workflow we have created works. The agent is able to read the file and use the tool provided to send a mail. Which was the purpose of this tutorial.

With this we are wrapping up this article! I hope this was useful to all the readers. You now have a solid baseline for running LangChain’s Managed Deep Agents.

Whether you want to automate inventory monitoring or build entirely different workflows, the framework takes care of the heavy lifting so you can focus on building.

Try giving it a spin with your own use cases, experiment with different tools and see what you can automate next. Happy coding!

*Drop a comment below if you run into any questions or build something cool. I’d love to hear how you are using it.*

[Introduction to Langchain Deep Agents](https://pub.towardsai.net/introduction-to-langchain-deep-agents-ad5090403038) was originally published in [Towards AI](https://pub.towardsai.net) on Medium, where people are continuing the conversation by highlighting and responding to this story.
