zozo123 commented on code in PR #76157: URL: https://github.com/apache/airflow/pull/76157#discussion_r4665827662
########## providers/databricks/src/airflow/providers/databricks/operators/genie.py: ########## @@ -0,0 +1,365 @@ +# 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. +"""Operators for asking Databricks Genie spaces questions as standalone tasks.""" + +from __future__ import annotations + +import hashlib +import time +from collections.abc import Sequence +from datetime import timedelta +from functools import cached_property +from typing import TYPE_CHECKING, Any +from urllib.parse import quote + +from airflow.providers.common.compat.sdk import AirflowFailException, BaseOperator, ResumableJobMixin, conf +from airflow.providers.databricks.hooks.genie import ( + _PENDING_STATUSES, + DatabricksGenieError, + DatabricksGenieHook, + _truncate_result, +) +from airflow.providers.databricks.triggers.genie import DatabricksGenieMessageTrigger + +if TYPE_CHECKING: + from airflow.providers.common.compat.sdk import Context + +GenieMessageRef = dict[str, str] + +_NOT_FOUND = "NOT_FOUND" +_STALE = "STALE" +_TERMINAL_STATUSES = frozenset({"COMPLETED", "FAILED", "CANCELLED", "QUERY_RESULT_EXPIRED"}) + + +class DatabricksGenieOperator(ResumableJobMixin, BaseOperator): + """ + Ask a Databricks Genie space one question and return a bounded, structured answer. + + The operator submits the question once, persists the Genie conversation and message IDs to task + state before waiting, then polls (or defers) until the message finishes. A retry after a worker + crash or timeout reconnects to the stored message instead of asking again. + + Genie has no idempotency key, so a submission whose outcome is unknown (a timeout, a connection + error or a 5xx response) cannot be told apart from one that was never received. The operator fails + without retrying in that case and the next try refuses to submit again; set ``conversation_id`` and + ``message_id`` to attach to the message you found, or ``resubmit_unconfirmed=True`` to ask again. + + .. seealso:: + For more information on how to use this operator, take a look at the guide: + :ref:`howto/operator:DatabricksGenieOperator` + + :param space_id: Genie space ID. (templated) + :param question: Question to ask. Required unless ``message_id`` is set. (templated) + :param databricks_conn_id: Databricks connection. Defaults to ``databricks_default``. (templated) + :param conversation_id: Existing conversation to ask the question in. The operator never deletes it. + Defaults to ``None``, which starts a new conversation. An empty string means ``None``. (templated) + :param message_id: Existing message to wait for instead of asking a question. Requires + ``conversation_id``. An empty string means ``None``. (templated) + :param polling_period_seconds: Seconds between status checks. Defaults to ``5``. + :param timeout: Maximum seconds to wait for the answer in one try. Timing out does not cancel the + message; the next try reconnects to it. Defaults to ``1800``. + :param resubmit_unconfirmed: Ask the question again even though an earlier submission's outcome is + unknown and may have created a message. Defaults to ``False``. + :param databricks_retry_limit: Attempts for each Genie read. Submissions are never retried. + Defaults to ``3``. + :param databricks_retry_delay: Minimum seconds between read attempts. Defaults to ``1``. + :param deferrable: Release the worker while waiting. Defaults to ``[operators] default_deferrable``, + with a fallback of ``False``. + :param durable: When ``True`` (the default), the Genie message IDs are persisted to task state + before waiting so a retry reconnects instead of asking again. Requires Airflow 3.3+; on earlier + versions every try asks the question again. + """ + + template_fields: Sequence[str] = ( + "space_id", + "question", + "databricks_conn_id", + "conversation_id", + "message_id", + ) + ui_color = "#1CB1C2" + external_id_key = "databricks_genie_message" + + def __init__( + self, + *, + space_id: str, + question: str | None = None, + databricks_conn_id: str = "databricks_default", + conversation_id: str | None = None, + message_id: str | None = None, + polling_period_seconds: float = 5, + timeout: float = 1800, + resubmit_unconfirmed: bool = False, + databricks_retry_limit: int = 3, + databricks_retry_delay: float = 1, + deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False), + durable: bool | None = None, + **kwargs: Any, + ) -> None: + # Named here (not left to **kwargs) so default_args reaches it on every supported Airflow version. + if durable is not None: + kwargs["durable"] = durable + super().__init__(**kwargs) + if polling_period_seconds <= 0: + raise ValueError("polling_period_seconds must be positive") + if timeout <= 0: + raise ValueError("timeout must be positive") + self.space_id = space_id + self.question = question + self.databricks_conn_id = databricks_conn_id + self.conversation_id = conversation_id + self.message_id = message_id + self.polling_period_seconds = polling_period_seconds + self.timeout = timeout + self.resubmit_unconfirmed = resubmit_unconfirmed + self.databricks_retry_limit = databricks_retry_limit + self.databricks_retry_delay = databricks_retry_delay + self.deferrable = deferrable + self._result: dict[str, Any] | None = None + + @cached_property + def hook(self) -> DatabricksGenieHook: + return DatabricksGenieHook( + self.databricks_conn_id, + retry_limit=self.databricks_retry_limit, + retry_delay=self.databricks_retry_delay, + caller=type(self).__name__, + poll_interval=self.polling_period_seconds, + ) + + @property + def _submission_key(self) -> str: + return f"{self.external_id_key}_submission" + + def _fingerprint(self) -> str: + """Identify the question so a retry never reconnects to an answer for a different one.""" + material = "\x1f".join((self.space_id, self.conversation_id or "", self.question or "")) + return hashlib.sha256(material.encode("utf-8")).hexdigest() + + def _task_state_store(self, context: Context) -> Any: + return context.get("task_state_store") if self.durable else None + + def _validate(self) -> None: + self.conversation_id = self.conversation_id or None + self.message_id = self.message_id or None + self.hook._validate_space_id(self.space_id) + if self.message_id is not None: + if self.conversation_id is None: + raise ValueError("message_id requires conversation_id") + elif not isinstance(self.question, str) or not self.question.strip(): + raise ValueError("question must be a non-empty string unless message_id is set") + + def execute(self, context: Context) -> dict[str, Any]: + self._validate() + if self.message_id is None: + return self.execute_resumable(context) + ref = { + "space_id": self.space_id, + "conversation_id": self.conversation_id, + "message_id": self.message_id, + "fingerprint": self._fingerprint(), + } + self.log.info( + "Attaching to Genie message %s in conversation %s", self.message_id, self.conversation_id + ) + if (store := self._task_state_store(context)) is not None: + store.set(self.external_id_key, ref) + store.delete(self._submission_key) + return self.poll_until_complete(ref, context) + + def submit_job(self, context: Context) -> Any: + store = self._task_state_store(context) + if store is not None: + marker = store.get(self._submission_key) + if ( + marker is not None + and not self.resubmit_unconfirmed + and (not isinstance(marker, dict) or marker.get("fingerprint") == self._fingerprint()) + ): + raise AirflowFailException( + "An earlier try submitted this Genie question but Databricks never confirmed the " + "outcome, so a message may already exist. Inspect the Genie space, then set " + "conversation_id and message_id to attach to it, or set resubmit_unconfirmed=True " + "to ask again." + ) + store.set(self._submission_key, {"fingerprint": self._fingerprint()}) + + space = quote(self.space_id, safe="") + if self.conversation_id is None: + endpoint = f"spaces/{space}/start-conversation" + else: + endpoint = f"spaces/{space}/conversations/{quote(self.conversation_id, safe='')}/messages" + try: + created = self.hook._request( Review Comment: Good catch, thank you. Fixed in 6d06c6be02: submit_job now calls a new hook `_prepare_request` (URL, HTTPS check, auth, request kwargs) before writing the marker, and `_request` sends with that prepared result. Added `test_failure_before_send_leaves_no_marker`, where the token step fails on the first try and the retry submits normally. ########## providers/databricks/src/airflow/providers/databricks/operators/genie.py: ########## @@ -0,0 +1,365 @@ +# 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. +"""Operators for asking Databricks Genie spaces questions as standalone tasks.""" + +from __future__ import annotations + +import hashlib +import time +from collections.abc import Sequence +from datetime import timedelta +from functools import cached_property +from typing import TYPE_CHECKING, Any +from urllib.parse import quote + +from airflow.providers.common.compat.sdk import AirflowFailException, BaseOperator, ResumableJobMixin, conf +from airflow.providers.databricks.hooks.genie import ( + _PENDING_STATUSES, + DatabricksGenieError, + DatabricksGenieHook, + _truncate_result, +) +from airflow.providers.databricks.triggers.genie import DatabricksGenieMessageTrigger + +if TYPE_CHECKING: + from airflow.providers.common.compat.sdk import Context + +GenieMessageRef = dict[str, str] + +_NOT_FOUND = "NOT_FOUND" +_STALE = "STALE" +_TERMINAL_STATUSES = frozenset({"COMPLETED", "FAILED", "CANCELLED", "QUERY_RESULT_EXPIRED"}) Review Comment: Done in 6d06c6be02. `GENIE_TERMINAL_STATUSES` now lives in the hook next to `_PENDING_STATUSES`, and both the operator and the trigger import it. ########## providers/databricks/src/airflow/providers/databricks/operators/genie.py: ########## @@ -0,0 +1,365 @@ +# 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. +"""Operators for asking Databricks Genie spaces questions as standalone tasks.""" + +from __future__ import annotations + +import hashlib +import time +from collections.abc import Sequence +from datetime import timedelta +from functools import cached_property +from typing import TYPE_CHECKING, Any +from urllib.parse import quote + +from airflow.providers.common.compat.sdk import AirflowFailException, BaseOperator, ResumableJobMixin, conf +from airflow.providers.databricks.hooks.genie import ( + _PENDING_STATUSES, + DatabricksGenieError, + DatabricksGenieHook, + _truncate_result, +) +from airflow.providers.databricks.triggers.genie import DatabricksGenieMessageTrigger + +if TYPE_CHECKING: + from airflow.providers.common.compat.sdk import Context + +GenieMessageRef = dict[str, str] + +_NOT_FOUND = "NOT_FOUND" +_STALE = "STALE" +_TERMINAL_STATUSES = frozenset({"COMPLETED", "FAILED", "CANCELLED", "QUERY_RESULT_EXPIRED"}) + + +class DatabricksGenieOperator(ResumableJobMixin, BaseOperator): + """ + Ask a Databricks Genie space one question and return a bounded, structured answer. + + The operator submits the question once, persists the Genie conversation and message IDs to task + state before waiting, then polls (or defers) until the message finishes. A retry after a worker + crash or timeout reconnects to the stored message instead of asking again. + + Genie has no idempotency key, so a submission whose outcome is unknown (a timeout, a connection + error or a 5xx response) cannot be told apart from one that was never received. The operator fails + without retrying in that case and the next try refuses to submit again; set ``conversation_id`` and + ``message_id`` to attach to the message you found, or ``resubmit_unconfirmed=True`` to ask again. + + .. seealso:: + For more information on how to use this operator, take a look at the guide: + :ref:`howto/operator:DatabricksGenieOperator` + + :param space_id: Genie space ID. (templated) + :param question: Question to ask. Required unless ``message_id`` is set. (templated) + :param databricks_conn_id: Databricks connection. Defaults to ``databricks_default``. (templated) + :param conversation_id: Existing conversation to ask the question in. The operator never deletes it. + Defaults to ``None``, which starts a new conversation. An empty string means ``None``. (templated) + :param message_id: Existing message to wait for instead of asking a question. Requires + ``conversation_id``. An empty string means ``None``. (templated) + :param polling_period_seconds: Seconds between status checks. Defaults to ``5``. + :param timeout: Maximum seconds to wait for the answer in one try. Timing out does not cancel the + message; the next try reconnects to it. Defaults to ``1800``. + :param resubmit_unconfirmed: Ask the question again even though an earlier submission's outcome is + unknown and may have created a message. Defaults to ``False``. + :param databricks_retry_limit: Attempts for each Genie read. Submissions are never retried. + Defaults to ``3``. + :param databricks_retry_delay: Minimum seconds between read attempts. Defaults to ``1``. + :param deferrable: Release the worker while waiting. Defaults to ``[operators] default_deferrable``, + with a fallback of ``False``. + :param durable: When ``True`` (the default), the Genie message IDs are persisted to task state + before waiting so a retry reconnects instead of asking again. Requires Airflow 3.3+; on earlier + versions every try asks the question again. + """ + + template_fields: Sequence[str] = ( + "space_id", + "question", + "databricks_conn_id", + "conversation_id", + "message_id", + ) + ui_color = "#1CB1C2" + external_id_key = "databricks_genie_message" + + def __init__( + self, + *, + space_id: str, + question: str | None = None, + databricks_conn_id: str = "databricks_default", + conversation_id: str | None = None, + message_id: str | None = None, + polling_period_seconds: float = 5, + timeout: float = 1800, + resubmit_unconfirmed: bool = False, + databricks_retry_limit: int = 3, + databricks_retry_delay: float = 1, + deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False), + durable: bool | None = None, + **kwargs: Any, + ) -> None: + # Named here (not left to **kwargs) so default_args reaches it on every supported Airflow version. + if durable is not None: + kwargs["durable"] = durable + super().__init__(**kwargs) + if polling_period_seconds <= 0: + raise ValueError("polling_period_seconds must be positive") + if timeout <= 0: + raise ValueError("timeout must be positive") + self.space_id = space_id + self.question = question + self.databricks_conn_id = databricks_conn_id + self.conversation_id = conversation_id + self.message_id = message_id + self.polling_period_seconds = polling_period_seconds + self.timeout = timeout + self.resubmit_unconfirmed = resubmit_unconfirmed + self.databricks_retry_limit = databricks_retry_limit + self.databricks_retry_delay = databricks_retry_delay + self.deferrable = deferrable + self._result: dict[str, Any] | None = None + + @cached_property + def hook(self) -> DatabricksGenieHook: + return DatabricksGenieHook( + self.databricks_conn_id, + retry_limit=self.databricks_retry_limit, + retry_delay=self.databricks_retry_delay, + caller=type(self).__name__, + poll_interval=self.polling_period_seconds, + ) + + @property + def _submission_key(self) -> str: + return f"{self.external_id_key}_submission" + + def _fingerprint(self) -> str: Review Comment: Renamed in 6d06c6be02: `_compute_fingerprint`, `_get_task_state_store`, `_build_message_path` and `_build_event`. The test helpers are now `build_message`, `build_stored_ref`, `stub_answered` and `collect_events`. ########## providers/databricks/docs/operators/genie_operator.rst: ########## @@ -0,0 +1,84 @@ + .. 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. + + + +.. _howto/operator:DatabricksGenieOperator: + +Ask a Databricks Genie space +============================ + +Use :class:`~airflow.providers.databricks.operators.genie.DatabricksGenieOperator` to ask a Genie space +one question as a standalone task. The operator returns the same bounded result as +:ref:`DatabricksGenieHook <howto/databricks-genie>` through XCom: the space, conversation and message +IDs, the message status, the text answer, generated queries and capped query results. + +.. exampleinclude:: /../../databricks/tests/system/databricks/example_databricks_genie.py + :language: python + :start-after: [START howto_operator_databricks_genie] + :end-before: [END howto_operator_databricks_genie] + +By default the operator starts a new conversation. Set ``conversation_id`` to ask a follow-up in an +existing conversation. The operator never deletes or cancels conversations, so a conversation you +supply stays yours. + +Set ``deferrable=True`` to release the worker while Genie works. The trigger only reads the message +status; the worker fetches the answer and query results when the task resumes, so the trigger event +never carries Genie output. + +.. exampleinclude:: /../../databricks/tests/system/databricks/example_databricks_genie.py + :language: python + :start-after: [START howto_operator_databricks_genie_deferrable] + :end-before: [END howto_operator_databricks_genie_deferrable] + +``timeout`` limits how long one try waits for the answer. Timing out does not cancel the message. + +Retries and resuming +-------------------- + +On Airflow 3.3 and later the operator is durable by default. It stores the conversation and message +IDs in the task state store before it waits, so a retry after a worker crash, a timeout or a failed +trigger reconnects to the same message instead of asking again: + +* A message that is still running is awaited again. +* A completed message returns its answer without asking again. +* A message that failed, was cancelled or whose result expired is asked again in a new message. +* A stored message that no longer exists, or that was asked for a different space, conversation or + question, is asked again. + +Set ``durable=False`` to ask again on every try. On Airflow versions before 3.3 there is no task state +store, so every try asks again; the operator logs the IDs right after it submits the question so you +can attach to the message by hand. + +Genie's start-conversation and create-message APIs have no idempotency key. When Databricks does not +confirm a submission (a timeout, a connection error, a 5xx response, or a response without IDs) the +message may or may not exist, and listing the conversation cannot reliably tell. The operator then fails +with ``AirflowFailException`` instead of retrying, and while the durable state remembers that unconfirmed +submission the next try refuses to ask again. Inspect the Genie space, then either: + +* set ``conversation_id`` and ``message_id`` to attach to the message you found; the operator waits for + it and returns its answer without asking, or +* set ``resubmit_unconfirmed=True`` to accept that the question may be asked twice. + +A request that Databricks rejects with a 4xx response created nothing, so Airflow's normal retries +apply to it. + +Cancellation +------------ + +Genie has no API to cancel a chat message, so killing or timing out the task leaves the message +running in Databricks. The next try reconnects to it. Review Comment: Qualified in 6d06c6be02. The docs, the `timeout` docstring and the class docstring now say a retry reconnects only with durable execution, and asks again with `durable=False` or on Airflow before 3.3. Both error messages now describe what the next try will actually do, with tests for each case. ########## providers/databricks/docs/operators/genie_operator.rst: ########## @@ -0,0 +1,84 @@ + .. 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. + + + +.. _howto/operator:DatabricksGenieOperator: + +Ask a Databricks Genie space +============================ + +Use :class:`~airflow.providers.databricks.operators.genie.DatabricksGenieOperator` to ask a Genie space +one question as a standalone task. The operator returns the same bounded result as +:ref:`DatabricksGenieHook <howto/databricks-genie>` through XCom: the space, conversation and message +IDs, the message status, the text answer, generated queries and capped query results. + +.. exampleinclude:: /../../databricks/tests/system/databricks/example_databricks_genie.py + :language: python + :start-after: [START howto_operator_databricks_genie] + :end-before: [END howto_operator_databricks_genie] + +By default the operator starts a new conversation. Set ``conversation_id`` to ask a follow-up in an +existing conversation. The operator never deletes or cancels conversations, so a conversation you +supply stays yours. + +Set ``deferrable=True`` to release the worker while Genie works. The trigger only reads the message +status; the worker fetches the answer and query results when the task resumes, so the trigger event +never carries Genie output. + +.. exampleinclude:: /../../databricks/tests/system/databricks/example_databricks_genie.py + :language: python + :start-after: [START howto_operator_databricks_genie_deferrable] + :end-before: [END howto_operator_databricks_genie_deferrable] + +``timeout`` limits how long one try waits for the answer. Timing out does not cancel the message. + +Retries and resuming Review Comment: Done in 6d06c6be02. The section is now "Durable execution" and links the task state store and the resumable tasks concept page, matching run_now and submit_run. ########## providers/databricks/docs/operators/genie_operator.rst: ########## @@ -0,0 +1,84 @@ + .. 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. + + + +.. _howto/operator:DatabricksGenieOperator: + +Ask a Databricks Genie space +============================ + +Use :class:`~airflow.providers.databricks.operators.genie.DatabricksGenieOperator` to ask a Genie space +one question as a standalone task. The operator returns the same bounded result as +:ref:`DatabricksGenieHook <howto/databricks-genie>` through XCom: the space, conversation and message +IDs, the message status, the text answer, generated queries and capped query results. + +.. exampleinclude:: /../../databricks/tests/system/databricks/example_databricks_genie.py + :language: python + :start-after: [START howto_operator_databricks_genie] + :end-before: [END howto_operator_databricks_genie] + +By default the operator starts a new conversation. Set ``conversation_id`` to ask a follow-up in an +existing conversation. The operator never deletes or cancels conversations, so a conversation you +supply stays yours. + +Set ``deferrable=True`` to release the worker while Genie works. The trigger only reads the message +status; the worker fetches the answer and query results when the task resumes, so the trigger event +never carries Genie output. + +.. exampleinclude:: /../../databricks/tests/system/databricks/example_databricks_genie.py + :language: python + :start-after: [START howto_operator_databricks_genie_deferrable] + :end-before: [END howto_operator_databricks_genie_deferrable] + +``timeout`` limits how long one try waits for the answer. Timing out does not cancel the message. + +Retries and resuming +-------------------- + +On Airflow 3.3 and later the operator is durable by default. It stores the conversation and message +IDs in the task state store before it waits, so a retry after a worker crash, a timeout or a failed +trigger reconnects to the same message instead of asking again: + +* A message that is still running is awaited again. +* A completed message returns its answer without asking again. +* A message that failed, was cancelled or whose result expired is asked again in a new message. +* A stored message that no longer exists, or that was asked for a different space, conversation or Review Comment: Documented in 6d06c6be02. The docs now explain that Genie may answer 403 for a missing message, that only 404 counts as missing, and how to recover: check the connection's access, then attach with `conversation_id` and `message_id` or run once with `durable=False`. A new DAG run is unaffected. ########## providers/databricks/docs/operators/genie.rst: ########## @@ -0,0 +1,66 @@ + .. 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. + +.. _howto/databricks-genie: + +Databricks Genie consultations +============================== + +The ``DatabricksGenieHook`` submits a question to a Genie space, waits for the message to finish, +and returns a bounded result with the space, conversation, and message IDs. It uses the +credentials in an Airflow ``databricks`` connection and implements Common AI's public +``BaseManagedAgentHook`` contract. + +Install the optional Common AI integration when using its managed-agent toolset: + +.. code-block:: bash + + pip install 'apache-airflow-providers-databricks[common.ai]' + +.. code-block:: python + + from airflow.providers.common.ai.toolsets import ManagedAgentToolset + from airflow.providers.databricks.hooks.genie import DatabricksGenieHook + + hook = DatabricksGenieHook(databricks_conn_id="databricks_analytics") + toolset = ManagedAgentToolset( + hook.agent("your-genie-space-id"), + tool_name="ask_analytics_genie", + description="Answers questions about the analytics tables in this Genie space.", + max_retries=0, + ) + +The hook can also be called directly without Common AI: + +.. code-block:: python + + result = hook.consult("your-genie-space-id", "How many orders were placed last week?") + +The result contains IDs and structured answer, generated query, and query-result fields. Large +responses are capped. A request that starts a conversation or posts a message is sent once; after +a timeout or server failure its outcome may be unknown, so inspect the conversation before +submitting again. Message and query-result reads may be retried. A 403 can mean either that access +was denied or that the resource is missing, because Genie may conceal missing resources this way. + +Genie MCP through Unity Gateway is enough when an external model or MCP client should discover and +call Genie directly through the organization's governed MCP endpoint. The native Databricks API +integration is useful when an Airflow-managed agent needs Genie as a typed tool backed by an Airflow +Databricks connection, and when the caller needs the Genie space/conversation/message IDs and +bounded query results in its response. Both paths still enforce Genie and Unity Catalog permissions. + +This hook handles consultations only. Resuming a consultation through a standalone Airflow task +across worker failure is a separate feature and is not provided here. Review Comment: Updated in 6d06c6be02. genie.rst now points to DatabricksGenieOperator and its guide for running Genie as a task that reconnects after a worker failure. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
