|
13 | 13 | # limitations under the License. |
14 | 14 | # |
15 | 15 | import base64 |
| 16 | +import contextlib |
16 | 17 | import importlib |
17 | 18 | import json |
| 19 | +import logging |
18 | 20 | import os |
19 | 21 | import re |
20 | 22 | import sys |
|
37 | 39 | from google.cloud.aiplatform_v1.services import reasoning_engine_service |
38 | 40 | from agentplatform._genai import runtimes |
39 | 41 | from agentplatform._genai import _runtimes_utils |
| 42 | +from agentplatform import ( |
| 43 | + version as agentplatform_version, |
| 44 | +) |
40 | 45 | from agentplatform.frameworks import ( |
41 | 46 | adk as adk_template, |
42 | 47 | ) |
|
48 | 53 | from google.adk.plugins.base_plugin import BasePlugin |
49 | 54 | from google.adk.sessions.base_session_service import BaseSessionService |
50 | 55 |
|
51 | | - |
52 | 56 | try: |
53 | 57 | from google.adk.agents import llm_agent |
54 | 58 |
|
@@ -419,6 +423,32 @@ async def before_run_callback(self, *, invocation_context): |
419 | 423 | ) |
420 | 424 |
|
421 | 425 |
|
| 426 | +@contextlib.contextmanager |
| 427 | +def _mask_missing_aiplatform(): |
| 428 | + """Simulates standalone google-cloud-agentplatform without aiplatform.""" |
| 429 | + # pylint: disable=protected-access |
| 430 | + aiplatform_pkg = aiplatform.__name__ |
| 431 | + missing_modules = { |
| 432 | + aiplatform_pkg: None, |
| 433 | + f"{aiplatform_pkg}.base": None, |
| 434 | + f"{aiplatform_pkg}.utils": None, |
| 435 | + f"{aiplatform_pkg}.utils.resource_manager_utils": None, |
| 436 | + f"{aiplatform_pkg}.version": None, |
| 437 | + } |
| 438 | + sentinel = object() |
| 439 | + saved_logger = getattr(adk_template._warn, "_LOGGER", sentinel) |
| 440 | + if saved_logger is not sentinel: |
| 441 | + delattr(adk_template._warn, "_LOGGER") |
| 442 | + try: |
| 443 | + with mock.patch.dict(sys.modules, missing_modules): |
| 444 | + yield |
| 445 | + finally: |
| 446 | + if hasattr(adk_template._warn, "_LOGGER"): |
| 447 | + delattr(adk_template._warn, "_LOGGER") |
| 448 | + if saved_logger is not sentinel: |
| 449 | + adk_template._warn._LOGGER = saved_logger |
| 450 | + |
| 451 | + |
422 | 452 | @pytest.mark.usefixtures("google_auth_mock") |
423 | 453 | class TestAdkApp: |
424 | 454 | def test_adk_version(self): |
@@ -1768,19 +1798,169 @@ def test_project_id_fails_open_on_lookup_error( |
1768 | 1798 | assert app._get_project_id(_TEST_PROJECT_NUMBER) == _TEST_PROJECT_NUMBER |
1769 | 1799 | get_project_id_mock.assert_called_once_with(_TEST_PROJECT_NUMBER) |
1770 | 1800 |
|
1771 | | - def test_project_id_fails_open_when_lookup_module_is_missing(self): |
1772 | | - """b/579673015: google-cloud-aiplatform is not installed. |
1773 | | -
|
1774 | | - The failed import used to leave `exceptions` unbound, so the except |
1775 | | - clause itself raised UnboundLocalError and set_up() failed. |
1776 | | - """ |
| 1801 | + def test_project_id_fails_open_when_lookup_module_is_missing(self, caplog): |
| 1802 | + """Fails open when google-cloud-aiplatform is not installed.""" |
| 1803 | + # pylint: disable=protected-access |
1777 | 1804 | app = adk_template.AdkApp(agent=_TEST_AGENT) |
1778 | | - with mock.patch.dict( |
1779 | | - sys.modules, {"google.cloud.aiplatform.aiplatform.utils": None} |
1780 | | - ): |
1781 | | - assert ( |
1782 | | - app._get_project_id(_TEST_PROJECT_NUMBER) == _TEST_PROJECT_NUMBER |
| 1805 | + with _mask_missing_aiplatform(): |
| 1806 | + with caplog.at_level(logging.WARNING, logger=adk_template.__name__): |
| 1807 | + project_id = app._get_project_id(_TEST_PROJECT_NUMBER) |
| 1808 | + assert project_id == _TEST_PROJECT_NUMBER |
| 1809 | + expected_msg = "Failed to convert project number to project ID" |
| 1810 | + assert expected_msg in caplog.text |
| 1811 | + |
| 1812 | + def test_warn_falls_back_when_aiplatform_is_missing(self, caplog): |
| 1813 | + """Verifies _warn falls back to stdlib logging without aiplatform.""" |
| 1814 | + # pylint: disable=protected-access |
| 1815 | + with _mask_missing_aiplatform(): |
| 1816 | + with caplog.at_level(logging.WARNING, logger=adk_template.__name__): |
| 1817 | + adk_template._warn("standalone warning") |
| 1818 | + assert adk_template._warn._LOGGER is logging.getLogger( |
| 1819 | + adk_template.__name__ |
| 1820 | + ) |
| 1821 | + assert "standalone warning" in caplog.text |
| 1822 | + |
| 1823 | + @pytest.mark.parametrize("mask_log_exporter", [False, True]) |
| 1824 | + def test_set_up_with_telemetry_when_aiplatform_is_missing( |
| 1825 | + self, caplog, mask_log_exporter: bool |
| 1826 | + ): |
| 1827 | + """Verifies cold-start set_up() with telemetry and no aiplatform.""" |
| 1828 | + # pylint: disable=g-import-not-at-top,protected-access |
| 1829 | + import opentelemetry._logs |
| 1830 | + import opentelemetry.sdk.trace |
| 1831 | + import opentelemetry.trace |
| 1832 | + |
| 1833 | + tracer_provider = opentelemetry.trace.get_tracer_provider() |
| 1834 | + original_span_processor = getattr( |
| 1835 | + tracer_provider, "_active_span_processor", None |
| 1836 | + ) |
| 1837 | + if original_span_processor is not None: |
| 1838 | + tracer_provider._active_span_processor = ( |
| 1839 | + opentelemetry.sdk.trace.SynchronousMultiSpanProcessor() |
1783 | 1840 | ) |
| 1841 | + original_logger_provider = getattr( |
| 1842 | + opentelemetry._logs, "_LOGGER_PROVIDER", None |
| 1843 | + ) |
| 1844 | + try: |
| 1845 | + with contextlib.ExitStack() as stack: |
| 1846 | + if mask_log_exporter: |
| 1847 | + stack.enter_context( |
| 1848 | + mock.patch.dict( |
| 1849 | + sys.modules, |
| 1850 | + { |
| 1851 | + "opentelemetry.exporter.otlp.proto.http" |
| 1852 | + "._log_exporter": None |
| 1853 | + }, |
| 1854 | + ) |
| 1855 | + ) |
| 1856 | + try: |
| 1857 | + log_exporter_mod = importlib.import_module( |
| 1858 | + "opentelemetry.exporter.otlp.proto.http._log_exporter" |
| 1859 | + ) |
| 1860 | + except ImportError: |
| 1861 | + log_exporter_mod = None |
| 1862 | + stack.enter_context(_mask_missing_aiplatform()) |
| 1863 | + stack.enter_context( |
| 1864 | + mock.patch.dict( |
| 1865 | + os.environ, |
| 1866 | + { |
| 1867 | + "GOOGLE_CLOUD_PROJECT": _TEST_PROJECT_NUMBER, |
| 1868 | + GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY: "true", |
| 1869 | + }, |
| 1870 | + ) |
| 1871 | + ) |
| 1872 | + stack.enter_context( |
| 1873 | + mock.patch.object( |
| 1874 | + adk_template, |
| 1875 | + "_use_client_cert_effective", |
| 1876 | + return_value=False, |
| 1877 | + ) |
| 1878 | + ) |
| 1879 | + stack.enter_context( |
| 1880 | + mock.patch.object( |
| 1881 | + adk_template.requests_auth, |
| 1882 | + "AuthorizedSession", |
| 1883 | + ) |
| 1884 | + ) |
| 1885 | + mock_span_exporter = stack.enter_context( |
| 1886 | + mock.patch( |
| 1887 | + "opentelemetry.exporter.otlp.proto.http.trace_exporter" |
| 1888 | + ".OTLPSpanExporter" |
| 1889 | + ) |
| 1890 | + ) |
| 1891 | + mock_log_exporter = None |
| 1892 | + if log_exporter_mod is not None: |
| 1893 | + mock_log_exporter = stack.enter_context( |
| 1894 | + mock.patch.object(log_exporter_mod, "OTLPLogExporter") |
| 1895 | + ) |
| 1896 | + stack.enter_context( |
| 1897 | + caplog.at_level( |
| 1898 | + logging.WARNING, |
| 1899 | + logger=adk_template.__name__, |
| 1900 | + ) |
| 1901 | + ) |
| 1902 | + |
| 1903 | + expected_prefix = ( |
| 1904 | + f"Vertex-Agent-Engine/{agentplatform_version.__version__}" |
| 1905 | + ) |
| 1906 | + user_agent = adk_template._get_user_agent() |
| 1907 | + assert user_agent.startswith(expected_prefix) |
| 1908 | + app = adk_template.AdkApp( |
| 1909 | + agent=_TEST_AGENT, |
| 1910 | + enable_tracing=True, |
| 1911 | + ) |
| 1912 | + app.set_up() |
| 1913 | + |
| 1914 | + assert app._tmpl_attrs.get("runner") is not None |
| 1915 | + expected_msg = "Failed to convert project number to project ID" |
| 1916 | + assert expected_msg in caplog.text |
| 1917 | + mock_span_exporter.assert_called_once() |
| 1918 | + assert mock_span_exporter.call_args.kwargs["headers"][ |
| 1919 | + "User-Agent" |
| 1920 | + ].startswith(expected_prefix) |
| 1921 | + if mock_log_exporter is not None: |
| 1922 | + mock_log_exporter.assert_called_once() |
| 1923 | + assert mock_log_exporter.call_args.kwargs["headers"][ |
| 1924 | + "User-Agent" |
| 1925 | + ].startswith(expected_prefix) |
| 1926 | + finally: |
| 1927 | + opentelemetry.trace._TRACER_PROVIDER = None |
| 1928 | + if original_span_processor is not None: |
| 1929 | + tracer_provider._active_span_processor = original_span_processor |
| 1930 | + opentelemetry._logs._LOGGER_PROVIDER = original_logger_provider |
| 1931 | + |
| 1932 | + @pytest.mark.asyncio |
| 1933 | + async def test_save_artifacts_when_aiplatform_is_missing(self, caplog): |
| 1934 | + """Verifies _save_artifacts falls back when aiplatform is absent.""" |
| 1935 | + # pylint: disable=protected-access |
| 1936 | + app = adk_template.AdkApp(agent=_TEST_AGENT, app_name="test-app") |
| 1937 | + artifact_service = mock.AsyncMock() |
| 1938 | + artifact_service.save_artifact.return_value = 2 |
| 1939 | + part = types.Part(text="hello") |
| 1940 | + request = adk_template._StreamRunRequest( |
| 1941 | + user_id=_TEST_USER_ID, |
| 1942 | + artifacts=[ |
| 1943 | + { |
| 1944 | + "file_name": "note.txt", |
| 1945 | + "versions": [ |
| 1946 | + { |
| 1947 | + "version": 1, |
| 1948 | + "data": part, |
| 1949 | + } |
| 1950 | + ], |
| 1951 | + } |
| 1952 | + ], |
| 1953 | + ) |
| 1954 | + with _mask_missing_aiplatform(): |
| 1955 | + with caplog.at_level(logging.DEBUG, logger=adk_template.__name__): |
| 1956 | + await app._save_artifacts( |
| 1957 | + "session-1", |
| 1958 | + artifact_service, |
| 1959 | + request, |
| 1960 | + ) |
| 1961 | + artifact_service.save_artifact.assert_awaited_once() |
| 1962 | + expected_debug = "Artifact 'note.txt' saved at version 2 instead of 1" |
| 1963 | + assert expected_debug in caplog.text |
1784 | 1964 |
|
1785 | 1965 | @pytest.mark.usefixtures("caplog") |
1786 | 1966 | def test_enable_tracing( |
|
0 commit comments