Apache Airflow® as an Orchestration Layer for AI Workflows
Data orchestration can be simplified to “defining the order of tasks” until you come across with the real data pipeline challenges or bottlenecks. Apache Airflow® has been helping the users deal with these challenges for a long time now. Personally, I can say that once I started using Airflow, I never felt the need to explore other orchestration frameworks for data pipelines; and that could be because data per se shows up mostly in patterns. Addressing those patterns and tracking them makes larger part of the challenges quite predictable.
However, new execution paradigms keep showing up and that’s when I start to question my belief system. The last time that happened was when I thought about AI orchestration. Not just orchestrating agents or LLM based tasks, but also when I thought of keeping data and AI within the same pipeline , and what I realized is, Airflow can run it, if you know your system layer well. As long as you are using it in the right place, it is one of the better tools available.
This article talks about where Airflow fits, and what does the architecture look like when you put it next to the MCP based agent tooling.
Agent Orchestrator
Agent in simple words, is something that gets the context, calls a model and lets the model decide which tool to call, whether to call the tool or not, execute that tool, feed the result back and repeat until a certain condition is met, and then returns the results.
Now when thinking in terms of orchestration, you might be wondering “how does agent orchestration work here? The sequence of tool calls is not known at the compile time!”. That’s right, the model decides it at the runtime and the number of iterations is often unbound until a model-defined stop condition fires.Airflow DAGs have a fixed shape at parse time. Tasks communicate using xcoms ( which isn’t ideal for an unbounded loop) , task scheduling runs on a heartbeat cycle in seconds and not milliseconds.
What changes the scene is the official apache-airflow-providers-common-ai package that helps in handling this without altering the DAG’s meaning. AgentOperator, with the help of dynamic task mapping, makes it possible for the tasks to break into sub-tasks and then synthesize the results to return a complete output. Conversation history and intermediate tool results live in the same in-process run. Toolsets comes as part of the provider package. That technically answers the questions to agentic orchestration demands like
- Dynamic graph shape issue solved with dynamic task mapping
- Low second latency requirements solved with step-level caching for LLM and AI agent operations.
- Persistent states across the loop solved with conversation history, intermediate tool results handling.
- Non traditional scheduling with asset aware scheduling.
Now the question shifts from “Can airflow schedule AI workloads?” to “How can I use Airflow for AI workloads?”
Let’s look into this with an example on how LLMs fit into the DAGs.
Scenario:
A data team runs a nightly job that pulls order data from a prod DB into a warehouse, summarizes it for stakeholders and needs to catch anything that looks wrong before a human ever has to look at it. With human in the loop, this can prevent a lot of silent data corruption in a board deck.
So the following questions need to be answered here:
- Was there any schema change I missed to notice? Any columns dropped or added in the upstream tasks?
- How safe is it to proceed?
- Query the data every night.
- Is there a way to check “what happened and why does it matter?” under 10 seconds?
- Anything we missed to notice? If so, find out why.
Solution
To answer these questions, we can make use of the 6 decorators provided by common-ai-provider specifically for LLM based tasks in the following dag:
Now let’s break down the tasks to see how they fit in the above use case:
Schema compare: We need to see if the upstream task has got data in which there is a change in schema detected. Outsourcing this problem to llm using @task.llm_schema_compare decorator the task looks like this:
@task.llm_schema_compare(
llm_conn_id="pydanticai_default",
db_conn_ids=["postgres_source", "snowflake_warehouse"],
table_names=["orders", "customers"],
context_strategy="full",
)
def check_schema_drift():
return "Flag any mismatches that would break tonight's load. Report only, no migrations."
@task.llm_schema_compare(
llm_conn_id="pydanticai_default",
db_conn_ids=["postgres_source", "snowflake_warehouse"],
table_names=["orders", "customers"],
context_strategy="full",
)
def check_schema_drift():
return "Flag any mismatches that would break tonight's load. Report only, no migrations."
In the above example, the llm_conn_id is the connection created in airflow where you can specify your model and AI provider, so that even if there is any change in that information in the near future, your dag doesn’t need an update. Considering the source of data as postgres and snowflake tables, we have also mentioned the respective DB connection ids. Table names where schema change is expected are passed as a list. Context_strategy can be set to full or basic. full means, complete schema definition gets sent to the LLM for analysis and that’s the default value as well. This task returns the instruction for what the model should do with that schema comparison data.
Route on schema change: Now we let the model decide if the team should be notified about the schema change or should we go ahead with the query execution in further steps.
@task.llm_branch(
llm_conn_id="pydanticai_default",
system_prompt=(
"Given a schema comparison result, decide whether nightly ETL is safe to run. "
"Route to 'generate_extract_query' if there are no critical mismatches, "
"otherwise route to 'notify_team'."
),
)
def route_on_schema(comparison: dict):
return f"Schema comparison result: {comparison}"
@task.llm_branch(
llm_conn_id="pydanticai_default",
system_prompt=(
"Given a schema comparison result, decide whether nightly ETL is safe to run. "
"Route to 'generate_extract_query' if there are no critical mismatches, "
"otherwise route to 'notify_team'."
),
)
def route_on_schema(comparison: dict):
return f"Schema comparison result: {comparison}"
In the above code, the system prompt asks the model to route to generate_extract_query if everything is fine or route to the notify_team method.
@task
def notify_team():
import os
import requests
requests.post(os.environ["SLACK_WEBHOOK_URL"],json={"text": "Schema drift detected — halting ETL and notifying the data team."})
@task
def notify_team():
import os
import requests
requests.post(os.environ["SLACK_WEBHOOK_URL"],json={"text": "Schema drift detected — halting ETL and notifying the data team."})
You can also configure SlackAPIPostOperator to get slack messages.
Now what’s interesting here is , in the generate_extract_query, we are simply defining the query in english while the decorator @task.llm_sql enables the conversion of prompt in english to sql, validates it.
@task.llm_sql(
llm_conn_id="pydanticai_default",
db_conn_id="postgres_source",
table_names=["orders", "customers"],
dialect="postgres",
)
def generate_extract_query(ds=None):
return f"Pull all orders and customer info for {ds}, joined on customer_id."
extract_query = generate_extract_query()
@task.llm_sql(
llm_conn_id="pydanticai_default",
db_conn_id="postgres_source",
table_names=["orders", "customers"],
dialect="postgres",
)
def generate_extract_query(ds=None):
return f"Pull all orders and customer info for {ds}, joined on customer_id."
extract_query = generate_extract_query()
The generated query can be run using SQLExecuteQueryOperator or decorator @task.sql decorator as follows.
list[dict]:
return sql
rows = run_extract_query(extract_query)” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
@task.sql
def run_extract_query(sql: str) -> list[dict]:
return sql
rows = run_extract_query(extract_query)
@task.sql
def run_extract_query(sql: str) -> list[dict]:
return sql
rows = run_extract_query(extract_query)
Now the next step would be to turn the raw rows to detailed summary. The prompt is passed to the llm configured in the airflow connections and the summary is generated for the input rows. My personal favorite here is the usage_limits. The task fails if the request_limit exceeds 5 model requests, 4_000 input tokens, or 1_000 output tokens implementing guardrails as most needed.
@task.llm(
llm_conn_id="pydanticai_default",
system_prompt="Summarize the day's order data for a stakeholder digest.",
output_type=DailySummary,
usage_limits=UsageLimits(
request_limit=5,
input_tokens_limit=4_000,
output_tokens_limit=1_000,
),
)
def summarize_orders(rows: list[dict]):
return f"Summarize this order data: {rows}"
summary = summarize_orders(rows)
@task.llm(
llm_conn_id="pydanticai_default",
system_prompt="Summarize the day's order data for a stakeholder digest.",
output_type=DailySummary,
usage_limits=UsageLimits(
request_limit=5,
input_tokens_limit=4_000,
output_tokens_limit=1_000,
),
)
def summarize_orders(rows: list[dict]):
return f"Summarize this order data: {rows}"
summary = summarize_orders(rows)
Now that the summary is generated, we export reports to S3 using the task flow apis.
@task
def export_report(summary: dict):
path = "s3://reports/orders/daily_summary.json"
print(f"Writing {summary} to {path}")
return path
report_path = export_report(summary)
@task
def export_report(summary: dict):
path = "s3://reports/orders/daily_summary.json"
print(f"Writing {summary} to {path}")
return path
report_path = export_report(summary)
In order to analyse and review the generated summary, we would be using the @task.llm_file_analysis decorator as follows:
@task.llm_file_analysis(
llm_conn_id="pydanticai_default",
file_path=report_path,
file_conn_id="aws_default",
output_type=FileFindings,
)
def analyze_report():
return "Review this report for any revenue anomalies or suspicious patterns."
findings = analyze_report()
@task.llm_file_analysis(
llm_conn_id="pydanticai_default",
file_path=report_path,
file_conn_id="aws_default",
output_type=FileFindings,
)
def analyze_report():
return "Review this report for any revenue anomalies or suspicious patterns."
findings = analyze_report()
This decorator resolves the file path and analyses the input file, supporting multi-modal inputs too and returns a Pydantic object if defined to ensure structured output.
If there is further investigation required, the output from this step can be passed on to an agent with the following two tasks
@task.branch
def needs_investigation(findings: dict):
return "investigate_anomaly" if findings.get("requires_investigation") else "done"
decision = needs_investigation(findings)
@task.agent(
llm_conn_id="pydanticai_default",
system_prompt="You are a data analyst investigating a revenue anomaly. Use SQL to dig in.",
toolsets=[
SQLToolset(
db_conn_id="postgres_source",
allowed_tables=["orders", "customers"],
)
],
)
def investigate_anomaly(findings: dict):
return f"These anomalies were flagged: {findings}. Investigate the root cause."
@task.branch
def needs_investigation(findings: dict):
return "investigate_anomaly" if findings.get("requires_investigation") else "done"
decision = needs_investigation(findings)
@task.agent(
llm_conn_id="pydanticai_default",
system_prompt="You are a data analyst investigating a revenue anomaly. Use SQL to dig in.",
toolsets=[
SQLToolset(
db_conn_id="postgres_source",
allowed_tables=["orders", "customers"],
)
],
)
def investigate_anomaly(findings: dict):
return f"These anomalies were flagged: {findings}. Investigate the root cause."
This step can vary based on your use case, you can either pass this to a human for review and complete the DAG based on the approval for advanced reliability as well.
If you would want to involve a human reviewer using HITL(human in the loop operators). You can refer to some examples here.
The whole dag together looks something like this.
Mechanics that matter!
Dynamic task mapping for agent task fan out. Agents usually work like a black box. Despite their multi-step mode of working , with tasks delegated and tool calls made, it either gets your task done or fails. Airflow DAGs already have a way to dynamically map tasks in fan-out fashion. Utilizing this while implementing Agentic execution in AI not only helps you with transparency but also helps you cut costs and latency.
If a multi step agent has 5 tasks and one of them fails, instead of the entire agent re-running to synthesize an output, dynamic task mapping will help a given task expand() into multiple sub tasks which can later synthesize to form a single output. That way, if the subtask fails, the retry is applicable only to that task and not the whole loop and you can also monitor the reason for failure quite easily.
Deferrable Operators for long running tool calls is a blessing when you want to integrate human in the loop or just wait for the response at the retrieval step in the RAG. There is no need for the worker to hold the slot. The real advantage here can be evidently noticed especially at scale.
Durable field in the AgentOperator helps you to cache the model responses and tool calls at each step when set to true. All you need to do is, set the field to true and env variable AIRFLOW__COMMON_AI__DURABLE_CACHE_PATH to an object storage backend path ( like S3). On successful task execution of the task, the cache gets auto cleaned up. This is useful especially when your dag is almost about to be declared successful but that one last step fails and the whole thing is set to retry making expensive llm calls. Setting durable=true , helps airflow retrieve the data from the cache and makes absolutely necessary calls at the step where the failure occurred. Of course, all this makes sense only if retries are set on the task. One thing to beware of is, durable doesn’t prevent the side effects on retry. For example, if there was an email sent by a task and then if the task failed, on retry, the mail is going to get triggered again.
XComs as a link between reasoning state and orchestration is possible when you send the data across the tasks as a structured handoff contract using Pydantic model so that the downstream tasks digest the inputs effortlessly.
Human in the loop cannot be stressed enough and this can save AI slops and blunders , if configured well before the data leaves your pipelines. Best places to add these are at on_failure_callback() methods and decision making step before handing out the data to the wider audience. SLA misses is something airflow provides which native agentic frameworks don’t provide. There are two ways to do it
- Approval Gate where you either approve or reject or modify the output.
- Iterative Review where you mention the max_hitl_iterations and the agent asks you to approve or reject and finish it off or if you are willing to ask for slight modifications, you get 5 chances to do so.
HookToolSet with explicit allow-list of methods is my personal favourite. Airflow has over 350+ hooks. Imagine if an Agent needs a toolset to make API calls to various systems.Handing these hooks as tools would literally solve the problem of authentication all over again, while taking off the fear of “what if the agent deletes something?”. You know you are good because you didn’t specify ‘delete’ in the allowed_methods here 🙂
Portability through Pydantic AI connection. If you observe the dag we wrote earlier, you might have noticed that there were no specific mentions of models or LLM providers in the dag. How will the dag connect with the model? The Pydantic Connection is defined with the provider:model string, which can be altered without touching the dag , if need arises.
First class operators for RAG with DocumentLoader for ingestion step, LlamaIndex Embedding Operator for generating embeddings, LlamaIndex Retrieval Operator for retrieval ( check this dag for example reference).
Retry Mechanism might not always be perfect solution for every dag. Be that for data pipelines or AI pipelines. There is no point in retrying 3 or more times when you hit a permission error. The mechanism to deal with network error/ connection error is by implementing sufficient wait times between retries. When you hit a rate limit , retries with exponential backoff is the way to go and some cases, you just don’t retry and fail the task. Seems like that needs multiple configurations, ain’t it? Not really! If the LLM model can decide the category of the error and then help with the right retry mechanism, that would be perfect.
Airflow helps with identifying the right approach to the Retry mechanism by introducing LLMRetry policies. A small example from the airflow documentation is as follows. The policy assigned in the task flow api, takes the error type to the LLM model that decides how to proceed with handling it.
from airflow.providers.common.ai.policies.retry import LLMRetryPolicy
from airflow.sdk.definitions.retry_policy import RetryAction, RetryRule
from datetime import timedelta
llm_policy = LLMRetryPolicy(
llm_conn_id="pydanticai_default",
timeout=30.0, # max seconds to wait for LLM response
fallback_rules=[ # used when LLM call fails
RetryRule(exception=ConnectionError, action=RetryAction.RETRY, retry_delay=timedelta(seconds=10)),
RetryRule(exception=PermissionError, action=RetryAction.FAIL),
],
)
@task(retries=5, retry_policy=llm_policy)
def call_external_api(): ...
from airflow.providers.common.ai.policies.retry import LLMRetryPolicy
from airflow.sdk.definitions.retry_policy import RetryAction, RetryRule
from datetime import timedelta
llm_policy = LLMRetryPolicy(
llm_conn_id="pydanticai_default",
timeout=30.0, # max seconds to wait for LLM response
fallback_rules=[ # used when LLM call fails
RetryRule(exception=ConnectionError, action=RetryAction.RETRY, retry_delay=timedelta(seconds=10)),
RetryRule(exception=PermissionError, action=RetryAction.FAIL),
],
)
@task(retries=5, retry_policy=llm_policy)
def call_external_api(): ...
Observability with otel tracing where the otel spans can be sent to Jaeger, HoneyComb, Datadog or Langfuse. Langchain bridge lets you use the langchain tools in airflow. MCP connection type lets you access MCP servers with Streamable HTTP, SSE, and stdio transfer types.
None of this makes Airflow an agentic framework, and it isn’t trying to be one. Pydantic AI runs the reasoning loop; Airflow runs the schedule, the retries, the audit trail, and the human checkpoint before anything reaches a stakeholder. That division of labor is the whole point. The moment your use case needs sub-second, conversational turnaround, this stops being the right tool. The heartbeat cycle and the in-process agent loop don’t bend that far, and no decorator changes that math. But for the much larger category of agentic work that’s scheduled, batch, or async-tolerant — nightly checks, report synthesis, schema drift, anomaly investigation, you already own the orchestrator that does this well. The question was never whether Airflow can run AI workloads. It’s whether you’re using it where the latency budget actually fits, and that’s an architecture decision, not a feature request.
If you found this article useful to understand orchestrating AI using airflow, go ahead and tap the claps 👏👏👏 For more such articles, do follow.
Originally published at https://insidedataengineering.substack.com.

