Source code for airflow.providers.common.ai.example_dags.example_langchain_toolset_bridge
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""
Expose an Airflow toolset to a LangChain agent (the reverse bridge).
common.ai's curated toolsets (``SQLToolset``, ``HookToolset``, ``MCPToolset``)
are pydantic-ai toolsets, so ``AgentOperator`` uses them natively. This example
shows the *reverse* direction: convert a ``SQLToolset`` into LangChain
``StructuredTool`` objects with
:func:`~airflow.providers.common.ai.toolsets.langchain_bridge.airflow_toolset_to_langchain_tools`
and hand them to a LangChain ReAct agent built with ``create_agent``. The agent
gets Airflow's managed connections and read-only SQL validation for free.
**Forward direction** (LangChain tools -> ``AgentOperator``): no Airflow code
is needed. pydantic-ai ships ``pydantic_ai.ext.langchain.LangChainToolset``
upstream, so ``LangChainToolset([my_langchain_tool])`` drops straight into
``AgentOperator(toolsets=[...])``. See https://ai.pydantic.dev for details.
Before running:
1. Install LangChain: ``pip install "apache-airflow-providers-common-ai[langchain]" langchain-openai``
2. Create a ``langchain`` connection named ``langchain_default`` (set
``password`` to your API key) for the model.
3. Create a database connection (``DB_CONN_ID``, default ``sql_default``) whose
hook is a ``DbApiHook`` (e.g. SQLite, Postgres, MySQL).
"""
from __future__ import annotations
import os
from airflow.providers.common.compat.sdk import dag, task
[docs]
LLM_CONN_ID = os.environ.get("LLM_CONN_ID", "langchain_default")
[docs]
LLM_MODEL = os.environ.get("LLM_MODEL", "openai:gpt-4o")
[docs]
DB_CONN_ID = os.environ.get("DB_CONN_ID", "sql_default")
[docs]
DEFAULT_QUESTION = "Which tables exist, and how many rows does each contain?"
# [START example_langchain_toolset_bridge]
@dag(tags=["example"])
# [END example_langchain_toolset_bridge]
example_langchain_toolset_bridge()