|
| 1 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +# or more contributor license agreements. See the NOTICE file |
| 3 | +# distributed with this work for additional information |
| 4 | +# regarding copyright ownership. The ASF licenses this file |
| 5 | +# to you under the Apache License, Version 2.0 (the |
| 6 | +# "License"); you may not use this file except in compliance |
| 7 | +# with the License. You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, |
| 12 | +# software distributed under the License is distributed on an |
| 13 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +# KIND, either express or implied. See the License for the |
| 15 | +# specific language governing permissions and limitations |
| 16 | +# under the License. |
| 17 | +""" |
| 18 | +TaskFlow decorator for LLM SQL generation. |
| 19 | +
|
| 20 | +The user writes a function that **returns the prompt**. The decorator handles |
| 21 | +the LLM call, schema introspection, and safety validation. The decorated task's |
| 22 | +XCom output is the generated SQL string. |
| 23 | +""" |
| 24 | + |
| 25 | +from __future__ import annotations |
| 26 | + |
| 27 | +from collections.abc import Callable, Collection, Mapping, Sequence |
| 28 | +from typing import TYPE_CHECKING, Any, ClassVar |
| 29 | + |
| 30 | +from airflow.providers.common.ai.operators.llm_sql import LLMSQLQueryOperator |
| 31 | +from airflow.providers.common.compat.sdk import ( |
| 32 | + DecoratedOperator, |
| 33 | + TaskDecorator, |
| 34 | + context_merge, |
| 35 | + task_decorator_factory, |
| 36 | +) |
| 37 | +from airflow.sdk.definitions._internal.types import SET_DURING_EXECUTION |
| 38 | +from airflow.utils.operator_helpers import determine_kwargs |
| 39 | + |
| 40 | +if TYPE_CHECKING: |
| 41 | + from airflow.sdk import Context |
| 42 | + |
| 43 | + |
| 44 | +class _LLMSQLDecoratedOperator(DecoratedOperator, LLMSQLQueryOperator): |
| 45 | + """ |
| 46 | + Wraps a callable that returns a prompt for LLM SQL generation. |
| 47 | +
|
| 48 | + The user function is called at execution time to produce the prompt string. |
| 49 | + All other parameters (``llm_conn_id``, ``db_conn_id``, ``table_names``, etc.) |
| 50 | + are passed through to :class:`~airflow.providers.common.ai.operators.llm_sql.LLMSQLQueryOperator`. |
| 51 | +
|
| 52 | + :param python_callable: A reference to a callable that returns the prompt string. |
| 53 | + :param op_args: Positional arguments for the callable. |
| 54 | + :param op_kwargs: Keyword arguments for the callable. |
| 55 | + """ |
| 56 | + |
| 57 | + template_fields: Sequence[str] = ( |
| 58 | + *DecoratedOperator.template_fields, |
| 59 | + *LLMSQLQueryOperator.template_fields, |
| 60 | + ) |
| 61 | + template_fields_renderers: ClassVar[dict[str, str]] = { |
| 62 | + **DecoratedOperator.template_fields_renderers, |
| 63 | + } |
| 64 | + |
| 65 | + custom_operator_name: str = "@task.llm_sql" |
| 66 | + |
| 67 | + def __init__( |
| 68 | + self, |
| 69 | + *, |
| 70 | + python_callable: Callable, |
| 71 | + op_args: Collection[Any] | None = None, |
| 72 | + op_kwargs: Mapping[str, Any] | None = None, |
| 73 | + **kwargs, |
| 74 | + ) -> None: |
| 75 | + super().__init__( |
| 76 | + python_callable=python_callable, |
| 77 | + op_args=op_args, |
| 78 | + op_kwargs=op_kwargs, |
| 79 | + prompt=SET_DURING_EXECUTION, |
| 80 | + **kwargs, |
| 81 | + ) |
| 82 | + |
| 83 | + def execute(self, context: Context) -> Any: |
| 84 | + context_merge(context, self.op_kwargs) |
| 85 | + kwargs = determine_kwargs(self.python_callable, self.op_args, context) |
| 86 | + |
| 87 | + self.prompt = self.python_callable(*self.op_args, **kwargs) |
| 88 | + |
| 89 | + if not isinstance(self.prompt, str) or not self.prompt.strip(): |
| 90 | + raise TypeError("The returned value from the @task.llm_sql callable must be a non-empty string.") |
| 91 | + |
| 92 | + self.render_template_fields(context) |
| 93 | + # Call LLMSQLQueryOperator.execute directly, not super().execute(), |
| 94 | + # because we need to skip DecoratedOperator.execute — the callable |
| 95 | + # invocation is already handled above. |
| 96 | + return LLMSQLQueryOperator.execute(self, context) |
| 97 | + |
| 98 | + |
| 99 | +def llm_sql_task( |
| 100 | + python_callable: Callable | None = None, |
| 101 | + **kwargs, |
| 102 | +) -> TaskDecorator: |
| 103 | + """ |
| 104 | + Wrap a function that returns a natural language prompt into an LLM SQL task. |
| 105 | +
|
| 106 | + The function body constructs the prompt (can use Airflow context, XCom, etc.). |
| 107 | + The decorator handles: LLM connection, schema introspection, SQL generation, |
| 108 | + and safety validation. |
| 109 | +
|
| 110 | + Usage:: |
| 111 | +
|
| 112 | + @task.llm_sql( |
| 113 | + llm_conn_id="openai_default", |
| 114 | + db_conn_id="postgres_default", |
| 115 | + table_names=["customers", "orders"], |
| 116 | + ) |
| 117 | + def build_query(ds=None): |
| 118 | + return f"Find top 10 customers by revenue in {ds}" |
| 119 | +
|
| 120 | + :param python_callable: Function to decorate. |
| 121 | + """ |
| 122 | + return task_decorator_factory( |
| 123 | + python_callable=python_callable, |
| 124 | + decorated_operator_class=_LLMSQLDecoratedOperator, |
| 125 | + **kwargs, |
| 126 | + ) |
0 commit comments